diff --git a/src/createZodFetcher.test.ts b/src/createZodFetcher.test.ts index 4cee80c..02c5efa 100644 --- a/src/createZodFetcher.test.ts +++ b/src/createZodFetcher.test.ts @@ -31,6 +31,23 @@ it("Should create a default fetcher", async () => { }); }); +it("Should successfully parse empty responses with the default fetcher", async () => { + server.use( + rest.get("https://example.com", (req, res, ctx) => { + return res(ctx.status(200)); + }), + ); + + const fetchWithZod = createZodFetcher(); + + const response = await fetchWithZod( + z.undefined(), + "https://example.com", + ); + + expect(response).toBeUndefined(); +}); + it("Should throw an error with mis-matched schemas with a default fetcher", async () => { server.use( rest.get("https://example.com", (req, res, ctx) => { diff --git a/src/createZodFetcher.ts b/src/createZodFetcher.ts index 21fc14b..047ef6d 100644 --- a/src/createZodFetcher.ts +++ b/src/createZodFetcher.ts @@ -31,7 +31,8 @@ export const defaultFetcher = async (...args: Parameters) => { throw new Error(`Request failed with status ${response.status}`); } - return response.json(); + // workaround since `.json()` would throw on empty responses + return response.text().then((text) => (text.length ? JSON.parse(text) : undefined)) }; /**