From eb60e36941d2c03b439f0b75f0ba059667dfab81 Mon Sep 17 00:00:00 2001 From: Hans Kristian Flaatten Date: Wed, 10 Feb 2016 22:22:21 +0100 Subject: [PATCH] feat(parser): add `string.toBoolean` and `string.toNumber` options --- README.md | 3 +++ index.js | 12 +++++++++--- test.js | 15 +++++++++++++++ 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2341d37..58c6a35 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,9 @@ var MongoQS = require('mongo-querystring'); * `object` blacklist - blacklisted query params * `object` whitelist - whitelisted query params * `object` custom - custom query params +* `object` string - string parsing + * `boolean` toBoolean - parse `"true"`, `"false"` string to booleans + * `boolean` toNumber - parse string integer and float values to numbers #### Bult in custom queries diff --git a/index.js b/index.js index 8924d60..eb04ab9 100644 --- a/index.js +++ b/index.js @@ -10,6 +10,12 @@ module.exports = function MongoQS(opts) { this.whitelist = opts.whitelist || {}; this.custom = opts.custom || {}; + // String Value Parsing + opts.string = opts.string || {}; + this.string = opts.string || {}; + this.string.toBoolean = opts.string.toBoolean || true; + this.string.toNumber = opts.string.toNumber || true; + this.keyRegex = opts.keyRegex || /^[a-zæøå0-9-_.]+$/i; this.arrRegex = opts.arrRegex || /^[a-zæøå0-9-_.]+(\[\])?$/i; @@ -101,11 +107,11 @@ module.exports.prototype.customAfter = function(field) { }; module.exports.prototype.parseString = function(string) { - if (string.toLowerCase() === 'true') { + if (this.string.toBoolean && string.toLowerCase() === 'true') { return true; - } else if (string.toLowerCase() === 'false') { + } else if (this.string.toBoolean && string.toLowerCase() === 'false') { return false; - } else if (!isNaN(string)) { + } else if (this.string.toNumber && !isNaN(string)) { return parseFloat(string, 10); } else { return string; diff --git a/test.js b/test.js index 2aa709e..903d3e6 100644 --- a/test.js +++ b/test.js @@ -105,14 +105,29 @@ describe('parseString()', function() { assert.equal(qs.parseString('true'), true); }); + it('returns string "true" when boolean parsing is disabled', function() { + qs.string.toBoolean = false; + assert.equal(qs.parseString('true'), 'true'); + }); + it('returns boolean false for "flase" string', function() { assert.equal(qs.parseString('false'), false); }); + it('returns string "false" when boolean parsing is disabled', function() { + qs.string.toBoolean = false; + assert.equal(qs.parseString('false'), 'false'); + }); + it('returns number for parseable integer', function() { assert.equal(qs.parseString('100'), 100); }); + it('returns string number when number parsing is disabled', function() { + qs.string.toNumber = false; + assert.equal(qs.parseString('100'), '100'); + }); + it('returns number for zero padded parseable integer', function() { assert.equal(qs.parseString('000100'), 100); });