Skip to content

Commit

Permalink
add strict flag - resolves #42
Browse files Browse the repository at this point in the history
  • Loading branch information
SamVerschueren committed Mar 26, 2016
1 parent 505e825 commit 0a725fe
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
15 changes: 11 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
'use strict';
var strictUriEncode = require('strict-uri-encode');

function encode(value, strict) {
return strict ? strictUriEncode(value) : encodeURIComponent(value);
}

exports.extract = function (str) {
return str.split('?')[1] || '';
};
Expand Down Expand Up @@ -45,7 +49,10 @@ exports.parse = function (str) {
return ret;
};

exports.stringify = function (obj) {
exports.stringify = function (obj, opts) {
opts = opts || {};
opts.strict = opts.strict !== false;

return obj ? Object.keys(obj).sort().map(function (key) {
var val = obj[key];

Expand All @@ -66,16 +73,16 @@ exports.stringify = function (obj) {
}

if (val2 === null) {
result.push(strictUriEncode(key));
result.push(encode(key, opts.strict));
} else {
result.push(strictUriEncode(key) + '=' + strictUriEncode(val2));
result.push(encode(key, opts.strict) + '=' + encode(val2, opts.strict));
}
});

return result.join('&');
}

return strictUriEncode(key) + '=' + strictUriEncode(val);
return encode(key, opts.strict) + '=' + encode(val, opts.strict);
}).filter(function (x) {
return x.length > 0;
}).join('&') : '';
Expand Down
8 changes: 8 additions & 0 deletions test/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,11 @@ test('handle undefined values in array', t => {
test('handle undefined and null values in array', t => {
t.same(fn.stringify({foo: null, bar: [undefined, null, 'baz']}), 'bar=baz&bar&foo');
});

test('strict encoding', t => {
t.same(fn.stringify({foo: '\'bar\''}), 'foo=%27bar%27');
});

test('loose encoding', t => {
t.same(fn.stringify({foo: '\'bar\''}, {strict: false}), 'foo=\'bar\'');
});

0 comments on commit 0a725fe

Please sign in to comment.