Event bus support for Fastify. Built upon js-event-bus.
yarn add fastify-event-bus
# or
npm install fastify-event-bus
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.
Copyright Gilles Marchand, licensed under MIT.