Skip to content

Commit

Permalink
Fix MSW integration
Browse files Browse the repository at this point in the history
  • Loading branch information
djhi committed Jun 3, 2024
1 parent f0d2880 commit b14b188
Showing 1 changed file with 29 additions and 25 deletions.
54 changes: 29 additions & 25 deletions src/msw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, any> | 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<string, any> | 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,
});
},
);
};

0 comments on commit b14b188

Please sign in to comment.