From d4075a6bb50f11192390ddb745c8b5f1abf3a57a Mon Sep 17 00:00:00 2001 From: HorizonCode Date: Thu, 11 May 2023 07:03:10 +0200 Subject: [PATCH] add queryParams --- example/test.ts | 2 ++ http_server.ts | 24 +++++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/example/test.ts b/example/test.ts index 5da8fae..04f5a2f 100644 --- a/example/test.ts +++ b/example/test.ts @@ -23,6 +23,8 @@ httpServer.add("GET", "/api/user/:userId", (req, rep) => { rep.status(Status.Teapot) .type("application/json"); + console.log(req.queryParams); + return JSON.stringify( { code: Status.Teapot, diff --git a/http_server.ts b/http_server.ts index 9b3f0f6..b7f35eb 100644 --- a/http_server.ts +++ b/http_server.ts @@ -227,7 +227,8 @@ export class RouteRequest { path: string; headers: Headers; method: string; - pathParams: { [key: string]: string | number }; + queryParams: { [key: string]: string }; + pathParams: { [key: string]: string }; constructor(request: Request) { this.url = request.url; @@ -236,20 +237,37 @@ export class RouteRequest { this.headers = request.headers; this.method = request.method; this.pathParams = {}; + this.queryParams = this.paramsToObject(urlObj.searchParams.entries()); } - header(name: string) { + private paramsToObject(entries: IterableIterator<[string, string]>) { + const result: { [key: string]: string } = {}; + for (const [key, value] of entries) { + result[key] = value; + } + return result; + } + + header(name: string): unknown { const matchingHeader = Array.from(this.headers.keys()).find((headerName) => headerName === name ); return matchingHeader ? this.headers.get(matchingHeader) : undefined; } - cookie(name: string) { + cookie(name: string): unknown { const allCookies = cookie.getCookies(this.headers); const allCookieNames = Object.keys(allCookies); return allCookieNames.includes(name) ? allCookies[name] : undefined; } + + pathParam(name: string): string { + return this.pathParams[name]; + } + + queryParam(name: string): string { + return this.queryParams[name]; + } } export class RouteReply {