Skip to content

Instantly share code, notes, and snippets.

@zazaulola
Last active September 8, 2021 01:38
Show Gist options
  • Save zazaulola/95ee1f1d1b14597db93d4cc549eac7cb to your computer and use it in GitHub Desktop.
Save zazaulola/95ee1f1d1b14597db93d4cc549eac7cb to your computer and use it in GitHub Desktop.
Primitive middleware router with timeout detection
const stepTimeout = 505;
const Router = (...chain) =>
Object.assign(
async (ctx) => {
await (async function run(idx) {
if ("function" == typeof chain[idx]) {
await new Promise((res, rej) => {
const to = setTimeout(
() => rej(new Error(`Step [${idx}] timeout on \n${chain[idx]}`)),
stepTimeout
);
chain[idx](ctx, () => {
clearTimeout(to);
res();
});
});
await run(idx + 1);
}
})(0);
},
{ use: (...mws) => chain.push(...mws) }
);
let router = Router();
router.use((ctx, next) => {
console.log(1);
ctx.x++;
next();
});
router.use((ctx, next) => {
console.log(2);
ctx.x++;
next();
});
router.use((ctx, next) => {
console.log(3);
ctx.x++;
next();
setTimeout(() => next(), 1000);
});
router.use((ctx, next) => {
console.log(4);
ctx.x++;
setTimeout(() => next(), 500);
});
router.use((ctx, next) => {
console.log(5);
ctx.x++;
next();
next();
});
router.use((ctx, next) => {
console.log(6);
ctx.x++;
next();
});
(async () => {
let ctx = { x: 0 };
try {
await router(ctx);
} catch (e) {
console.error(e);
}
console.log("End");
console.log("x=", ctx.x, "ctx=", ctx);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment