Skip to content

Commit 87e5d59

Browse files
authored
feat: add isLibp2p function for type guarding (#3211)
Adds a function that detects libp2p-like objects.
1 parent 6a7d4b8 commit 87e5d59

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

packages/libp2p/src/index.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,3 +212,23 @@ export async function createLibp2p <T extends ServiceMap = ServiceMap> (options:
212212

213213
return node
214214
}
215+
216+
// a non-exhaustive list of methods found on the libp2p object
217+
const LIBP2P_METHODS = ['dial', 'dialProtocol', 'hangUp', 'handle', 'unhandle', 'getMultiaddrs', 'getProtocols']
218+
219+
/**
220+
* Returns true if the passed object is a libp2p node - this can be used for
221+
* type guarding in TypeScript.
222+
*/
223+
export function isLibp2p <T extends ServiceMap = ServiceMap> (obj?: any): obj is Libp2p<T> {
224+
if (obj == null) {
225+
return false
226+
}
227+
228+
if (obj instanceof Libp2pClass) {
229+
return true
230+
}
231+
232+
// if these are all functions it's probably a libp2p object
233+
return LIBP2P_METHODS.every(m => typeof obj[m] === 'function')
234+
}

packages/libp2p/test/core/core.spec.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { multiaddr } from '@multiformats/multiaddr'
44
import { expect } from 'aegir/chai'
55
import { stubInterface } from 'sinon-ts'
6-
import { createLibp2p } from '../../src/index.js'
6+
import { createLibp2p, isLibp2p } from '../../src/index.js'
77
import type { Libp2p, Transport } from '@libp2p/interface'
88

99
describe('core', () => {
@@ -19,6 +19,19 @@ describe('core', () => {
1919
expect(libp2p).to.have.property('status', 'started')
2020
})
2121

22+
it('should detect the libp2p type', async () => {
23+
libp2p = await createLibp2p()
24+
25+
expect(isLibp2p(libp2p)).to.be.true()
26+
})
27+
28+
it('should not detect the libp2p type', async () => {
29+
expect(isLibp2p({})).to.be.false()
30+
expect(isLibp2p()).to.be.false()
31+
expect(isLibp2p(null)).to.be.false()
32+
expect(isLibp2p(undefined)).to.be.false()
33+
})
34+
2235
it('should say an address is not dialable if we have no transport for it', async () => {
2336
libp2p = await createLibp2p()
2437

0 commit comments

Comments
 (0)