Skip to content

Commit 6ccbb06

Browse files
authored
feat: add isPubSub method to detect PubSub implementations (#2707)
Adds a type guard function to signal to tsc that an object implements the PubSub interface.
1 parent b0c0681 commit 6ccbb06

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

packages/interface-compliance-tests/src/pubsub/api.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { isStartable, start, stop } from '@libp2p/interface'
1+
import { isPubSub, isStartable, start, stop } from '@libp2p/interface'
22
import { expect } from 'aegir/chai'
33
import delay from 'delay'
44
import pDefer from 'p-defer'
@@ -39,6 +39,10 @@ export default (common: TestSetup<PubSub, PubSubArgs>): void => {
3939
mockNetwork.reset()
4040
})
4141

42+
it('is a PubSub implementation', () => {
43+
expect(isPubSub(pubsub)).to.be.true()
44+
})
45+
4246
it('can start correctly', async () => {
4347
if (!isStartable(pubsub)) {
4448
return

packages/interface/src/pubsub/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,16 @@ export interface PeerStreamEvents {
268268
'stream:outbound': CustomEvent<never>
269269
'close': CustomEvent<never>
270270
}
271+
272+
/**
273+
* All Pubsub implementations must use this symbol as the name of a property
274+
* with a boolean `true` value
275+
*/
276+
export const pubSubSymbol = Symbol.for('@libp2p/pubsub')
277+
278+
/**
279+
* Returns true if the passed argument is a PubSub implementation
280+
*/
281+
export function isPubSub (obj?: any): obj is PubSub {
282+
return Boolean(obj?.[pubSubSymbol])
283+
}

packages/pubsub-floodsub/src/index.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
* ```
3333
*/
3434

35-
import { serviceDependencies } from '@libp2p/interface'
35+
import { pubSubSymbol, serviceDependencies } from '@libp2p/interface'
3636
import { PubSubBaseProtocol, type PubSubComponents } from '@libp2p/pubsub'
3737
import { toString } from 'uint8arrays/to-string'
3838
import { SimpleTimeCache } from './cache.js'
@@ -78,6 +78,8 @@ export class FloodSub extends PubSubBaseProtocol {
7878
})
7979
}
8080

81+
readonly [pubSubSymbol] = true
82+
8183
readonly [Symbol.toStringTag] = '@libp2p/floodsub'
8284

8385
readonly [serviceDependencies]: string[] = [

0 commit comments

Comments
 (0)