diff --git a/example/test.ts b/example/test.ts index 734f4b3..c486b9d 100644 --- a/example/test.ts +++ b/example/test.ts @@ -3,9 +3,13 @@ import { HTTPServer } from "../mod.ts"; const httpServer = new HTTPServer(); -httpServer.middleware((req) => { +httpServer.middleware(async (req, done) => { + const started = Date.now(); console.log(`${req.method} - ${req.ip()} - ${req.path}`); -}) + await done(); + const processTime = Date.now() - started; + console.log(`Processed in ${processTime}ms`); +}); httpServer.error((req, _rep) => { return JSON.stringify( diff --git a/mod.ts b/mod.ts index d54bb12..8a19a59 100644 --- a/mod.ts +++ b/mod.ts @@ -19,10 +19,14 @@ type RouteHandler = ( | Promise | unknown; -type RouteMiddlewareHandler = (req: RouteRequest) => +type RouteMiddlewareHandler = ( + req: RouteRequest, + done: () => Promise, +) => | Promise | void; -export type RouteParam = { + +type RouteParam = { idx: number; paramKey: string; }; @@ -105,9 +109,16 @@ export class HTTPServer { this.handleNotFound(routeRequest, routeReply, requestEvent); continue; } + let resolveAction: (value?: unknown) => void = () => {}; + let middlewarePromise; if (this.middlewareHandler) { - this.middlewareHandler(routeRequest); + middlewarePromise = (): Promise => { + return new Promise((resolve) => { + resolveAction = resolve; + }); + }; + this.middlewareHandler(routeRequest, middlewarePromise); } if (this.staticServePath && filepath.startsWith(this.staticServePath)) { @@ -122,12 +133,14 @@ export class HTTPServer { file = await Deno.open(pathLoc, { read: true }); } catch { this.handleNotFound(routeRequest, routeReply, requestEvent); + if (middlewarePromise) resolveAction(); continue; } const readableStream = file.readable; const response = new Response(readableStream); await requestEvent.respondWith(response); + if (middlewarePromise) resolveAction(); return; } const routeName = `${requestEvent.request.method}@${filepath}`; @@ -152,6 +165,7 @@ export class HTTPServer { statusText: STATUS_TEXT[routeReply.statusCode], }), ); + if (middlewarePromise) resolveAction(); continue; } @@ -183,9 +197,11 @@ export class HTTPServer { statusText: STATUS_TEXT[routeReply.statusCode], }), ); + if (middlewarePromise) resolveAction(); continue; } this.handleNotFound(routeRequest, routeReply, requestEvent); + if (middlewarePromise) resolveAction(); } }