npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@sbs-def/express-nats-microservice

v1.0.1

Published

A simple Express.js and NATS Streaming package for inter-microservice communication

Downloads

80

Readme

Express NATS Microservice

A simple and efficient package for inter-microservice communication using Express.js and NATS Streaming. This package provides a streamlined way to publish and subscribe to messages between microservices, enabling reliable communication in a distributed architecture.

Features

  • NATS Streaming integration: Allows microservices to communicate asynchronously.
  • Publish/Subscribe Pattern: Supports both publishing messages and subscribing to topics.
  • Configurable Acknowledgment: Provides options for manual acknowledgment, ensuring reliable message delivery.
  • Express.js Compatible: Easily integrates with Express applications.

Installation

Install the package using npm:

npm install [email protected]

Getting Started

Step 1: Initialize and Configure

To start using the Express NATS Microservice package, first create an instance of the NatsMicroservice class, specifying the NATS Streaming cluster ID, client ID, and server URL.

const NatsMicroservice = require('express-nats-microservice');

const natsService = new NatsMicroservice('test-cluster', 'client-id', 'nats://localhost:4222');

Step 2: Connect to NATS Streaming

Use the connect method to establish a connection to the NATS Streaming server. This method returns a Promise, allowing asynchronous handling.

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

Step 3: Publish Messages

After connecting, use the publish method to send messages to a specific subject. This method takes a subject name and a message object.

natsService.publish('order', { event: 'order_created', data: { orderId: 123, userId: 456 } })
  .then((guid) => {
    console.log('Message published with GUID:', guid);
  })
  .catch((err) => {
    console.error('Failed to publish message:', err);
  });

Step 4: Subscribe to Messages

To receive messages, use the subscribe method, specifying the subject and a callback function to handle incoming messages. The callback receives parsed JSON data from the message.

natsService.subscribe('order', (message) => {
  console.log('Received message:', message);
});

Full Example

Here is a complete example that shows how to connect, publish, and subscribe to messages using the NatsMicroservice class.

const NatsMicroservice = require('express-nats-microservice');

const natsService = new NatsMicroservice('test-cluster', 'client-id', 'nats://localhost:4222');

async function start() {
  try {
    await natsService.connect();
    console.log('Connected to NATS');

    // Publish a message
    await natsService.publish('order', { event: 'order_created', data: { orderId: 123, userId: 456 } });
    console.log('Message published');

    // Subscribe to messages
    natsService.subscribe('order', (message) => {
      console.log('Received message:', message);
    });

  } catch (error) {
    console.error('Error starting the service:', error);
  }
}

start();

API Documentation

Class: NatsMicroservice

Constructor

new NatsMicroservice(clusterId, clientId, natsUrl)
  • clusterId (string): The ID of the NATS Streaming cluster.
  • clientId (string): The unique ID for the client connecting to NATS.
  • natsUrl (string): The URL of the NATS Streaming server.

Methods

  • connect()

    • Connects to the NATS Streaming server.
    • Returns: A Promise that resolves when the connection is established.
  • publish(subject, message)

    • Publishes a message to a specific subject.
    • Parameters:
      • subject (string): The name of the subject.
      • message (object): The message data to be published.
    • Returns: A Promise that resolves with the message GUID upon successful publication.
  • subscribe(subject, onMessage)

    • Subscribes to a subject to receive messages.
    • Parameters:
      • subject (string): The name of the subject to subscribe to.
      • onMessage (function): A callback function that processes incoming messages. Receives a parsed message object as an argument.

Error Handling

The package includes basic error handling for failed connections, publication errors, and subscription errors. It is recommended to use try-catch blocks or .catch() methods to handle potential issues in production environments.

Requirements

  • Node.js version 10 or higher
  • NATS Streaming server running and accessible

Example Use Case

This package is ideal for systems with microservices that need to communicate asynchronously, such as:

  • Order Processing: One service can publish an "order_created" event, which other services (e.g., inventory, billing) subscribe to and handle in real-time.
  • Notification Systems: Publish notifications to a message queue for real-time updates to subscribers.

License

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