Skip to content

Commit cee7b83

Browse files
committed
fix(define-operation): ensure optional parameters are considered
In one case (`checkPassword`) we support an optional parameter, so `defineOperation` needs to take this into account, and modify the current parameter index during validation. fixes NODE-1770
1 parent e94a365 commit cee7b83

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

lib/util.js

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,16 @@ function validateParameter(parameter, spec) {
1010
}
1111

1212
if (spec.type && typeof parameter !== spec.type) {
13+
if (spec.required === false) return false;
14+
1315
throw new TypeError(
1416
`Invalid type for parameter \`${spec.name}\`, expected \`${
1517
spec.type
1618
}\` but found \`${typeof parameter}\``
1719
);
1820
}
21+
22+
return true;
1923
}
2024

2125
/**
@@ -30,11 +34,11 @@ function defineOperation(fn, paramDefs) {
3034
return function() {
3135
const args = Array.prototype.slice.call(arguments);
3236
const params = [];
33-
for (let i = 0; i < paramDefs.length; ++i) {
37+
for (let i = 0, argIdx = 0; i < paramDefs.length; ++i, ++argIdx) {
3438
const def = paramDefs[i];
35-
let arg = args[i];
39+
let arg = args[argIdx];
3640

37-
if (def.default && arg == null) arg = def.default;
41+
if (def.hasOwnProperty('default') && arg == null) arg = def.default;
3842
if (def.type === 'object' && def.default != null) {
3943
arg = Object.assign({}, def.default, arg);
4044
}
@@ -44,11 +48,14 @@ function defineOperation(fn, paramDefs) {
4448
arg = {};
4549
}
4650

47-
validateParameter(arg, paramDefs[i]);
48-
params.push(arg);
51+
if (validateParameter(arg, paramDefs[i])) {
52+
params.push(arg);
53+
} else {
54+
argIdx--;
55+
}
4956
}
5057

51-
const callback = params.pop();
58+
const callback = arguments[arguments.length - 1];
5259
if (typeof callback !== 'function') {
5360
return new Promise((resolve, reject) => {
5461
params.push((err, response) => {
@@ -60,7 +67,6 @@ function defineOperation(fn, paramDefs) {
6067
});
6168
}
6269

63-
params.push(callback);
6470
fn.apply(this, params);
6571
};
6672
}

0 commit comments

Comments
 (0)