add done promise for middleware
This commit is contained in:
parent
b974abff1b
commit
10fb61793f
|
@ -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(
|
||||
|
|
22
mod.ts
22
mod.ts
|
@ -19,10 +19,14 @@ type RouteHandler = (
|
|||
| Promise<unknown>
|
||||
| unknown;
|
||||
|
||||
type RouteMiddlewareHandler = (req: RouteRequest) =>
|
||||
type RouteMiddlewareHandler = (
|
||||
req: RouteRequest,
|
||||
done: () => Promise<unknown>,
|
||||
) =>
|
||||
| Promise<void>
|
||||
| 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<unknown> => {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Reference in New Issue
Block a user