Skip to content

Commit

Permalink
have to clone response to be able to parse body in interceptors
Browse files Browse the repository at this point in the history
  • Loading branch information
Nigui committed Oct 9, 2023
1 parent 58e99f1 commit b8009c0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
11 changes: 10 additions & 1 deletion packages/http/src/http.common.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ describe('handleBody', () => {

const blob = jest.fn(() => Promise.resolve());

await handleBody({ blob, headers } as any);
await handleBody({
headers,
clone: jest.fn().mockReturnValue({ blob }),
} as any);

Check warning on line 60 in packages/http/src/http.common.test.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/http/src/http.common.test.ts#L60

[@typescript-eslint/no-explicit-any] Unexpected any. Specify a different type.

expect(blob).toHaveBeenCalled();
});
Expand All @@ -77,6 +80,12 @@ describe('handleBody', () => {
expect(result.data).toBe('');
});

it("should manage response's body and return a clone with unused body", async () => {
const result = await handleBody(new Response('ok') as any);

Check warning on line 84 in packages/http/src/http.common.test.ts

View workflow job for this annotation

GitHub Actions / ESLint Report Analysis

packages/http/src/http.common.test.ts#L84

[@typescript-eslint/no-explicit-any] Unexpected any. Specify a different type.
expect(result.data).toBe('ok');
expect(result.response.bodyUsed).toBe(false);
});

describe('#handleHttpResponse', () => {
it('should handle the response with 2xx code', async () => {
const headers = new Headers();
Expand Down
7 changes: 4 additions & 3 deletions packages/http/src/http.common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,17 +40,18 @@ export function encodePayload(headers: HeadersInit, payload: any) {
* @return {Promise} A promise that resolves with the result of parsing the body
*/
export async function handleBody(response: Response) {
const clonedResponse = response.clone();
const { headers } = response;
const contentType = headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
return response.json().then(data => ({ data, response }));
return clonedResponse.json().then(data => ({ data, response }));
}

if (contentType && contentType.includes('application/zip')) {
return response.blob().then(data => ({ data, response }));
return clonedResponse.blob().then(data => ({ data, response }));
}

return response.text().then(data => ({ data, response }));
return clonedResponse.text().then(data => ({ data, response }));
}

/**
Expand Down

0 comments on commit b8009c0

Please sign in to comment.