@simplecomercio/rabbitmq-rpc
v1.3.2
Published
This custom npm module exports several functions that can be used to interact with a RabbitMQ server using the Remote Procedure Call (RPC) pattern and the AMQP protocol (Advanced Message Queuing Protocol).
Downloads
32
Readme
This custom npm module exports several functions that can be used to interact with a RabbitMQ server using the Remote Procedure Call (RPC) pattern and the AMQP protocol (Advanced Message Queuing Protocol).
This module allows for communication between different applications or services through the use of queues and message routing. It uses the AMQP protocol and the amqplib library to connect to a RabbitMQ server and send and receive messages.
Main function:
connect(uri:string): Promise<IRPCService>
: This function connects to a RabbitMQ server using the provided URI and returns an object that contains several methods that can be used to interact with the server.
The IRPCService
object contains the following methods:
getStatus(): Promise<Boolean>
: which returns true if the channel is initialized and connected to the server, otherwise false.
publishToQueue(queueName: string, data: any): Promise<RPCResponse>
: which sends a message to a specific queue.
createRouter(): Router
: which creates a new router object that can be used to route messages to different queues.
The Router
object contains the following methods:
route(queueName: string, cb: (obj: any) => void)
: which sets up a route to listen for messages on a queue. It takes a queueName
string and a callback function as inputs. The queueName
is the name of the queue on which to listen for messages, and the callback function is called for each message received. The callback function takes an argument obj
which is the content of the message
Here's an example of how to use it:
import { connect, rpc } from '@simplecomercio/rabbitmq-rpc';
const rpcService = await connect('amqp://localhost:5672');
const isConnected = await rpc.getStatus();
if (isConnected)
console.log('RabbitMQ Server connection is up');
To route messages to different queues, you can use the createRouter method to create a new router object and the route method to define the routing rules.
const router = rpc.createRouter();
router.route('queue-name', (obj: any) => {
const { name: string } = obj
const greetings = `Hello ${name}`
return {
status: 200,
details: 'success',
data: greetings
}
});
You could then use the publishToQueue method to send a message to a specific queue.
const { status, details, data: greetings } = await rpcService.publishToQueue('queue-name', { name: 'Juan' });
console.log(greetings); // Hello Juan