UNPKG

@anyhowstep/ts-route-server

Version:

86 lines 2.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const express = require("express"); const HandlerMiddleware_1 = require("./HandlerMiddleware"); const SchemaMiddleware_1 = require("./SchemaMiddleware"); const error_middleware_1 = require("@anyhowstep/error-middleware"); class Router { constructor(raw = express.Router()) { this.raw = raw; } getRaw() { return this.raw; } use(handler) { this.raw.use(HandlerMiddleware_1.HandlerMiddleware.Create(handler)); return this; } addRoute(route, matcher) { const definition = route.getDefinition(); const handlerArr = route.getHandlerArr(); matcher = matcher.bind(this.raw); matcher(definition.pathBuilder.getPath(), error_middleware_1.ErrorMiddleware.Watch(), SchemaMiddleware_1.SchemaMiddleware.Create("query", (req) => req.query, definition.querySchema), SchemaMiddleware_1.SchemaMiddleware.Create("body", (req) => req.body, definition.bodySchema), (_req, res, next) => { res.respond = (arg) => { return res.json(arg); }; next(); }, [...handlerArr], error_middleware_1.ErrorMiddleware.WatchUncaught()); } all(route) { this.addRoute(route, this.raw.all); } get(route) { this.addRoute(route, this.raw.get); } put(route) { this.addRoute(route, this.raw.put); } post(route) { this.addRoute(route, this.raw.post); } delete(route) { this.addRoute(route, this.raw.delete); } patch(route) { this.addRoute(route, this.raw.patch); } options(route) { this.addRoute(route, this.raw.options); } head(route) { this.addRoute(route, this.raw.head); } getMatcher(method) { 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; } } } add(route) { this.addRoute(route, this.getMatcher(route.getDefinition().method)); } } exports.Router = Router; //# sourceMappingURL=Router.js.map