If you need complete control over the pub/sub mechanism, you can implement the CustomPubSub interface and pass it to the subscription.pubsub option.
Note: If you provide both pubsub and emitter in the configuration, emitter will be ignored.
To implement CustomPubSub, your class must provide:
subscribe(topic, queue, ...customArgs): Returns a Promise. The queue is a Readable stream where data is pushed. customArgs allows passing extra parameters (like offset) from the resolver.publish(event, callback): event contains topic and payload. The callback is invoked when the operation completes.
class CustomPubSub {
constructor () {
this.emitter = new EventEmitter()
}
async subscribe (topic, queue, offset) {
const listener = (value) => {
queue.push(value)
}
const close = () => {
this.emitter.removeListener(topic, listener)
}
this.emitter.on(topic, listener)
queue.close.push(close)
}
publish (event, callback) {
this.emitter.emit(event.topic, event.payload)
callback()
}
}
const pubsub = new CustomPubSub()
app.register(mercurius, {
schema,
resolvers: {
Subscription: {
retrieveItems: {
subscribe: (root, args, { pubsub }) => pubsub.subscribe('RETRIEVE_ITEMS', args.offset)
}
}
},
subscription: {
pubsub
}
})