Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
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
31 changes: 31 additions & 0 deletions __tests__/utils/fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as fetch from '../../src/utils/fetch';

describe('utils.fetch#encodeQueryData', () => {
test('should create valid query string', () => {
const result1 = fetch.encodeQueryData({
a: 1,
b: true,
c: null,
d: 'foo',
e: undefined
});

const result2 = fetch.encodeQueryData({
a: {
a: 1,
b: true,
c: null,
d: 'foo',
e: undefined
},
b: {
c: {
d: 'foo'
}
}
});

expect(result1).toEqual('a.i=1&b.b=true&c.n=null&d.s=foo&e.u=undefined');
expect(result2).toEqual('a.a.i=1&a.b.b=true&a.c.n=null&a.d.s=foo&a.e.u=undefined&b.c.d.s=foo');
});
});
24 changes: 20 additions & 4 deletions src/utils/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,29 @@
* @license Simplified BSD License
*/

const typesToken = {
string : 's',
number : 'i',
boolean : 'b',
undefined: 'u',
null: 'n'
};

/*
* Creates URL request path
*/
const encodeQueryData = data => Object.keys(data)
.filter(k => typeof data[k] !== 'object')
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(data[k]))
.join('&');
export const encodeQueryData = (data, nesting = '') => {
const pairs = Object.entries(data).map(([key, val]) => {
const isNull = val === null;
if (typeof val === 'object' && !isNull) {
return encodeQueryData(val, nesting + `${key}.`);
} else {
const type = typesToken[isNull ? 'null' : typeof val];
return encodeURIComponent(nesting + key + '.' + type) + '=' + encodeURIComponent(val);
}
});
return pairs.join('&');
};

const bodyTypes = [
window.ArrayBuffer,
Expand Down