Skip to content

Commit ad98ff1

Browse files
timotewaddaleax
authored andcommitted
vm: consolidate validation
PR-URL: nodejs#18816 Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Tiancheng "Timothy" Gu <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent 9d73910 commit ad98ff1

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

Diff for: lib/vm.js

+16-18
Original file line numberDiff line numberDiff line change
@@ -80,22 +80,23 @@ Script.prototype.runInNewContext = function(sandbox, options) {
8080
return this.runInContext(context, options);
8181
};
8282

83+
function validateString(prop, propName) {
84+
if (prop !== undefined && typeof prop !== 'string')
85+
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', propName,
86+
'string', prop);
87+
}
88+
8389
function getContextOptions(options) {
84-
const contextOptions = options ? {
85-
name: options.contextName,
86-
origin: options.contextOrigin
87-
} : {};
88-
if (contextOptions.name !== undefined &&
89-
typeof contextOptions.name !== 'string') {
90-
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.contextName',
91-
'string', contextOptions.name);
92-
}
93-
if (contextOptions.origin !== undefined &&
94-
typeof contextOptions.origin !== 'string') {
95-
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.contextOrigin',
96-
'string', contextOptions.origin);
90+
if (options) {
91+
const contextOptions = {
92+
name: options.contextName,
93+
origin: options.contextOrigin
94+
};
95+
validateString(contextOptions.name, 'options.contextName');
96+
validateString(contextOptions.origin, 'options.contextOrigin');
97+
return contextOptions;
9798
}
98-
return contextOptions;
99+
return {};
99100
}
100101

101102
let defaultContextNameIndex = 1;
@@ -121,10 +122,7 @@ function createContext(sandbox, options) {
121122
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.name',
122123
'string', options.name);
123124
}
124-
if (options.origin !== undefined && typeof options.origin !== 'string') {
125-
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.origin',
126-
'string', options.origin);
127-
}
125+
validateString(options.origin, 'options.origin');
128126
} else {
129127
options = {
130128
name: `VM Context ${defaultContextNameIndex++}`

0 commit comments

Comments
 (0)