Skip to content

Commit

Permalink
crypto: simplify KeyObject constructor
Browse files Browse the repository at this point in the history
Inline a function that only gets called in the constructor. Make call to
`super()` more straightforward in the process by removing conditional
involving the function as it only ever returns `undefined` or else
throws. That made the code a little hard to understand, as without
looking at the function, one would likely expect it to return `true`
on success rather than `undefined`.

PR-URL: #35064
Reviewed-By: Tobias Nießen <tniessen@tnie.de>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
  • Loading branch information
Trott authored and richardlau committed Sep 7, 2020
1 parent a12d92c commit 178a740
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions lib/internal/crypto/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,6 @@ for (const m of [[kKeyEncodingPKCS1, 'pkcs1'], [kKeyEncodingPKCS8, 'pkcs8'],
[kKeyEncodingSPKI, 'spki'], [kKeyEncodingSEC1, 'sec1']])
encodingNames[m[0]] = m[1];

function checkKeyTypeAndHandle(type, handle) {
if (type !== 'secret' && type !== 'public' && type !== 'private')
throw new ERR_INVALID_ARG_VALUE('type', type);
if (typeof handle !== 'object' || !(handle instanceof KeyObjectHandle))
throw new ERR_INVALID_ARG_TYPE('handle', 'object', handle);
}

// Creating the KeyObject class is a little complicated due to inheritance
// and that fact that KeyObjects should be transferrable between threads,
// which requires the KeyObject base class to be implemented in C++.
Expand All @@ -64,7 +57,12 @@ const [
// Publicly visible KeyObject class.
class KeyObject extends NativeKeyObject {
constructor(type, handle) {
super(checkKeyTypeAndHandle(type, handle) || handle);
if (type !== 'secret' && type !== 'public' && type !== 'private')
throw new ERR_INVALID_ARG_VALUE('type', type);
if (typeof handle !== 'object' || !(handle instanceof KeyObjectHandle))
throw new ERR_INVALID_ARG_TYPE('handle', 'object', handle);

super(handle);

this[kKeyType] = type;

Expand Down

0 comments on commit 178a740

Please sign in to comment.