Skip to content

Commit

Permalink
lib: use validators
Browse files Browse the repository at this point in the history
Used more validators for the sake of consistency.

PR-URL: #39663
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
  • Loading branch information
VoltrexKeyva authored and targos committed Sep 4, 2021
1 parent 9c33e4b commit dbaf498
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
26 changes: 18 additions & 8 deletions lib/internal/util.js
Expand Up @@ -26,7 +26,6 @@ const {

const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_NO_CRYPTO,
ERR_UNKNOWN_SIGNAL
},
Expand Down Expand Up @@ -83,6 +82,8 @@ function isError(e) {
// each one once.
const codesWarned = new Set();

let validateString;

// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
Expand All @@ -91,8 +92,12 @@ function deprecate(fn, msg, code) {
return fn;
}

if (code !== undefined && typeof code !== 'string')
throw new ERR_INVALID_ARG_TYPE('code', 'string', code);
// Lazy-load to avoid a circular dependency.
if (validateString === undefined)
({ validateString } = require('internal/validators'));

if (code !== undefined)
validateString(code, 'code');

let warned = false;
function deprecated(...args) {
Expand Down Expand Up @@ -307,15 +312,20 @@ function getSystemErrorMap() {
const kCustomPromisifiedSymbol = SymbolFor('nodejs.util.promisify.custom');
const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs');

let validateFunction;

function promisify(original) {
if (typeof original !== 'function')
throw new ERR_INVALID_ARG_TYPE('original', 'Function', original);
// Lazy-load to avoid a circular dependency.
if (validateFunction === undefined)
({ validateFunction } = require('internal/validators'));

validateFunction(original, 'original');

if (original[kCustomPromisifiedSymbol]) {
const fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') {
throw new ERR_INVALID_ARG_TYPE('util.promisify.custom', 'Function', fn);
}

validateFunction(fn, 'util.promisify.custom');

return ObjectDefineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
Expand Down
6 changes: 6 additions & 0 deletions lib/internal/validators.js
Expand Up @@ -233,6 +233,11 @@ const validateAbortSignal = hideStackFrames((signal, name) => {
}
});

const validateFunction = hideStackFrames((value, name) => {
if (typeof value !== 'function')
throw new ERR_INVALID_ARG_TYPE(name, 'Function', value);
});

module.exports = {
isInt32,
isUint32,
Expand All @@ -241,6 +246,7 @@ module.exports = {
validateBoolean,
validateBuffer,
validateEncoding,
validateFunction,
validateInt32,
validateInteger,
validateNumber,
Expand Down

0 comments on commit dbaf498

Please sign in to comment.