Skip to content

Commit

Permalink
vm: consolidate validation
Browse files Browse the repository at this point in the history
PR-URL: #18816
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: Tiancheng "Timothy" Gu <[email protected]>
Reviewed-By: Luigi Pinca <[email protected]>
  • Loading branch information
timotew authored and addaleax committed Feb 26, 2018
1 parent 4fa1f31 commit 38797b5
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions lib/vm.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,22 +80,23 @@ Script.prototype.runInNewContext = function(sandbox, options) {
return this.runInContext(context, options);
};

function validateString(prop, propName) {
if (prop !== undefined && typeof prop !== 'string')
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', propName,
'string', prop);
}

function getContextOptions(options) {
const contextOptions = options ? {
name: options.contextName,
origin: options.contextOrigin
} : {};
if (contextOptions.name !== undefined &&
typeof contextOptions.name !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.contextName',
'string', contextOptions.name);
}
if (contextOptions.origin !== undefined &&
typeof contextOptions.origin !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.contextOrigin',
'string', contextOptions.origin);
if (options) {
const contextOptions = {
name: options.contextName,
origin: options.contextOrigin
};
validateString(contextOptions.name, 'options.contextName');
validateString(contextOptions.origin, 'options.contextOrigin');
return contextOptions;
}
return contextOptions;
return {};
}

let defaultContextNameIndex = 1;
Expand All @@ -121,10 +122,7 @@ function createContext(sandbox, options) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.name',
'string', options.name);
}
if (options.origin !== undefined && typeof options.origin !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.origin',
'string', options.origin);
}
validateString(options.origin, 'options.origin');
} else {
options = {
name: `VM Context ${defaultContextNameIndex++}`
Expand Down

0 comments on commit 38797b5

Please sign in to comment.