Skip to content
This repository has been archived by the owner on May 22, 2023. It is now read-only.

Commit

Permalink
Issue 27 return empty object on 204 responses (#28)
Browse files Browse the repository at this point in the history
Addresses #27 by returning
an empty object for 204 responses to avoid json parsing errors while
keeping with current conventions for backward compatability.
  • Loading branch information
nholik committed Apr 20, 2023
1 parent fabfad2 commit ff3ae1b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
37 changes: 37 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,25 @@ describe('post()', () => {
body: { foo: 'Bar' },
});
});

it('returns empty object on 204', async () => {
const client = createClient<paths>();
fetchMocker.mockResponseOnce(() => ({ status: 204, body: '' }));
const { data, error, response } = await client.post('/create-tag/{name}', {
params: { path: { name: 'New Tag' } },
body: { description: 'This is a new tag' },
});

// assert correct URL was called
expect(fetchMocker.mock.calls[0][0]).toBe('/create-tag/New%20Tag');

// assert correct data was returned
expect(data).toEqual({});
expect(response.status).toBe(204);

// assert error is empty
expect(error).toBe(undefined);
});
});

describe('delete()', () => {
Expand All @@ -258,6 +277,24 @@ describe('delete()', () => {
await client.del('/' as any, {});
expect(fetchMocker.mock.calls[0][1]?.method).toBe('DELETE');
});

it('returns empty object on 204', async () => {
const client = createClient<paths>();
fetchMocker.mockResponseOnce(() => ({ status: 204, body: '' }));
const { data, error, response } = await client.del('/post/{post_id}', {
params: { path: { post_id: '123' } },
});

// assert correct URL was called
expect(fetchMocker.mock.calls[0][0]).toBe('/post/123');

// assert correct data was returned
expect(data).toEqual({});
expect(response.status).toBe(204);

// assert error is empty
expect(error).toBe(undefined);
});
});

describe('options()', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export default function createClient<T>(options?: ClientOptions) {
type: res.type,
url: res.url,
};
return res.ok ? { data: await res.json(), response } : { error: await res.json(), response };
return res.ok ? { data: res.status === 204 ? {} : await res.json(), response } : { error: await res.json(), response };
}

return {
Expand Down

0 comments on commit ff3ae1b

Please sign in to comment.