From 905bbe5fd3aa907801a8a7a5758a8897656bd127 Mon Sep 17 00:00:00 2001 From: mahdi Date: Wed, 14 Aug 2024 01:53:11 +0330 Subject: [PATCH] feat(core): Request handling with additional methods for better abstraction --- lib/core/request.ts | 67 ++++++++------------------------------------- 1 file changed, 12 insertions(+), 55 deletions(-) diff --git a/lib/core/request.ts b/lib/core/request.ts index cf9363c..44f2fce 100644 --- a/lib/core/request.ts +++ b/lib/core/request.ts @@ -1,63 +1,17 @@ -import { createServer, IncomingMessage, ServerResponse } from 'http'; -import { URL } from 'url'; -import { URLParams } from '../types/types'; - -class URLParser> { - private url: URL; - private pattern: string; - private params: URLParams = {} as URLParams; - private queries: Record = {}; - - constructor(urlString: string, host: string, pattern: string) { - this.url = new URL(urlString, `http://${host}`); - this.pattern = pattern; - this.extractParams(); - this.extractQueries(); - } - - private extractParams() { - const pathParts = this.url.pathname.split('/').filter(Boolean); - const patternParts = this.pattern.split('/').filter(Boolean); - - patternParts.forEach((part, index) => { - if (part.startsWith(':')) { - const key = part.substring(1) as keyof URLParams; - if (pathParts[index]) { - this.params[key] = pathParts[index] as URLParams[typeof key]; - } - } - }); - } - - private extractQueries() { - this.url.searchParams.forEach((value, key) => { - this.queries[key] = value; - }); - } - - getParams(): URLParams { - return this.params; - } - - getQueries(): Record { - return this.queries; - } -} +import { IncomingMessage } from 'http'; +import { URLParser } from '../helper'; class Request> extends IncomingMessage { private urlParser: URLParser; - - constructor(req: IncomingMessage, pattern: string) { - // Initialize the parent class + constructor(req: IncomingMessage,) { super(req.socket); - // Ensure the instance properties are correctly set this.url = req.url; this.method = req.method; this.headers = req.headers; - this.urlParser = new URLParser(this.url!, this.headers.host || '', pattern); + this.urlParser = new URLParser(this.url!); } - get params(): URLParams { + get params(): T { return this.urlParser.getParams(); } @@ -73,10 +27,13 @@ class Request> extends IncomingMessage { return (this.socket as any).encrypted ? 'https' : 'http'; } - public getHeader(name: string){ + public getHeader(name: string) { const lowerCaseName = name.toLowerCase(); - return this.headers[lowerCaseName as keyof IncomingMessage['headers']] ?? - (lowerCaseName === 'referer' || lowerCaseName === 'referrer' ? - this.headers.referrer ?? this.headers.referer : undefined); + return ( + this.headers[lowerCaseName as keyof IncomingMessage['headers']] ?? + (lowerCaseName === 'referer' || lowerCaseName === 'referrer' + ? this.headers.referrer ?? this.headers.referer + : undefined) + ); } }