Skip to content

Commit

Permalink
fix(define-operation): ensure optional parameters are considered
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mbroadst committed Nov 27, 2018
1 parent e94a365 commit cee7b83
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ function validateParameter(parameter, spec) {
}

if (spec.type && typeof parameter !== spec.type) {
if (spec.required === false) return false;

throw new TypeError(
`Invalid type for parameter \`${spec.name}\`, expected \`${
spec.type
}\` but found \`${typeof parameter}\``
);
}

return true;
}

/**
Expand All @@ -30,11 +34,11 @@ function defineOperation(fn, paramDefs) {
return function() {
const args = Array.prototype.slice.call(arguments);
const params = [];
for (let i = 0; i < paramDefs.length; ++i) {
for (let i = 0, argIdx = 0; i < paramDefs.length; ++i, ++argIdx) {
const def = paramDefs[i];
let arg = args[i];
let arg = args[argIdx];

if (def.default && arg == null) arg = def.default;
if (def.hasOwnProperty('default') && arg == null) arg = def.default;
if (def.type === 'object' && def.default != null) {
arg = Object.assign({}, def.default, arg);
}
Expand All @@ -44,11 +48,14 @@ function defineOperation(fn, paramDefs) {
arg = {};
}

validateParameter(arg, paramDefs[i]);
params.push(arg);
if (validateParameter(arg, paramDefs[i])) {
params.push(arg);
} else {
argIdx--;
}
}

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

params.push(callback);
fn.apply(this, params);
};
}
Expand Down

0 comments on commit cee7b83

Please sign in to comment.