Skip to content
This repository has been archived by the owner on Nov 8, 2024. It is now read-only.

Commit

Permalink
fix: adds "normalizeHeaders"
Browse files Browse the repository at this point in the history
  • Loading branch information
artem-zakharchenko committed May 17, 2019
1 parent 79448a3 commit 350d8ca
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lib/api/test/unit/units/normalize/normalizeHeaders.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const { assert } = require('chai');
const normalizeHeaders = require('../../../../units/normalize/normalizeHeaders');

describe('normalizeHeaders', () => {
describe('when given nothing', () => {
const headers = normalizeHeaders(undefined);

it('coerces to empty object', () => {
assert.deepEqual(headers, {});
});
});

describe('when given headers object', () => {
const headers = {
'Accept-Language': 'en-US, en',
'Content-Type': 'application/json',
'Content-Length': 128
};
const normalizedHeaders = normalizeHeaders(headers);

it('lowercases the keys', () => {
const expectedKeys = Object.keys(headers).map((key) => key.toLowerCase());
assert.hasAllKeys(normalizedHeaders, expectedKeys);
});

it('lowercases the values', () => {
const expectedValues = Object.values(headers).map((value) =>
typeof value === 'string' ? value.toLowerCase() : value
);
assert.deepEqual(Object.values(normalizedHeaders), expectedValues);
});
});

describe('when given non-object headers', () => {
const unsupportedTypes = [['string', 'foo'], ['number', 2]];

unsupportedTypes.forEach(([typeName, dataType]) => {
it(`when given ${typeName}`, () => {
assert.throw(() => normalizeHeaders(dataType));
});
});
});
});
8 changes: 8 additions & 0 deletions lib/api/units/normalize/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const evolve = require('../../utils/evolve');
const normalizeHeaders = require('./normalizeHeaders');

const normalize = evolve({
headers: normalizeHeaders
});

module.exports = normalize;
35 changes: 35 additions & 0 deletions lib/api/units/normalize/normalizeHeaders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const normalizeStringValue = (value) => {
return value.toLowerCase().trim();
};

/**
* Normalizes the given headers.
* @param {Object} headers
* @returns {Object}
*/
const normalizeHeaders = (headers) => {
if (!headers) {
return {};
}

const headersType = typeof headers;

if (headersType === null || headersType !== 'object') {
throw new Error(
`Can't validate: expected "headers" to be an Object, but got: ${headersType}.`
);
}

return Object.keys(headers).reduce(
(acc, name) => ({
...acc,
[name.toLowerCase()]:
typeof headers[name] === 'string'
? normalizeStringValue(headers[name])
: headers[name]
}),
{}
);
};

module.exports = normalizeHeaders;

0 comments on commit 350d8ca

Please sign in to comment.