Skip to content

Commit

Permalink
feat: add isPubSub method to detect PubSub implementations (#2707)
Browse files Browse the repository at this point in the history
Adds a type guard function to signal to tsc that an object
implements the PubSub interface.
  • Loading branch information
achingbrain committed Sep 19, 2024
1 parent b0c0681 commit 6ccbb06
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
6 changes: 5 additions & 1 deletion packages/interface-compliance-tests/src/pubsub/api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isStartable, start, stop } from '@libp2p/interface'
import { isPubSub, isStartable, start, stop } from '@libp2p/interface'
import { expect } from 'aegir/chai'
import delay from 'delay'
import pDefer from 'p-defer'
Expand Down Expand Up @@ -39,6 +39,10 @@ export default (common: TestSetup<PubSub, PubSubArgs>): void => {
mockNetwork.reset()
})

it('is a PubSub implementation', () => {
expect(isPubSub(pubsub)).to.be.true()
})

it('can start correctly', async () => {
if (!isStartable(pubsub)) {
return
Expand Down
13 changes: 13 additions & 0 deletions packages/interface/src/pubsub/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,3 +268,16 @@ export interface PeerStreamEvents {
'stream:outbound': CustomEvent<never>
'close': CustomEvent<never>
}

/**
* All Pubsub implementations must use this symbol as the name of a property
* with a boolean `true` value
*/
export const pubSubSymbol = Symbol.for('@libp2p/pubsub')

/**
* Returns true if the passed argument is a PubSub implementation
*/
export function isPubSub (obj?: any): obj is PubSub {
return Boolean(obj?.[pubSubSymbol])
}
4 changes: 3 additions & 1 deletion packages/pubsub-floodsub/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
* ```
*/

import { serviceDependencies } from '@libp2p/interface'
import { pubSubSymbol, serviceDependencies } from '@libp2p/interface'
import { PubSubBaseProtocol, type PubSubComponents } from '@libp2p/pubsub'
import { toString } from 'uint8arrays/to-string'
import { SimpleTimeCache } from './cache.js'
Expand Down Expand Up @@ -78,6 +78,8 @@ export class FloodSub extends PubSubBaseProtocol {
})
}

readonly [pubSubSymbol] = true

readonly [Symbol.toStringTag] = '@libp2p/floodsub'

readonly [serviceDependencies]: string[] = [
Expand Down

0 comments on commit 6ccbb06

Please sign in to comment.