import _ from "lodash"; import { Router, RequestHandler, Request, Response, NextFunction } from "express"; export type HandlerFn = ( req: Request, res: Response, next: NextFunction ) => Promise; export class BaseController { router: Router; constructor() { this.router = Router(); } get(path: string, handler: HandlerFn) { this.router.get(path, this.prepareHandler(handler)); } post(path: string, handler: HandlerFn) { this.router.post(path, this.prepareHandler(handler)); } use(path: string, handler: HandlerFn) { this.router.use(path, this.prepareHandler(handler)); } prepareHandler(handler: HandlerFn): RequestHandler { handler = handler.bind(this); return async (req: Request, res: Response, next: NextFunction) => { try { const result = await handler(req, res, next); if (_.isObject(result)) { return res.json(result); } else if (result !== undefined) { return res.end(result); } return null; } catch (err: any) { next(err); } }; } }