@ffsm/napi
Version:
Napi - A framework using with Next.js for building APIs.
91 lines (90 loc) • 3.03 kB
JavaScript
import { matchRoute } from "./helpers/match-route";
export class NapiContext {
constructor(prefix, controller, switchInstance, routeParams = {}) {
this.prefix = prefix;
this.controller = controller;
this.switchInstance = switchInstance;
this.routeParams = routeParams;
this.decoratorParams = [];
}
getRequest() {
return this.switchInstance.getRequest();
}
getRouter() {
return this.switchInstance.getRouter();
}
getPayload() {
return this.switchInstance.getPayload();
}
getConfig(name) {
return this.switchInstance.getConfig(name);
}
getResponse() {
return this.switchInstance.getResponse();
}
getController() {
return this.controller.getInstance();
}
execute(route) {
if (!this.controller) {
throw new Error("Controller not found");
}
if (!this.findMethod(route).method) {
throw new Error("No route found");
}
return this.initDecoratorParams();
}
getMethod() {
return this.method;
}
getRouteParams() {
return this.routeParams;
}
getDecoratorParams() {
return this.decoratorParams;
}
findMethod(reqRoute) {
reqRoute = `/${reqRoute}`.replace(/\/+/g, "/");
const request = this.getRequest();
const routes = this.controller.getRoutes();
const keys = Array.from(routes.keys());
for (let index = 0; index < keys.length; index++) {
const methodName = keys[index];
const [method, ...remain] = methodName.split(":");
if (method.toUpperCase() !== request.method.toUpperCase()) {
continue;
}
const route = `/${this.prefix}/${this.controller.getPrefix()}/${remain.join(":")}`.replace(/\/+/g, "/");
const params = matchRoute(route, reqRoute);
if (!params) {
continue;
}
this.method = routes.get(methodName);
this.routeParams = params;
break;
}
return this;
}
async initDecoratorParams() {
var _a;
if (!this.method) {
return this;
}
const params = (_a = this.controller.getParams(this.method)) !== null && _a !== void 0 ? _a : [];
const indexes = params.map((param) => param.index);
indexes.push(-1);
const maxIndex = Math.max(...indexes);
const decorators = await Promise.all(params.map(async (params) => {
const result = await params.handle(params.options, this.switchInstance);
return {
index: params.index,
result,
};
}));
for (let index = 0; index <= maxIndex; index++) {
const param = decorators.find((d) => d.index === index);
this.decoratorParams.push(param === null || param === void 0 ? void 0 : param.result);
}
return this;
}
}