@uplatform/event-bus

uPlatform - Event Bus Component ============================

Usage no npm install needed!

<script type="module">
  import uplatformEventBus from 'https://cdn.skypack.dev/@uplatform/event-bus';
</script>

README

uPlatform - Event Bus Component

npm version license

Usage

Step 1. Install the module

npm install --save @uplatform/event-bus

Step 2. Configure the event bus

const { EventBus } = require('@uplatform/event-bus');

const eventBus = new EventBus({
    name: 'my-service-1',
});

Step 3. Start NATS:

docker run --rm -it -p 127.0.0.1:4222:4222 -p 127.0.0.1:8222:8222 nats

Step 4. Start the application:

export NATS_URL=nats://127.0.0.1:4222
node app.js

Snippets

Publish an event

await eventBus.publish('users.registered', {
    id: 1,
    name: 'Alex',
});

Subscribe to events by type

await eventBus.subcribe(
    'users.registered',
    message => {
        console.log(message, '@', 'users.registered');
    },
);

Subscribe to events by mask

await eventBus.subcribe(
    'users.*',
    ({ subject, ...message }) => {
        console.log(message, '@', subject);
    },
);

Send a request

await eventBus.request(
    'calculator.sum',
    { a: 10, b: 20 },
    ({ sum }) => {
        console.log(`10 + 20 = ${sum}`);
    },
);

Reply to the request

await eventBus.subscribe(
    'calculator.sum',
    ({ a, b, reply }) => {
        reply({
            sum: a + b,
        });
    },
);