From b14b188038c9b76907b907a0926ce045c3a3a770 Mon Sep 17 00:00:00 2001 From: Gildas Garcia <1122076+djhi@users.noreply.github.com> Date: Mon, 3 Jun 2024 09:49:05 +0200 Subject: [PATCH] Fix MSW integration --- src/msw.ts | 54 +++++++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/src/msw.ts b/src/msw.ts index c34bb97..89113fd 100644 --- a/src/msw.ts +++ b/src/msw.ts @@ -29,30 +29,34 @@ const getCollectionHandlers = ({ collectionName: string; server: BaseServer; }) => { - return http.all(`${baseUrl}/${collectionName}`, async ({ request }) => { - const url = new URL(request.url); - const params = Object.fromEntries( - Array.from(new URLSearchParams(url.search).entries()).map( - ([key, value]) => [key, JSON.parse(value)], - ), - ); - let requestJson: Record | undefined = undefined; - try { - const text = await request.text(); - requestJson = JSON.parse(text); - } catch (e) { - // not JSON, no big deal - } - const response = server.handleRequest({ - url: request.url.split('?')[0], - method: request.method, - requestJson, - params, - }); + return http.all( + // Using a regex ensures we match all URLs that start with the collection name + new RegExp(`${baseUrl}/${collectionName}`), + async ({ request }) => { + const url = new URL(request.url); + const params = Object.fromEntries( + Array.from(new URLSearchParams(url.search).entries()).map( + ([key, value]) => [key, JSON.parse(value)], + ), + ); + let requestJson: Record | undefined = undefined; + try { + const text = await request.text(); + requestJson = JSON.parse(text); + } catch (e) { + // not JSON, no big deal + } + const response = server.handleRequest({ + url: request.url.split('?')[0], + method: request.method, + requestJson, + params, + }); - return HttpResponse.json(response.body, { - status: response.status, - headers: response.headers, - }); - }); + return HttpResponse.json(response.body, { + status: response.status, + headers: response.headers, + }); + }, + ); };