Clean up how route handlers are called
This commit is contained in:
60
deno/app.ts
60
deno/app.ts
@@ -1,39 +1,75 @@
|
||||
import { services } from "./services.ts";
|
||||
import {
|
||||
DenoRequest,
|
||||
massageMethod,DenoResponse,
|
||||
DenoResponse,
|
||||
InternalHandler,
|
||||
massageMethod,
|
||||
Method,
|
||||
ProcessedRoute,
|
||||
Request,
|
||||
Request as Request,
|
||||
Route,
|
||||
} from "./types.ts";
|
||||
|
||||
import { routes } from "./routes.ts";
|
||||
|
||||
services.logging.log({ source: "logging", text: ["1"] });
|
||||
const processedRoutes: ProcessedRoute[] = routes.map(
|
||||
const processedRoutes: { [K in Method]: ProcessedRoute[] } = {
|
||||
"GET": [],
|
||||
"POST": [],
|
||||
"PUT": [],
|
||||
"PATCH": [],
|
||||
"DELETE": [],
|
||||
};
|
||||
|
||||
function isPromise<T>(value: T | Promise<T>): value is Promise<T> {
|
||||
return typeof (value as any)?.then === "function";
|
||||
}
|
||||
|
||||
routes.forEach(
|
||||
(route: Route, _idx: number, _allRoutes: Route[]) => {
|
||||
const pattern: URLPattern = new URLPattern({ pathname: route.path });
|
||||
const method: Method = route.method;
|
||||
const handler = async (denoRequest: DenoRequest) => {
|
||||
const methodList = route.methods;
|
||||
|
||||
const handler: InternalHandler = async (denoRequest: DenoRequest) => {
|
||||
const method = massageMethod(denoRequest.method);
|
||||
|
||||
if (!methodList.includes(method)) {
|
||||
// XXX: Worth asserting this?
|
||||
}
|
||||
|
||||
const p = new URL(denoRequest.url);
|
||||
const path = p.pathname;
|
||||
|
||||
const req: Request = {
|
||||
pattern: route.pattern,
|
||||
path: denoRequest.path,
|
||||
method: massageMethod(denoRequest.method),
|
||||
pattern: route.path,
|
||||
path,
|
||||
method,
|
||||
parameters: { one: 1, two: 2 },
|
||||
denoRequest,
|
||||
};
|
||||
return route.handler(req);
|
||||
|
||||
const retval = route.handler(req);
|
||||
if (isPromise(retval)) {
|
||||
return await retval;
|
||||
} else {
|
||||
return retval;
|
||||
}
|
||||
};
|
||||
|
||||
const retval: ProcessedRoute = { pattern, method, handler };
|
||||
for (const [_idx, method] of methodList.entries()) {
|
||||
const pr: ProcessedRoute = { pattern, method, handler };
|
||||
|
||||
return retval;
|
||||
processedRoutes[method].push(pr);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
async function handler(req: DenoRequest): Promise<DenoResponse> {
|
||||
for (const [idx, pr] of processedRoutes.entries()) {
|
||||
const m = req.method;
|
||||
const m1 = massageMethod(m);
|
||||
|
||||
const byMethod = processedRoutes[m1];
|
||||
for (const [_idx, pr] of byMethod.entries()) {
|
||||
const match = pr.pattern.exec(req.url);
|
||||
if (match) {
|
||||
const resp = await pr.handler(req);
|
||||
|
||||
Reference in New Issue
Block a user