Skip to content

Commit

Permalink
crypto: extract throwInvalidArgType function
Browse files Browse the repository at this point in the history
This commit extracts the throwing of ERR_INVALID_ARG_TYPE which is done
in identical ways in a few places in cipher.js.

The motivation for this is that I think it improves readability enough to
warrant a commit even though I'm aware that we should avoid commits with
only these sort of refactoring.

PR-URL: #22947
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
danbev authored and targos committed Oct 4, 2018
1 parent 7d21cc2 commit f98d441
Showing 1 changed file with 12 additions and 20 deletions.
32 changes: 12 additions & 20 deletions lib/internal/crypto/cipher.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,19 @@ function createCipherBase(cipher, credential, options, decipher, iv) {
LazyTransform.call(this, options);
}

function invalidArrayBufferView(name, value) {
return new ERR_INVALID_ARG_TYPE(
name,
['string', 'Buffer', 'TypedArray', 'DataView'],
value
);
}

function createCipher(cipher, password, options, decipher) {
validateString(cipher, 'cipher');
password = toBuf(password);
if (!isArrayBufferView(password)) {
throw new ERR_INVALID_ARG_TYPE(
'password',
['string', 'Buffer', 'TypedArray', 'DataView'],
password
);
throw invalidArrayBufferView('password', password);
}

createCipherBase.call(this, cipher, password, options, decipher);
Expand All @@ -101,20 +105,12 @@ function createCipherWithIV(cipher, key, options, decipher, iv) {
validateString(cipher, 'cipher');
key = toBuf(key);
if (!isArrayBufferView(key)) {
throw new ERR_INVALID_ARG_TYPE(
'key',
['string', 'Buffer', 'TypedArray', 'DataView'],
key
);
throw invalidArrayBufferView('key', key);
}

iv = toBuf(iv);
if (iv !== null && !isArrayBufferView(iv)) {
throw new ERR_INVALID_ARG_TYPE(
'iv',
['string', 'Buffer', 'TypedArray', 'DataView'],
iv
);
throw invalidArrayBufferView('iv', iv);
}
createCipherBase.call(this, cipher, key, options, decipher, iv);
}
Expand Down Expand Up @@ -149,11 +145,7 @@ Cipher.prototype.update = function update(data, inputEncoding, outputEncoding) {
outputEncoding = outputEncoding || encoding;

if (typeof data !== 'string' && !isArrayBufferView(data)) {
throw new ERR_INVALID_ARG_TYPE(
'data',
['string', 'Buffer', 'TypedArray', 'DataView'],
data
);
throw invalidArrayBufferView('data', data);
}

const ret = this._handle.update(data, inputEncoding);
Expand Down

0 comments on commit f98d441

Please sign in to comment.