Skip to content

Instantly share code, notes, and snippets.

@kindziora
Forked from Curtis017/index.ts
Created January 13, 2020 08:10
Show Gist options
  • Save kindziora/04761d99a774b057a4d6b049e8da1924 to your computer and use it in GitHub Desktop.
Save kindziora/04761d99a774b057a4d6b049e8da1924 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