Created
December 26, 2021 21:19
-
-
Save cihad/774f734cd599a669771e532cfa0167eb to your computer and use it in GitHub Desktop.
Javascript middleware pattern using promises, simple but powerfull
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function wrap(fn, thisCtx, ...ctx) { | |
return await new Promise(async (next, end) => { | |
next(await fn.call(thisCtx, ...ctx, next, end)) | |
}) | |
} | |
export class Middleware { | |
constructor(...middlewares) { | |
this.middlewares = middlewares | |
} | |
use(...middlewares) { | |
this.middlewares = [...this.middlewares, ...middlewares] | |
return this | |
} | |
async exec(...context) { | |
const thisCtx = {} | |
for (const fn of this.middlewares) { | |
try { | |
await wrap(fn, thisCtx, ...context) | |
} catch (err) { | |
break | |
} | |
} | |
return context | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment