Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow to use default fetcher for requests that return an empty response #13

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/createZodFetcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
3 changes: 2 additions & 1 deletion src/createZodFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ export const defaultFetcher = async (...args: Parameters<typeof fetch>) => {
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))
};

/**
Expand Down