UNPKG

@kadena/hardhat-chainweb

Version:
61 lines 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Router = void 0; const path_to_regexp_1 = require("path-to-regexp"); class Router { constructor() { this.routes = new Map(); } route(route, handler, validate = (params) => { return Object.values(params).every((v) => typeof v === 'string'); }) { this.routes.set(route, { handler, validate }); } async execute(url, next, context, tag) { if (url === undefined) { next.failure('No route found', 404); return; } for (const [route, { handler, validate }] of this.routes.entries()) { const matchRoute = (0, path_to_regexp_1.match)(route); const matched = matchRoute(url); if (matched && validate(matched.params)) { console.log(`[${tag}]`, matched.path); try { const result = await handler(matched.params, { success: (msg, mimeType) => ({ type: 'success', result: { msg, mimeType }, }), failure: (msg, code) => ({ type: 'failure', error: { msg, code }, }), proxy: (handler) => ({ type: 'proxy', handler, }), }, context); switch (result === null || result === void 0 ? void 0 : result.type) { case 'success': return next.success(result.result.msg, result.result.mimeType); case 'failure': return next.failure(result.error.msg, result.error.code); case 'proxy': return next.proxy(result.handler); default: console.error('the handler must return a valid result ("success" | "failure" | "proxy")'); return next.failure('Invalid handler result', 500); } } catch (e) { console.error(e); return next.failure('Internal server error', 500); } } } next.failure(`NOT FOUND: ${url}`, 404); } } exports.Router = Router; //# sourceMappingURL=Route.js.map