refactor request handling to improve type safety and streamline request parsing

This commit is contained in:
Flummi 2025-03-15 22:45:13 +01:00
parent dc8c150ce8
commit 4514a37999

View File

@ -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<any>} - A promise that resolves to the parsed body data.
*/
private async readBody(req: IncomingMessage): Promise<Record<string, string>> {
private async readBody(req: Request): Promise<Record<string, string>> {
return new Promise((resolve, reject) => {
let body = "";
let body: string = "";
req.on("data", chunk => {
req.on("data", (chunk: string) => {
body += chunk;
});