Skip to content

Instantly share code, notes, and snippets.

@Curtis017
Created March 8, 2019 03:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save Curtis017/ce072208f5160e8c24b77cc662f10fec to your computer and use it in GitHub Desktop.
Save Curtis017/ce072208f5160e8c24b77cc662f10fec to your computer and use it in GitHub Desktop.
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