object-key-validator
Advanced tools
Comparing version 1.0.0 to 1.1.0
24
index.js
@@ -7,14 +7,20 @@ const reducers = { | ||
const validateKeys = (rule, obj) => { | ||
if (!obj || !Object.keys(obj).length) return false; | ||
const ruleType = Object.keys(rule)[0]; | ||
if (!Array.isArray(rule[ruleType]) || !rule[ruleType].length) | ||
const [ruleType] = Object.keys(rule); | ||
if ( | ||
ruleType !== '$not' && | ||
(!Array.isArray(rule[ruleType]) || !rule[ruleType].length) | ||
) | ||
throw new Error('invalid rule'); | ||
return rule[ruleType] | ||
.map( | ||
r => | ||
typeof r === 'string' ? obj[r] !== undefined : validateKeys(r, obj), | ||
) | ||
.reduce(reducers[ruleType], ruleType === '$and'); | ||
return ruleType === '$not' | ||
? !validateKeys(rule['$not'], obj) | ||
: rule[ruleType] | ||
.map( | ||
r => | ||
typeof r === 'string' | ||
? obj[r] !== undefined && obj[r] !== null | ||
: validateKeys(r, obj), | ||
) | ||
.reduce(reducers[ruleType], ruleType === '$and'); | ||
}; | ||
module.exports = validateKeys; |
@@ -18,2 +18,18 @@ const validate = require('./'); | ||
it('checks $not properly with `or`', () => { | ||
const rule = { $not: { $or: ['a', 'b'] } }; | ||
expect(validate(rule, { b: 1 })).toEqual(false); | ||
expect(validate(rule, { a: 1, b: 1 })).toEqual(false); | ||
expect(validate(rule, { c: 1 })).toEqual(true); | ||
}); | ||
it('checks $not properly with `and`', () => { | ||
const rule = { $not: { $and: ['a', 'b'] } }; | ||
expect(validate(rule, { b: 1 })).toEqual(true); | ||
expect(validate(rule, { a: 1, b: 1 })).toEqual(false); | ||
expect(validate(rule, { c: 1 })).toEqual(true); | ||
}); | ||
it('checks nested $and properly', () => { | ||
@@ -20,0 +36,0 @@ const rule = { $and: [{ $and: ['a', 'b'] }, 'c'] }; |
{ | ||
"name": "object-key-validator", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "check objects for the existence of certain keys", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
4239
68