Skip to content

Commit

Permalink
feat: add basic pubsub (#1277)
Browse files Browse the repository at this point in the history
  • Loading branch information
phawxby committed Apr 18, 2023
1 parent d51a3bd commit a85bf54
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/command.js
Expand Up @@ -24,6 +24,8 @@ export function throwIfInSubscriberMode(commandName, RedisMock) {
'psubscribeBuffer',
'unsubscribe',
'unsubscribeBuffer',
'pubsub',
'pubsubBuffer',
'punsubscribe',
'punsubscribeBuffer',
'ping',
Expand Down
1 change: 1 addition & 0 deletions src/commands/index.js
Expand Up @@ -76,6 +76,7 @@ export * from './psetex'
export * from './psubscribe'
export * from './pttl'
export * from './publish'
export * from './pubsub'
export * from './punsubscribe'
export * from './quit'
export * from './randomkey'
Expand Down
24 changes: 24 additions & 0 deletions src/commands/pubsub.js
@@ -0,0 +1,24 @@
import patternMatchesString from '../commands-utils/patternMatchesString'

export function pubsub(subCommand, pattern) {
switch (subCommand) {
case 'CHANNELS': {
let channels = []

this.channels?.instanceListeners?.forEach((instanceMap, channel) => {
channels.push(channel)
})

if (pattern) {
channels = channels.filter(x => patternMatchesString(pattern, x))
}

return channels
}
default: {
throw new Error('Currently not implemented as a mock')
}
}
}

export const pubsubBuffer = pubsub
57 changes: 57 additions & 0 deletions test/integration/commands/pubsub.js
@@ -0,0 +1,57 @@
import Redis from 'ioredis'

// eslint-disable-next-line import/no-relative-parent-imports
import { runTwinSuite } from '../../../test-utils'

const testChannels = ['emails', 'messages', 'feed']

runTwinSuite('pubsub', command => {
// @TODO Rewrite test suite so it runs on a real Redis instance
;(process.env.IS_E2E ? describe.skip : describe)(command, () => {
describe('CHANNELS', () => {
let redis

beforeEach(() => {
redis = new Redis({
host: 'pubsub',
})
})

afterEach(async () => {
await Promise.all(testChannels.map(x => redis.unsubscribe(x)))
})

test('should return 0 when publishing without subscribers', async () => {
expect(await redis[command]('CHANNELS')).toMatchObject([])
})

it('should return the single active channel', async () => {
redis.subscribe('emails')

expect(await redis[command]('CHANNELS')).toMatchObject(['emails'])
})

it('should return multiple active channels', async () => {
redis.subscribe('emails')
redis.subscribe('messages')
redis.subscribe('feed')

expect(await redis[command]('CHANNELS')).toMatchObject([
'emails',
'messages',
'feed',
])
})

it('should return filtered channels', async () => {
redis.subscribe('emails')
redis.subscribe('messages')
redis.subscribe('feed')

expect(await redis[command]('CHANNELS', 'email*')).toMatchObject([
'emails',
])
})
})
})
})

0 comments on commit a85bf54

Please sign in to comment.