fix(ajax): don't throw on non-JSON responses in fetchJson

This commit is contained in:
Lars den Bakker 2022-08-17 20:09:45 +02:00 committed by Thijs Louisse
parent cc1c5bc4a6
commit 66abd3ea4c
3 changed files with 25 additions and 9 deletions

View file

@ -0,0 +1,5 @@
---
'@lion/ajax': patch
---
don't throw on non-JSON responses in fetchJson

View file

@ -180,14 +180,19 @@ export class Ajax {
responseText = responseText.substring(jsonPrefix.length);
}
/** @type {any} */
let body = responseText;
if (response.headers.get('content-type')?.includes('application/json')) {
try {
return {
response,
body: JSON.parse(responseText),
};
body = JSON.parse(responseText);
} catch (error) {
throw new Error(`Failed to parse response from ${response.url} as JSON.`);
}
} else {
body = responseText;
}
return { response, body };
}
/**

View file

@ -159,6 +159,12 @@ describe('Ajax', () => {
expect(response.response.headers.get('X-Custom-Header')).to.equal('y-custom-value');
});
it('handles non-json responses', async () => {
fetchStub.returns(Promise.resolve(new Response('!@#$')));
const response = await ajax.fetchJson('/foo');
expect(response.body).to.eql('!@#$');
});
describe('given a request body', () => {
it('encodes the request body as json', async () => {
await ajax.fetchJson('/foo', { method: 'POST', body: { a: 1, b: 2 } });
@ -176,14 +182,14 @@ describe('Ajax', () => {
describe('given a json prefix', () => {
it('strips json prefix from response before decoding', async () => {
const localAjax = new Ajax({ jsonPrefix: '//.,!' });
fetchStub.returns(Promise.resolve(new Response('//.,!{"a":1,"b":2}')));
fetchStub.returns(Promise.resolve(new Response('//.,!{"a":1,"b":2}', responseInit())));
const response = await localAjax.fetchJson('/foo');
expect(response.body).to.eql({ a: 1, b: 2 });
});
});
it('throws on invalid JSON responses', async () => {
fetchStub.returns(Promise.resolve(new Response('invalid-json')));
fetchStub.returns(Promise.resolve(new Response('invalid-json', responseInit())));
let thrown = false;
try {