UNPKG

f2e-server3

Version:

f2e-server 3.0

113 lines (112 loc) 4.07 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Route = void 0; const misc_1 = require("../utils/misc"); const resp_1 = require("../utils/resp"); const utils_1 = require("../utils"); class Route { routes = []; route_map = new Map(); options; respUtils; filter; constructor(options, filter) { this.options = options; this.respUtils = (0, resp_1.createResponseHelper)(options); this.filter = filter; } find(path, method = '*') { return this.routes.find(r => { if (r.method?.toUpperCase() === method.toUpperCase() || r.method === '*') { return typeof r.path === 'string' ? r.path === path : r.path.test(path); } else { return false; } }); } on = (path, handler, ext) => { this.routes.push({ path: typeof path === 'string' ? (0, misc_1.pathname_fixer)(path) : path, handler, method: '*', ...(ext || {}), }); }; match = (path, method = '*') => { let item = this.route_map.get(path + ':' + method) || this.route_map.get(path + ':*'); if (item) { return item; } item = this.find(path, method); if (item) { if (typeof item.path === 'string') { this.route_map.set(path + ':' + item.method, item); } return item; } return undefined; }; execute = async (pathname, ctx) => { const { handleError, handleSuccess, handleNotFound, handleSSE } = this.respUtils; const { req, resp, body, headers = {} } = ctx; if (this.filter) { const filterResult = await this.filter(pathname, ctx); if (false === filterResult) { return false; } if (typeof filterResult === 'string') { pathname = filterResult; } } let data = null; if (body && body.length > 0) { const contentType = headers['content-type'] || 'application/x-www-form-urlencoded'; try { switch (contentType) { case 'application/json': data = JSON.parse(body.toString()); break; default: data = (0, misc_1.queryparams)(body.toString()); break; } } catch (e) { utils_1.logger.error('onRoute Error:', pathname, e); } } const item = this.match(pathname, ctx.method); if (item) { try { switch (item.type || 'json') { case 'none': await item.handler(data, ctx); break; case 'json': handleSuccess(ctx, '.json', JSON.stringify(await item.handler(data, ctx))); break; case 'jsonp': const callback = req.getQuery('callback') || 'callback'; handleSuccess(ctx, '.js', `${callback}(${JSON.stringify(await item.handler(data, ctx))})`); break; case 'sse': handleSSE(ctx, item, data); break; default: const result = await item.handler(data, ctx); if (typeof result === 'undefined') { handleNotFound(resp, pathname); } else { handleSuccess(ctx, item.sourceType || 'txt', result); } break; } } catch (e) { utils_1.logger.error('onRoute Error:', pathname, e); handleError(resp, e + ''); } return false; } }; } exports.Route = Route;