Skip to content

Commit a5b98b6

Browse files
committed
fix(validation): identify invalid types for non terminal optionals
1 parent cee7b83 commit a5b98b6

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

lib/util.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

3-
function validateParameter(parameter, spec) {
3+
function validateParameter(parameter, specs, specIndex) {
4+
const spec = specs[specIndex];
45
if (parameter == null && spec.required === false) {
56
return;
67
}
@@ -9,8 +10,13 @@ function validateParameter(parameter, spec) {
910
throw new TypeError(`Required parameter \`${spec.name}\` missing`);
1011
}
1112

12-
if (spec.type && typeof parameter !== spec.type) {
13-
if (spec.required === false) return false;
13+
const paramType = typeof parameter;
14+
if (spec.type && paramType !== spec.type) {
15+
if (spec.required === false) {
16+
if (specs.slice(specIndex).some(def => def.type === paramType)) {
17+
return false;
18+
}
19+
}
1420

1521
throw new TypeError(
1622
`Invalid type for parameter \`${spec.name}\`, expected \`${
@@ -48,7 +54,7 @@ function defineOperation(fn, paramDefs) {
4854
arg = {};
4955
}
5056

51-
if (validateParameter(arg, paramDefs[i])) {
57+
if (validateParameter(arg, paramDefs, i)) {
5258
params.push(arg);
5359
} else {
5460
argIdx--;

test/defineOperation_tests.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ describe('defineOperation', () => {
1515
expect(() => testMethod(42)).to.throw(/Invalid type for parameter/);
1616
});
1717

18+
it('should validate optional parameters, with valid parameters after', function() {
19+
expect(() => testMethod('llamas', false, true, () => {})).to.throw(
20+
/Invalid type for parameter `optionalString`/
21+
);
22+
});
23+
1824
it('should support defaults', function(done) {
1925
expect(() => testMethod('testing')).to.not.throw();
2026
testMethod('testing', true, err => {

0 commit comments

Comments
 (0)