Skip to content

Commit

Permalink
Fix support for non-JSON fetch responses (#153)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
adamkiss and sindresorhus authored Mar 30, 2022
1 parent 8e88725 commit 1bf01cf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,18 @@ alfy.fetch = async (url, options) => {
return cachedResponse;
}

if ('json' in options && options.json === false) {
delete options.json;
options.responseType = 'text';
} else {
options.responseType = 'json';
}

options.resolveBodyOnly = true;

let response;
try {
response = await got(url, options).json();
response = await got(url, options);
} catch (error) {
if (cachedResponse) {
return cachedResponse;
Expand Down
6 changes: 6 additions & 0 deletions test/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ test.before(() => {
nock(URL).get('/cache-key?unicorn=rainbow').reply(200, {unicorn: 'rainbow'});
nock(URL).get('/cache-version').once().reply(200, {foo: 'bar'});
nock(URL).get('/cache-version').twice().reply(200, {unicorn: 'rainbow'});
nock(URL).get('/string-response').once().reply(200, 'unicorn is rainbow');
});

test('no cache', async t => {
Expand Down Expand Up @@ -74,3 +75,8 @@ test('invalid version', async t => {
// t.deepEqual(await alfy3.fetch(`${URL}/cache-version`, {maxAge: 5000}), {unicorn: 'rainbow'});
// t.deepEqual(alfy.cache.store['https://foo.bar/cache-version{"maxAge":5000}'].data, {unicorn: 'rainbow'});
});

test('non-JSON response', async t => {
const alfy = createAlfy();
t.is(await alfy.fetch(`${URL}/string-response`, {json: false}), 'unicorn is rainbow');
});

0 comments on commit 1bf01cf

Please sign in to comment.