import { Method, Routes } from '@rondo.dev/http-types' import express from 'express' import { TypedHandler, TypedMiddleware } from './TypedHandler' 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, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { if (handlers.length === 2) { const middleware = handlers[0] const handler = handlers[1] this.router[method](path, ...middleware, this.wrapHandler(handler)) } else { this.router[method](path, this.wrapHandler(handlers[0])) } } protected wrapHandler( handler: TypedHandler, ): express.RequestHandler { return (req, res, next) => { handler(req, res, next) .then(response => { res.json(response) }) .catch(next) } } get

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ): void { this.addRoute('get', path, ...handlers) } post

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { this.addRoute('post', path, ...handlers) } put

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { this.addRoute('put', path, ...handlers) } delete

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { this.addRoute('delete', path, ...handlers) } head

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { this.addRoute('head', path, ...handlers) } options

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { this.addRoute('options', path, ...handlers) } patch

( path: P, ...handlers: [TypedHandler] | [ Array>, TypedHandler, ] ) { this.addRoute('patch', path, ...handlers) } }