Skip to content

Instantly share code, notes, and snippets.

@cihad
Created December 26, 2021 21:19
Show Gist options
  • Save cihad/774f734cd599a669771e532cfa0167eb to your computer and use it in GitHub Desktop.
Save cihad/774f734cd599a669771e532cfa0167eb to your computer and use it in GitHub Desktop.
Javascript middleware pattern using promises, simple but powerfull
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