Skip to content

Shiva127/fastify-event-bus

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fastify-event-bus

CI npm JavaScript Style Guide

Event bus support for Fastify. Built upon js-event-bus.

Install

yarn add fastify-event-bus
# or
npm install fastify-event-bus

Usage

import Fastify from "fastify";

const fastify = Fastify();

await fastify.register(import("fastify-event-bus"));
await fastify.register(import("@fastify/websocket"));

fastify.get("/ws", { websocket: true }, (connection, request) => {
  function sendHello(who) {
    request.log.debug(`Send Hello ${who}!`);
    connection.socket.send(`Hello ${who}!`);
  }
  fastify.eventBus.on("hello.send", sendHello); // <- register to the event

  connection.socket.on("close", () => {
    fastify.eventBus.detach("hello.send", sendHello); // <- detach the event
  });
});

fastify.get("/hello-world", async (request, reply) => {
  fastify.eventBus.emit("hello.send", null, "World"); // <- emit the event
});

await fastify.listen({ port: 3000 });

For more information and options, you can check js-event-bus API documentation.

License

Copyright Gilles Marchand, licensed under MIT.