From 96163aae6b0af114be2d148368d38981e907e3d4 Mon Sep 17 00:00:00 2001 From: Ian VanSchooten Date: Wed, 19 Jun 2024 08:30:02 -0400 Subject: [PATCH] Handle response bodies other than strings Related to https://github.com/miragejs/miragejs/pull/1110 --- lib/msw-config.ts | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/lib/msw-config.ts b/lib/msw-config.ts index d948a1e..72f819a 100644 --- a/lib/msw-config.ts +++ b/lib/msw-config.ts @@ -9,8 +9,12 @@ type RawHandler = RouteHandler | {}; type ResponseCode = number; -/** code, headers, serialized response */ -type ResponseData = [ResponseCode, { [k: string]: string }, string | undefined]; +/** code, headers, response body */ +type ResponseData = [ + ResponseCode, + { [k: string]: string }, + string | BodyInit | undefined, +]; /** e.g. "/movies/:id" */ type Shorthand = string; @@ -249,19 +253,25 @@ export default class MswConfig { // Return the correct type of response based on the `accept` header const accept = request.headers?.get('accept')?.toLowerCase() || ''; + if (!responseBody) { return new HttpResponse(null, init); - } else if (accept.includes('json')) { - return HttpResponse.json(JSON.parse(responseBody), init); - } else if (accept.includes('text')) { - return HttpResponse.text(responseBody, init); - } else { - try { - const json = JSON.parse(responseBody); - return HttpResponse.json(json, init); - } catch (e) { + } else if (typeof responseBody === 'string') { + if (accept.includes('json')) { + return HttpResponse.json(JSON.parse(responseBody), init); + } else if (accept.includes('text')) { return HttpResponse.text(responseBody, init); + } else { + try { + const json = JSON.parse(responseBody); + return HttpResponse.json(json, init); + } catch (e) { + return HttpResponse.text(responseBody, init); + } } + } else { + // Could be a ReadableStream, Blob, ArrayBuffer, etc. + return new HttpResponse(responseBody, init); } }); if (this.msw) {