Skip to content

Commit 1bf01cf

Browse files
Fix support for non-JSON fetch responses (#153)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
1 parent 8e88725 commit 1bf01cf

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

index.js

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,18 @@ alfy.fetch = async (url, options) => {
137137
return cachedResponse;
138138
}
139139

140+
if ('json' in options && options.json === false) {
141+
delete options.json;
142+
options.responseType = 'text';
143+
} else {
144+
options.responseType = 'json';
145+
}
146+
147+
options.resolveBodyOnly = true;
148+
140149
let response;
141150
try {
142-
response = await got(url, options).json();
151+
response = await got(url, options);
143152
} catch (error) {
144153
if (cachedResponse) {
145154
return cachedResponse;

test/fetch.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ test.before(() => {
1313
nock(URL).get('/cache-key?unicorn=rainbow').reply(200, {unicorn: 'rainbow'});
1414
nock(URL).get('/cache-version').once().reply(200, {foo: 'bar'});
1515
nock(URL).get('/cache-version').twice().reply(200, {unicorn: 'rainbow'});
16+
nock(URL).get('/string-response').once().reply(200, 'unicorn is rainbow');
1617
});
1718

1819
test('no cache', async t => {
@@ -74,3 +75,8 @@ test('invalid version', async t => {
7475
// t.deepEqual(await alfy3.fetch(`${URL}/cache-version`, {maxAge: 5000}), {unicorn: 'rainbow'});
7576
// t.deepEqual(alfy.cache.store['https://foo.bar/cache-version{"maxAge":5000}'].data, {unicorn: 'rainbow'});
7677
});
78+
79+
test('non-JSON response', async t => {
80+
const alfy = createAlfy();
81+
t.is(await alfy.fetch(`${URL}/string-response`, {json: false}), 'unicorn is rainbow');
82+
});

0 commit comments

Comments
 (0)