From 4514a37999d41158de4b3fcbea826032e150a22f Mon Sep 17 00:00:00 2001 From: Flummi Date: Sat, 15 Mar 2025 22:45:13 +0100 Subject: [PATCH] refactor request handling to improve type safety and streamline request parsing --- src/index.ts | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/index.ts b/src/index.ts index 610590b..6de22b6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -53,13 +53,11 @@ export default class Flummpress { listen(...args: any[]): this { this.server = http .createServer(async (request: IncomingMessage, response: ServerResponse) => { - const req = request as Request; - const res = this.createResponse(response); + const req: Request = this.parseRequest(request); + const res: Response = this.createResponse(response); const start = process.hrtime(); try { - this.parseRequest(req); - for(const mw of this.middleware) { await mw(req, res, () => {}); } @@ -104,8 +102,9 @@ export default class Flummpress { return this; } - private parseRequest(req: Request): void { - const url = new URL(req.url!.replace(/(?!^.)(\/+)?$/, ""), "http://localhost"); + private parseRequest(request: IncomingMessage): Request { + const url = new URL(request.url!.replace(/(?!^.)(\/+)?$/, ""), "http://localhost"); + const req = request as Request; req.parsedUrl = { pathname: url.pathname, split: url.pathname.split("/").slice(1), @@ -120,18 +119,19 @@ export default class Flummpress { req.cookies![key] = decodeURIComponent(value); }); } + return req; } /** * Reads and parses the body of an incoming HTTP request. - * @param {IncomingMessage} req - The HTTP request object. + * @param {Request} req - The HTTP request object. * @returns {Promise} - A promise that resolves to the parsed body data. */ - private async readBody(req: IncomingMessage): Promise> { + private async readBody(req: Request): Promise> { return new Promise((resolve, reject) => { - let body = ""; + let body: string = ""; - req.on("data", chunk => { + req.on("data", (chunk: string) => { body += chunk; });