From 3cb3618973bcf7817b55eb4fd96cc5fe7284cbd9 Mon Sep 17 00:00:00 2001 From: "Timothy O. Peters" Date: Mon, 12 Feb 2018 19:58:15 +0100 Subject: vm: consolidate validation PR-URL: https://github.com/nodejs/node/pull/18816 Reviewed-By: Ruben Bridgewater Reviewed-By: Tiancheng "Timothy" Gu Reviewed-By: Luigi Pinca --- lib/vm.js | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) (limited to 'lib/vm.js') diff --git a/lib/vm.js b/lib/vm.js index c9bb44f057..78a2de16d3 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -79,22 +79,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; @@ -120,10 +121,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++}` -- cgit v1.2.3