About
@discordjs/brokers is a powerful set of message brokers
Installation
Node.js 22.12.0 or newer is required.
npm install @discordjs/brokers
yarn add @discordjs/brokers
pnpm add @discordjs/brokersExample usage
These examples use ES modules.
pub sub
// publisher.js
import { PubSubRedisBroker } from '@discordjs/brokers';
import Redis from 'ioredis';
// Considering this only pushes events, the group and name are not important.
const broker = new PubSubRedisBroker(new Redis(), { group: 'noop', name: 'noop' });
await broker.publish('test', 'Hello World!');
await broker.destroy();
// subscriber.js
import { PubSubRedisBroker } from '@discordjs/brokers';
import Redis from 'ioredis';
const broker = new PubSubRedisBroker(new Redis(), {
// This is the consumer group name. You should make sure to not re-use this
// across different applications in your stack, unless you absolutely know
// what you're doing.
group: 'subscribers',
// With the assumption that this service will scale to more than one instance,
// you MUST ensure `UNIQUE_CONSUMER_ID` is unique across all of them and
// also deterministic (i.e. if instance-1 restarts, it should still be instance-1)
name: `consumer-${UNIQUE_CONSUMER_ID}`,
});
broker.on('test', ({ data, ack }) => {
console.log(data);
void ack();
});
await broker.subscribe(['test']);RPC
// caller.js
import { RPCRedisBroker } from '@discordjs/brokers';
import Redis from 'ioredis';
const broker = new RPCRedisBroker(new Redis(), { group: 'noop', name: 'noop' });
console.log(await broker.call('testcall', 'Hello World!'));
await broker.destroy();
// responder.js
import { RPCRedisBroker } from '@discordjs/brokers';
import Redis from 'ioredis';
const broker = new RPCRedisBroker(new Redis(), {
// Equivalent to the group/name in pubsub, refer to the previous example.
group: 'responders',
name: `consumer-${UNIQUE_ID}`,
});
broker.on('testcall', ({ data, ack, reply }) => {
console.log('responder', data);
void ack();
void reply(`Echo: ${data}`);
});
await broker.subscribe(['testcall']);Links
Guide (source) Also see the v13 to v14 Update Guide, which includes updated and removed items from the library.
Contributing
Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the
documentation.
See the contribution guide if you'd like to submit a PR.
Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official discord.js Server.