1.0.1 • Published 9 months ago

microservice-nats-comm v1.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
9 months ago

microservice-nats-comm

microservice-nats-comm is an easy-to-use communication package that simplifies message publishing and subscribing between microservices using Express.js and NATS Streaming. It abstracts the complexity of connecting to and interacting with a NATS Streaming server, enabling smooth communication in a microservices architecture. Installation

Install the package using npm:

npm install microservice-nats-comm

Features

Publish messages to any NATS Streaming subject.
Subscribe to subjects and handle incoming messages.
Automatic connection and error handling for NATS Streaming.

Usage

Below are examples showing how to use this package in two microservices: one that publishes messages, and another that subscribes to them.

1. Publisher Microservice

The publisher microservice sends messages to a specific subject. Example Setup

const express = require('express');
const NATSClient = require('microservice-nats-comm');

const app = express();
const port = 3000;

// Create a NATS client instance
const natsClient = new NATSClient('test-cluster', 'publisher-microservice');

// Connect to NATS and publish a message on request
natsClient.connect().then(() => {
    console.log('Connected to NATS as Publisher.');

    // Publish a message when the /publish route is called
    app.post('/publish', (req, res) => {
        const message = 'Hello from Publisher to Subscriber!';

        natsClient.publish('event-channel', message)
            .then((guid) => {
                console.log(`Message published with GUID: ${guid}`);
                res.status(200).send(`Message published: ${message}`);
            })
            .catch(err => {
                console.error('Error publishing message:', err);
                res.status(500).send('Failed to publish message');
            });
    });
}).catch(err => {
    console.error('Failed to connect to NATS:', err);
});

app.listen(port, () => {
    console.log(`Publisher microservice running at http://localhost:${port}`);
}); 

2. Subscriber Microservice

The subscriber microservice listens to a subject and processes incoming messages. Example Setup

const express = require('express');
const NATSClient = require('microservice-nats-comm');

const app = express();
const port = 3001;

// Create a NATS client instance
const natsClient = new NATSClient('test-cluster', 'subscriber-microservice');

// Connect to NATS and subscribe to the 'event-channel'
natsClient.connect().then(() => {
    console.log('Connected to NATS as Subscriber.');

    // Subscribe to the subject 'event-channel'
    natsClient.subscribe('event-channel', (msg) => {
        const message = msg.getData();
        console.log(`Message received: ${message}`);
    });
}).catch(err => {
    console.error('Failed to connect to NATS:', err);
});

app.listen(port, () => {
    console.log(`Subscriber microservice running at http://localhost:${port}`);
});

Configuration

When creating a NATSClient instance, you must pass three parameters:

clusterId: The NATS Streaming cluster ID.
clientId: A unique client ID for each microservice (should differ between Publisher and Subscriber).
natsUrl (optional): The URL of the NATS Streaming server. If not provided, it defaults to nats://localhost:4222.

javascript

const natsClient = new NATSClient(clusterId, clientId, [natsUrl]);

    clusterId: The NATS cluster identifier (e.g., 'test-cluster').
    clientId: The unique client identifier for the microservice (e.g., 'publisher-microservice' or 'subscriber-microservice').
    natsUrl (optional): The URL to the NATS Streaming server (default: 'nats://localhost:4222').

API

The package provides the following methods:
connect()

Connects to the NATS Streaming server and returns a Promise that resolves when the connection is established.

natsClient.connect().then(() => {
    console.log('Connected to NATS');
}).catch(err => {
    console.error('Error connecting to NATS:', err);
});

publish(subject, message) Publishes a message to the specified subject.

subject: The name of the NATS subject/channel.
message: The message content to be published.
natsClient.publish('event-channel', 'Hello from Publisher!')
    .then((guid) => {
        console.log(`Message published with GUID: ${guid}`);
    })
    .catch(err => {
        console.error('Error publishing message:', err);
    });

subscribe(subject, callback)

Subscribes to a subject and listens for messages. The callback function will be called whenever a new message is received.

subject: The name of the NATS subject/channel.
callback: A function that takes a message object as its argument.
natsClient.subscribe('event-channel', (msg) => {
    console.log(`Message received: ${msg.getData()}`);
});

disconnect()

Closes the connection to NATS Streaming.

natsClient.disconnect();
console.log('Disconnected from NATS');

Error Handling

You can catch connection and publishing errors by using Promises or try-catch in an async/await setup:

natsClient.connect().catch((err) => {
    console.error('Failed to connect to NATS:', err);
});

Example with Environment Variables

You can configure the connection parameters using environment variables for flexibility:

Create a .env file in your microservice directories:
NATS_CLUSTER_ID=test-cluster
NATS_CLIENT_ID=publisher-microservice
NATS_URL=nats://localhost:4222

Load the variables and use them in your code:

require('dotenv').config();
const NATSClient = require('microservice-nats-comm');

const natsClient = new NATSClient(process.env.NATS_CLUSTER_ID, process.env.NATS_CLIENT_ID, process.env.NATS_URL);

License

This package is licensed under ISC. See the LICENSE file for more details.

1.0.1

9 months ago

1.0.0

9 months ago