import express from 'express' import {IRoutes, IMethod} from '@rondo/common' import {ITypedHandler} from './ITypedHandler' export class AsyncRouter { readonly router: express.Router readonly use: express.IRouterHandler & express.IRouterMatcher constructor(router?: express.Application | express.Router) { this.router = router ? router : express.Router() this.use = this.router.use.bind(this.router) as any } protected addRoute( method: M, path: P, handler: ITypedHandler, ) { const addRoute = this.router[method].bind(this.router) addRoute(path, this.wrapHandler(handler)) } protected wrapHandler( handler: ITypedHandler, ): express.RequestHandler { return (req, res, next) => { handler(req, res, next) .then(response => { res.json(response) }) .catch(next) } } get

( path: P, handler: ITypedHandler, ) { this.addRoute('get', path, handler) } post

( path: P, handler: ITypedHandler, ) { this.addRoute('post', path, handler) } put

( path: P, handler: ITypedHandler, ) { this.addRoute('put', path, handler) } delete

( path: P, handler: ITypedHandler) { this.addRoute('delete', path, handler) } head

( path: P, handler: ITypedHandler, ) { this.addRoute('head', path, handler) } options

( path: P, handler: ITypedHandler) { this.addRoute('options', path, handler) } patch

( path: P, handler: ITypedHandler) { this.addRoute('patch', path, handler) } }