Skip to content

Instantly share code, notes, and snippets.

@alexpermiakov
Last active October 9, 2019 09:14
Show Gist options
  • Save alexpermiakov/0a627475c8dcfe92520525446efaa1da to your computer and use it in GitHub Desktop.
Save alexpermiakov/0a627475c8dcfe92520525446efaa1da to your computer and use it in GitHub Desktop.
Applies routes
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);
}
};
@iamarcel
Copy link

iamarcel commented Oct 9, 2019

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),

type Route = {
  path: string;
  method: 'checkout' | 'copy' | 'delete' | 'get' | 'head' | 'lock' | 'merge' | 'mkactivity' | 'mkcol' | 'move' | 'm-search' | 'notify' | 'options' | 'patch' | 'post' | 'purge' | 'put' | 'report' | 'search' | 'subscribe' | 'trace' | 'unlock' | 'unsubscribe';
  handler: Handler | Handler[];
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment