Skip to content

Commit

Permalink
perf(node): use util.types.is* helpers when available
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed May 18, 2021
1 parent e0ce916 commit d36311d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
18 changes: 16 additions & 2 deletions src/runtime/node/is_key_object.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
import { KeyObject } from 'crypto'
import * as util from 'util'

export default function isKeyObject(obj: unknown): obj is KeyObject {
return obj != null && obj instanceof KeyObject
// eslint-disable-next-line import/no-mutable-exports
let impl: (obj: unknown) => obj is KeyObject

// @ts-expect-error
if (util.types.isKeyObject) {
impl = function isKeyObject(obj): obj is KeyObject {
// @ts-expect-error
return <boolean>util.types.isKeyObject(obj)
}
} else {
impl = function isKeyObject(obj): obj is KeyObject {
return obj != null && obj instanceof KeyObject
}
}

export default impl
24 changes: 19 additions & 5 deletions src/runtime/node/webcrypto.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,32 @@
import * as crypto from 'crypto'
import * as util from 'util'

// @ts-expect-error
const webcrypto = <Crypto>crypto.webcrypto

export default webcrypto
export function isCryptoKey(key: unknown): key is CryptoKey {
if (webcrypto !== undefined) {

let impl: (obj: unknown) => obj is CryptoKey

// @ts-expect-error
if (util.types.isCryptoKey) {
impl = function isCryptoKey(obj): obj is CryptoKey {
// @ts-expect-error
return key != null && key instanceof webcrypto.CryptoKey
return <boolean>util.types.isCryptoKey(obj)
}

return false
} else if (webcrypto) {
impl = function isCryptoKey(obj): obj is CryptoKey {
//@ts-expect-error
return obj != null && obj instanceof webcrypto.CryptoKey;
}
} else {
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/no-unused-vars
impl = (obj): obj is CryptoKey => false
}

export { impl as isCryptoKey }

function getHashLength(hash: KeyAlgorithm) {
return parseInt(hash?.name.substr(4), 10)
}
Expand Down

0 comments on commit d36311d

Please sign in to comment.