A Fastify RabbitMQ Plugin Developed in Pure TypeScript. It uses the node-rabbitmq-client plugin as a wrapper.
The build exports this to valid ESM and CJS for ease of cross-compatibility.
If you are using this NPM package, please consider giving it a ⭐ star. This will increase its visibility and solicit more contribution from the outside.
npm install fastify-rabbitmq
Register this as a plugin. Make sure it is loaded before any routes are loaded.
export default fp<FastifyRabbitMQOptions>((fastify, options, done) => {
void fastify.register(fastifyRabbit, {
connection: `amqp://guest:guest@localhost`,
});
void fastify.ready().then(async () => {
const consumer = fastify.rabbitmq.createConsumer(
{
queue: "foo",
queueOptions: { durable: true },
},
async (msg: any) => {
console.log(msg); // ==> bar
},
);
});
});
Within any "endpoint" function, or if you have access to fastify.rabbitmq
you can then call:
fastify.get("/rabbitmq", async (request, reply) => {
let pub = request.rabbitmq.createPublisher({
confirm: true,
maxAttempts: 1,
});
await pub.send("foo", "bar"); // ==> sent to foo queue
});
Sending the string bar
to the queue called foo
.
export interface FastifyRabbitMQOptions {
/** Connection String or object pointing to the RabbitMQ Broker Services */
connection: string | ConnectionOptions;
/** To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time. */
namespace?: string;
}
Connection String or object pointing to the RabbitMQ Broker Services.
This can be an object of ConnectionOptions
from the node-rabbitmq-client
plugin options.
If you need more than one "connection" to a different set and/or array of RabbitMQ servers, either on network or cloud, each registration of the plugin needs it to be in its own namespace. If the name space is duplicated, it will fail to load.
- node-rabbitmq-client
- fastify
- ... and my Wife and Baby Girl.
Licensed under MIT.