Skip to content

Commit

Permalink
fix: cast to boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeIbberson committed Apr 9, 2020
1 parent 21f837f commit 8b24898
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/__tests__/comparison.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ const exp = [
'bestFriend.name=jon',
'colleague.age=*',
'!colour',
'new=true',
];

const stub = {
new: true,
colour: null,
foo: 'bar',
age: 21,
Expand Down Expand Up @@ -58,6 +60,7 @@ describe('Comparison', () => {
{ 'bestFriend.name': /jon/gi },
{ 'colleague.age': { $exists: true } },
{ 'colour': { $eq: null } },
{ 'new': true },
],
}));

Expand Down
4 changes: 4 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
const moment = require('moment');

const toBoolean = (v) => v === 'true';

const validate = (v) => ({
alpha: () => new RegExp(/^[A-Z]+$/, 'gi').test(v),
date: () => moment(v, moment.ISO_8601, true).isValid(),
numeric: () => !Number.isNaN(parseFloat(v)),
boolean: () => toBoolean(v) || v === 'false',
});

class ValidatorRunner {
Expand Down Expand Up @@ -101,6 +104,7 @@ const cast = (v) => {
const test = validate(v);
if (test.date()) return v;
if (test.numeric()) return parseFloat(v);
if (test.boolean()) return toBoolean(v);
return new RegExp(v, 'i');
};

Expand Down

0 comments on commit 8b24898

Please sign in to comment.