Skip to content

Commit

Permalink
fix(fetchtool): catch fetch exception on get resource (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreyNikitin authored Nov 29, 2021
1 parent d331232 commit 33e6ddf
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/FetchTool.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ class FetchTool {
*/
get ({url, ...options}) {
return fetch(url, Object.assign({method: 'GET'}, options))
.then(result => result.arrayBuffer())
.then(result => {
if (result.ok) return result.arrayBuffer();
return Promise.reject(result.status);
})
.then(body => new Uint8Array(body));
}

Expand Down
33 changes: 33 additions & 0 deletions test/unit/fetch-tool.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
const test = require('tap').test;
const TextEncoder = require('util').TextEncoder;
const TextDecoder = require('util').TextDecoder;

const FetchTool = require('../../src/FetchTool');

Expand Down Expand Up @@ -27,3 +29,34 @@ test('send failure returns response.status', t => {
t.equal(reason, 500);
});
});

test('get success returns Uint8Array.body(response.arrayBuffer())', t => {
const text = 'successful response';
const encoding = 'utf-8';
const encoded = new TextEncoder().encode(text);
const decoder = new TextDecoder(encoding);

global.fetch = () => Promise.resolve({
ok: true,
arrayBuffer: () => encoded.buffer
});

const tool = new FetchTool();

return tool.get({url: 'url'}).then(result => {
t.equal(decoder.decode(result), text);
});
});

test('get failure returns response.status', t => {
global.fetch = () => Promise.resolve({
ok: false,
status: 500
});

const tool = new FetchTool();

return tool.get({url: 'url'}).catch(reason => {
t.equal(reason, 500);
});
});

0 comments on commit 33e6ddf

Please sign in to comment.