From b03b0ef706cfa6681f44523b870ca20b55b8908c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=8E?= Date: Sun, 22 Oct 2023 18:01:08 +0800 Subject: [PATCH] feat(route): support json param in route.fulfill --- src/WS/route/Route.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/WS/route/Route.ts b/src/WS/route/Route.ts index f33d6d6..03f8cd9 100644 --- a/src/WS/route/Route.ts +++ b/src/WS/route/Route.ts @@ -115,6 +115,7 @@ export default class Route { body, contentType, headers, + json, path, response, status, @@ -122,25 +123,42 @@ export default class Route { body?: string | ArrayBufferLike | Blob | ArrayBufferView | null; contentType?: string; headers?: Record; + json?: unknown; path?: string; response?: Response; status?: number; } = {}) { this.assertNotHandled(); - let fulfillBody = body; + + let fulfillBody; + if (json !== undefined) { + if (body !== undefined) { + throw new Error('Can specify either body or json parameters'); + } + fulfillBody = JSON.stringify(fulfillBody); + } else { + fulfillBody = body; + } + if (fulfillBody === undefined) { const responseAB = await response?.clone().arrayBuffer(); if (responseAB && responseAB.byteLength > 0) { fulfillBody = responseAB; } } + + let fulfillContentType = contentType; + if (fulfillContentType === undefined && json !== undefined) { + fulfillContentType = 'application/json'; + } + const hasBody = fulfillBody !== undefined && fulfillBody !== null; this.ws.send(createRouteMeta({ action: 'fulfill', id: this.id, resolveID: this.resolveID, hasBody, - contentType: contentType ?? response?.headers.get('Content-Type') ?? undefined, + contentType: fulfillContentType, headers: headers ?? ( response && [...response.headers] .reduce((acc: Record, [key, value]) => {