Created
March 8, 2019 03:29
-
-
Save Curtis017/ce072208f5160e8c24b77cc662f10fec to your computer and use it in GitHub Desktop.
Simple middleware implementation using typescript and ES6
This file contains hidden or 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
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); |
This file contains hidden or 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
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