Skip to content

Instantly share code, notes, and snippets.

@VldMrgnn
Created August 8, 2024 18:49
Show Gist options
  • Save VldMrgnn/4d99bc1b3c6543234fb51296401cfc11 to your computer and use it in GitHub Desktop.
Save VldMrgnn/4d99bc1b3c6543234fb51296401cfc11 to your computer and use it in GitHub Desktop.
starfx apis example
import { createApi, createThunks, Err, mdw, Ok, put, sleep, spawn, take } from 'starfx';
import { service } from '@app/service/delphiService';
import { schema } from './schema';
import { mainWorker } from './workers/workerApi';
import type { Next, ApiCtx, Result } from 'starfx';
import type { ThunkCtx } from '@app/types';
export const xApi = createApi<ApiCtx>();
xApi.use(mdw.err);
xApi.use(mdw.api({ schema }));
xApi.use(xApi.routes());
xApi.use(mdw.queryCtx);
xApi.use(mdw.nameParser);
xApi.use(mdw.fetch({ baseUrl: service }));
export const xThunk = createThunks<ThunkCtx>();
xThunk.use(function* (ctx: ThunkCtx, next: Next) {
console.log('ctx', ctx.key);
yield* next();
console.log('done ctx', ctx.key);
});
xThunk.use(mdw.err);
xThunk.use(mdw.actions);
xThunk.use(xThunk.routes());
function* waitMdw(ctx: ApiCtx, next: Next) {
yield* spawn(function* () {
if (!['/get-wait', '/wait'].some((x) => ctx.key.startsWith(x))) {
yield* sleep(1);
ctx.json = Ok('posted');
} else {
yield* sleep(8000);
ctx.json = Err(new Error('timeout'));
}
yield* put({ type: `/bailout${ctx.key}` });
});
yield* next();
while (true) {
const workerResult = yield* take([
`/wresult${ctx.key}`,
`/bailout${ctx.key}`,
]);
console.log('workerResult', workerResult);
if (workerResult.type === `/wresult${ctx.key}`) {
ctx.json = workerResult.payload as Result<any>;
}
break;
}
}
export const xWorker = createApi<ApiCtx>();
xWorker.use(mdw.err);
xWorker.use(mdw.api({ schema }));
xWorker.use(xWorker.routes());
xWorker.use(mdw.queryCtx);
xWorker.use(mdw.nameParser);
xWorker.use(mainWorker);
xWorker.use(waitMdw);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment