Skip to content

Commit cbfda2c

Browse files
authored
feat: add isKeychain function (#3473)
Add type guard function that allows detecting if a given object conforms to the KeyChain interface.
1 parent 69a4465 commit cbfda2c

3 files changed

Lines changed: 26 additions & 1 deletion

File tree

packages/keychain/src/index.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,3 +216,18 @@ export function keychain (init: KeychainInit = {}): (components: KeychainCompone
216216
return new KeychainClass(components, init)
217217
}
218218
}
219+
220+
export function isKeychain (obj?: any): obj is Keychain {
221+
if (obj == null) {
222+
return false
223+
}
224+
225+
return typeof obj.findKeyByName === 'function' &&
226+
typeof obj.findKeyById === 'function' &&
227+
typeof obj.importKey === 'function' &&
228+
typeof obj.exportKey === 'function' &&
229+
typeof obj.removeKey === 'function' &&
230+
typeof obj.renameKey === 'function' &&
231+
typeof obj.listKeys === 'function' &&
232+
typeof obj.rotateKeychainPass === 'function'
233+
}

packages/keychain/test/keychain.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { expect } from 'aegir/chai'
66
import { MemoryDatastore } from 'datastore-core/memory'
77
import { Key } from 'interface-datastore/key'
88
import { toString as uint8ArrayToString } from 'uint8arrays/to-string'
9+
import { isKeychain } from '../src/index.js'
910
import { Keychain as KeychainClass } from '../src/keychain.js'
1011
import { importPrivateKey } from '../src/utils/import.js'
1112
import type { KeychainInit, Keychain, KeyInfo } from '../src/index.js'
@@ -41,6 +42,16 @@ describe('keychain', () => {
4142
}()).to.eventually.be.ok()
4243
})
4344

45+
it('is a keychain', async () => {
46+
expect(isKeychain(ks)).to.be.true()
47+
})
48+
49+
it('should not be a keychain', async () => {
50+
expect(isKeychain()).to.be.false()
51+
expect(isKeychain({})).to.be.false()
52+
expect(isKeychain(true)).to.be.false()
53+
})
54+
4455
it('can override the self key name', async () => {
4556
const selfKey = 'other-key'
4657
const kc = new KeychainClass({

packages/keychain/test/utils/import-export.spec.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
/* eslint-env mocha */
21
import { generateKeyPair } from '@libp2p/crypto/keys'
32
import { expect } from 'aegir/chai'
43
import { base58btc } from 'multiformats/bases/base58'

0 commit comments

Comments
 (0)