Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple middleware implementation using typescript and ES6
import pipeline, { Middleware } from './pipeline';
const step1: Middleware<any, any> = (req, res, next) => {
if (req.body) {
console.log(`STEP 1: \n req: ${JSON.stringify(req)}\n res: ${JSON.stringify(res)}`);
next();
}
}
const step2: Middleware<any, any> = async (req, res, next) => {
await setTimeout(() => {
res.status = 200;
console.log(`STEP 2: \n req: ${JSON.stringify(req)}\n res: ${JSON.stringify(res)}`);
next();
}, 2000);
}
const step3: Middleware<any, any> = (req, res, next) => {
console.log(`STEP 3: \n req: ${JSON.stringify(req)}\n res: ${JSON.stringify(res)}`);
next();
}
const req = { body: {}};
const res = {};
pipeline(req, res, step1, step2, step3);
export type Middleware<T, P> = (req: T, res: P, next: () => void) => any;
const pipeline = (req: any, res: any, ...steps: Middleware<any, any>[]) => {
const [ step, ...next ] = steps;
return (step) ? step(req, res, () => pipeline(req, res, ...next)) : undefined;
}
export default pipeline;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment