diff options
author | Denys Otrishko <shishugi@gmail.com> | 2020-06-26 13:14:48 +0300 |
---|---|---|
committer | James M Snell <jasnell@gmail.com> | 2020-08-17 21:50:46 +0300 |
commit | 6726246dbb83e3251f080fc4729154d492f7e340 (patch) | |
tree | acb72cb1e8a5f4cdbdc1f77d0fec2f565d001df7 /lib/internal/validators.js | |
parent | c62cf1d9c50aa4d152f28f61df86a6faafa45093 (diff) |
lib: allow to validate enums with validateOneOf
PR-URL: https://github.com/nodejs/node/pull/34070
Reviewed-By: Zeyu Yang <himself65@outlook.com>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Diffstat (limited to 'lib/internal/validators.js')
-rw-r--r-- | lib/internal/validators.js | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/lib/internal/validators.js b/lib/internal/validators.js index deab53d4b82..71726f70051 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -13,6 +13,7 @@ const { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, + ERR_INVALID_OPT_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL, ERR_INVALID_CALLBACK, @@ -126,6 +127,21 @@ function validateNumber(value, name) { throw new ERR_INVALID_ARG_TYPE(name, 'number', value); } +const validateOneOf = hideStackFrames((value, name, oneOf, option = false) => { + if (!oneOf.includes(value)) { + const allowed = oneOf + .map((v) => (typeof v === 'string' ? `'${v}'` : String(v))) + .join(', '); + if (!option) { + const reason = 'must be one of: ' + allowed; + throw new ERR_INVALID_ARG_VALUE(name, value, reason); + } else { + const reason = 'Must be one of: ' + allowed; + throw new ERR_INVALID_OPT_VALUE(name, value, reason); + } + } +}); + function validateBoolean(value, name) { if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value); @@ -212,6 +228,7 @@ module.exports = { validateInteger, validateNumber, validateObject, + validateOneOf, validatePort, validateSignalName, validateString, |