diff --git a/package.json b/package.json index eb6f0ef..dfa8dd0 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "description": "Validate JSON objects with TypeScript-like interface specifications.", "main": "lib/interface-validator.js", "scripts": { + "pretest": "tsc", "test": "mocha", "prepublish": "tsc" }, @@ -23,14 +24,14 @@ }, "homepage": "https://github.com/hanlindev/interface-validator#readme", "dependencies": { - "@types/lodash": "^4.14.62", + "@types/lodash": "^4.14.95", "lodash": "^4.17.4" }, "devDependencies": { - "@types/chai": "^3.4.35", - "@types/mocha": "^2.2.40", + "@types/chai": "^3.5.2", + "@types/mocha": "^2.2.47", "chai": "^3.5.0", - "mocha": "^3.2.0" + "mocha": "^3.5.3" }, "types": "./lib/interface-validator.d.ts" } diff --git a/src/interface-validator.ts b/src/interface-validator.ts index 846dc0a..b54cdb6 100644 --- a/src/interface-validator.ts +++ b/src/interface-validator.ts @@ -24,7 +24,7 @@ export type PrimitiveTypes = 'string!' | 'string' | 'number' | 'number!' | 'boolean' | 'boolean!' - | 'object'; + | 'object' | object[]; /** * The key must be a valid variable name with an optional trailing question @@ -58,6 +58,15 @@ export function getMismatchedFields( return (isOptional) ? [] : [valueKey]; } + if (_.isArray(fieldSpecs[specName])) { + return values[valueKey].map((arrayValue, index) => { + return getMismatchedFields( + arrayValue, + fieldSpecs[specName][0] as Interface, + ).map((name) => `${valueKey}[${index}].${name}`); + }).filter((e) => e.length > 0) + } + return getMismatchedFields( values[valueKey], fieldSpecs[specName] as Interface, diff --git a/src/test/test-interface-validator.ts b/src/test/test-interface-validator.ts index 32b4759..931a729 100644 --- a/src/test/test-interface-validator.ts +++ b/src/test/test-interface-validator.ts @@ -16,6 +16,12 @@ describe('interface-validator getMismatchedFields', () => { }, string: 'nested str', }, + objectArray: [{ + string: 'str', + number: 0, + },{ + string: 'str' + }], castToNumber: '123', castToNumberFail: 'one', castToBoolean: 'true', @@ -131,4 +137,18 @@ describe('interface-validator getMismatchedFields', () => { expect(getMismatchedFields(tested, subSpecs)).to.be.empty; }); }); + + describe('nested array interface', () => { + const specs: Interface = { + number: 'number', + objectArray: [{ + string: 'string', + 'number?': 'number' + }] + }; + + it('returns empty array when all matched', () => { + expect(getMismatchedFields(tested, specs)).to.be.empty; + }) + }); }); \ No newline at end of file