Visitar URL original
refactor response create function outside of promise handler by kalisjoshua · Pull Request #132 · developit/unfetch · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
refactor response create function outside of promise handler
not sure that this is favorable or not but thought that it might be and it allows
for easier testing of the creation of responses and their properties.
  • Loading branch information
jkalis-rm committed Feb 18, 2020
commit ecfc94fe661390aa64e51eb48e05edc377de0fa1
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ node_modules
npm-debug.log
.DS_Store
/polyfill/index.js
coverage
51 changes: 26 additions & 25 deletions src/index.mjs
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
const regex = /^(.*?):[^\S\n]*([\s\S]*?)$/gm;
const response = (request, headers) => ({
ok: (request.status/100|0) == 2, // 200-299
statusText: request.statusText,
status: request.status,
url: request.responseURL,
text: () => Promise.resolve(request.responseText),
json: () => Promise.resolve(JSON.parse(request.responseText)),
blob: () => Promise.resolve(new Blob([request.response])),
clone: () => response(request, headers),
headers: {
keys: () => headers.keys,
entries: () => headers.all,
get: n => headers.raw[n.toLowerCase()],
has: n => n.toLowerCase() in headers.raw
}
});

export default function(url, options) {
options = options || {};
return new Promise( (resolve, reject) => {
const request = new XMLHttpRequest();
const keys = [];
const all = [];
const headers = {};

const response = () => ({
ok: (request.status/100|0) == 2, // 200-299
statusText: request.statusText,
status: request.status,
url: request.responseURL,
text: () => Promise.resolve(request.responseText),
json: () => Promise.resolve(JSON.parse(request.responseText)),
blob: () => Promise.resolve(new Blob([request.response])),
clone: response,
headers: {
keys: () => keys,
entries: () => all,
get: n => headers[n.toLowerCase()],
has: n => n.toLowerCase() in headers
}
});

request.open(options.method || 'get', url, true);

request.onload = () => {
request.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, (m, key, value) => {
keys.push(key = key.toLowerCase());
all.push([key, value]);
headers[key] = headers[key] ? `${headers[key]},${value}` : value;
const head = { all: [], keys: [], raw: {} };
request.getAllResponseHeaders().replace(regex, (m, key, value) => {
head.all.push([key, value]);
head.keys.push(key = key.toLowerCase());
head.raw[key] = head.raw[key] ? `${head.raw[key]},${value}` : value;
});
resolve(response());
resolve(response(request, head));
};

request.onerror = reject;
Expand All @@ -45,3 +44,5 @@ export default function(url, options) {
request.send(options.body || null);
});
}

export { response };
31 changes: 30 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fetch from '../src/index.mjs';
import fetch, { response } from '../src/index.mjs';
import fetchDist from '..';

describe('unfetch', () => {
Expand Down Expand Up @@ -81,4 +81,33 @@ describe('unfetch', () => {
return p;
});
});

describe('response()', () => {
it('returns text()', () => response({ responseText: 'A passing test.' })
.text()
.then((text) => expect(text).toBe('A passing test.'))
);

it('returns blob()', () => response({ response: 'A passing test.' })
.blob()
.then((text) => expect(text.toString()).toBe(new Blob(['A passing test.']).toString()))
);

it('returns headers', () => {
const all = [['x-foo', 'bar'], ['x-baz', 'boo']];
const result = response({}, { all }).headers.entries();
expect(result).toEqual(all);
});

it('returns header keys', () => {
const result = response({}, { keys: ['x-foo'] }).headers.keys();
expect(result).toEqual(['x-foo']);
});

it('returns headers has', () => {
const raw = { 'x-foo': 'bar', 'x-baz': 'boo' };
const test = response({}, { raw }).headers;
expect(test.has('x-foo')).toBe(true);
});
});
});