Last active
October 9, 2019 09:14
-
-
Save alexpermiakov/0a627475c8dcfe92520525446efaa1da to your computer and use it in GitHub Desktop.
Applies routes
This file contains 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 { Router, Request, Response, NextFunction } from "express"; | |
type Wrapper = ((router: Router) => void); | |
export const applyMiddleware = ( | |
middlewareWrappers: Wrapper[], | |
router: Router | |
) => { | |
for (const wrapper of middlewareWrappers) { | |
wrapper(router); | |
} | |
}; | |
type Handler = ( | |
req: Request, | |
res: Response, | |
next: NextFunction | |
) => Promise<void> | void; | |
type Route = { | |
path: string; | |
method: string; | |
handler: Handler | Handler[]; | |
}; | |
export const applyRoutes = (routes: Route[], router: Router) => { | |
for (const route of routes) { | |
const { method, path, handler } = route; | |
(router as any)[method](path, handler); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for your great post!
Improvement: You can avoid casting the router to
any
if you make the methods explicit, e.g. (using all available routes types in the docs),