Skip to content

Commit

Permalink
feat: Consistent header support for client-side
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Krems committed Apr 15, 2016
1 parent c26613c commit 71e8fe4
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
16 changes: 15 additions & 1 deletion lib/fetch.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,23 @@ function verifyAndExtendResponse(options, response) {
(max === false || code <= max);
}

var originalHeaders = response.headers;
var cachedHeaders;
function getCachedHeaders() {
if (!cachedHeaders) {
cachedHeaders = {};
originalHeaders.forEach(function addHeader(value, name) {
if (name) {
cachedHeaders[name] = value;
}
});
}
return cachedHeaders;
}

Object.defineProperties(response, {
statusCode: { value: response.status },
headers: { value: {} },
headers: { get: getCachedHeaders },
});

function generateStatusCodeError(code) {
Expand Down
13 changes: 13 additions & 0 deletions test/fetch-http.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,10 @@ describe('fetch: the basics', function () {
});

it('exposes a promise to a response body stream', function () {
if (typeof document !== 'undefined') {
// Streams in the browser and streams in node are two different things.
return this.skip();
}
function concat(stream) {
return new Bluebird(function (resolve, reject) {
stream.on('error', reject);
Expand All @@ -97,4 +101,13 @@ describe('fetch: the basics', function () {
assert.equal('ok', '' + body);
});
});

it('returns response headers', function () {
// this is a silly test in node but is relevant to browser usage
return fetch('/test/path', options)
.then(function (res) {
// Testing content-language b/c it's a "simple response header"
assert.equal('has%20stuff', res.headers['content-language']);
});
});
});
3 changes: 3 additions & 0 deletions test/mock-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ function send404(req, res) {
}

function handleRequest(req, res) {
// A random header that happens to be a "simple response header".
// See: https://www.w3.org/TR/cors/#simple-response-header
res.setHeader('Content-Language', 'has%20stuff');
if (req.headers.origin) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
Expand Down

0 comments on commit 71e8fe4

Please sign in to comment.