UNPKG

@anyhowstep/ts-route-server

Version:

100 lines (95 loc) 3.58 kB
import * as express from "express"; import * as core from "express-serve-static-core"; import {Handler} from "./Handler"; import {HandlerMiddleware} from "./HandlerMiddleware"; import {Route} from "./Route"; import {SchemaMiddleware} from "./SchemaMiddleware"; import * as TsRouteShared from "@anyhowstep/ts-route-shared"; import {ErrorMiddleware} from "@anyhowstep/error-middleware"; export class Router<L={_dummy:undefined}> { private raw : core.Router; public constructor (raw : core.Router=express.Router()) { this.raw = raw; } public getRaw () { return this.raw; } public use<N> (handler : Handler<{}, {}, {}, {}, {}, L, N>) : Router<L & N> { this.raw.use(HandlerMiddleware.Create(handler)); return this as any; } private addRoute<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>, matcher : express.IRouterMatcher<core.Router>) { const definition = route.getDefinition(); const handlerArr = route.getHandlerArr(); matcher = matcher.bind(this.raw); matcher( definition.pathBuilder.getPath(), ErrorMiddleware.Watch(), SchemaMiddleware.Create("query", (req) => req.query, definition.querySchema), SchemaMiddleware.Create("body" , (req) => req.body , definition.bodySchema), (_req : express.Request, res : express.Response, next : express.NextFunction) => { (res as any).respond = (arg : TsRouteShared.Response<D, M>|Error|Error[]) => { return res.json(arg); }; next(); }, [...handlerArr], ErrorMiddleware.WatchUncaught() ); } public all<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.all); } public get<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.get); } public put<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.put); } public post<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.post); } public delete<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.delete); } public patch<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.patch); } public options<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.options); } public head<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.raw.head); } public getMatcher (method : TsRouteShared.Method) : express.IRouterMatcher<core.Router> { switch (method) { case "GET": { return this.raw.get; } case "PUT": { return this.raw.put; } case "POST": { return this.raw.post; } case "DELETE": { return this.raw.delete; } case "PATCH": { return this.raw.patch; } case "OPTIONS": { return this.raw.options; } case "HEAD": { return this.raw.head; } default: { return this.raw.all; } } } public add<P, B, Q, D, M> (route : Route<P, B, Q, D, M, L>) { this.addRoute(route, this.getMatcher(route.getDefinition().method)); } }