From 76f5e875c9f763c087b524538e9940cb670ad1e6 Mon Sep 17 00:00:00 2001 From: Seedgou Date: Fri, 8 Nov 2024 18:18:06 +0800 Subject: [PATCH] refactor: parse headers and params using Headers and URLSearchParams --- src/adapter/alibaba-cloud-fc3/handler.test.ts | 42 +++++++++++++++++++ src/adapter/alibaba-cloud-fc3/handler.ts | 17 ++------ 2 files changed, 46 insertions(+), 13 deletions(-) diff --git a/src/adapter/alibaba-cloud-fc3/handler.test.ts b/src/adapter/alibaba-cloud-fc3/handler.test.ts index e55c9ce4..3af1fb14 100644 --- a/src/adapter/alibaba-cloud-fc3/handler.test.ts +++ b/src/adapter/alibaba-cloud-fc3/handler.test.ts @@ -149,6 +149,48 @@ describe('createRequest', () => { const text = await request.text() expect(text).toEqual('Request Body') }) + + it('Should handle escaped paths in request URL correctly', () => { + const event: AlibabaCloudFC3Event = { + version: 'v1', + rawPath: '/my/path%E4%BD%A0%E5%A5%BD', + headers: { + Accept: '*/*', + 'User-Agent': 'curl/7.81.0', + }, + queryParameters: { + 你好: '世界', + }, + body: '', + isBase64Encoded: true, + requestContext: { + accountId: '1234567890123456', + domainName: 'hono-al-fc-test.us-east-1.fcapp.run', + domainPrefix: 'hono-al-fc-test', + requestId: '1-12345678-12345678-123456789012', + time: '2024-11-07T07:52:56Z', + timeEpoch: '1730965976961', + http: { + method: 'GET', + path: '/my/path你好', + protocol: 'HTTP/1.1', + sourceIp: '1.2.3.4', + userAgent: 'curl/7.81.0', + }, + }, + } + + const request = createRequest(event) + + expect(request.method).toEqual('GET') + const requestUrl = new URL(request.url) + expect(requestUrl.pathname).toEqual('/my/path%E4%BD%A0%E5%A5%BD') + expect(requestUrl.searchParams.get('你好')).toEqual('世界') + expect(Object.fromEntries(request.headers)).toEqual({ + accept: '*/*', + 'user-agent': 'curl/7.81.0', + }) + }) }) describe('createResponse', () => { diff --git a/src/adapter/alibaba-cloud-fc3/handler.ts b/src/adapter/alibaba-cloud-fc3/handler.ts index 5b459396..f14d5601 100644 --- a/src/adapter/alibaba-cloud-fc3/handler.ts +++ b/src/adapter/alibaba-cloud-fc3/handler.ts @@ -31,20 +31,11 @@ export const handle = { - const queryString = Object.entries(event.queryParameters || {}) - .map(([key, value]) => `${key}=${value}`) - .join('&') + const url = new URL(`https://${event.requestContext.domainName}${event.rawPath}`) - const url = `https://${event.requestContext.domainName}${event.rawPath}${ - queryString ? `?${queryString}` : '' - }` - - const headers = new Headers() - if (event.headers) { - for (const [key, value] of Object.entries(event.headers)) { - headers.set(key, value) - } - } + const params = new URLSearchParams(event.queryParameters) + url.search = params.toString() + const headers = new Headers(event.headers) const method = event.requestContext.http.method const requestInit: RequestInit = {