4.0.0 • Published 2 months ago

fastify-sse-v2 v4.0.0

Weekly downloads
204
License
MIT
Repository
github
Last release
2 months ago

Fastify SSE Plugin

CI check npm version

Fastify plugin for sending Server-sent events.

For fastify@2.x use fastify-sse-v2@1.x!

How to use?

yarn add fastify-sse-v2

Register fastify-sse-v2 plugin into your fastify instance:

import {FastifySSEPlugin} from "fastify-sse-v2";

const server = fastify();
server.register(FastifySSEPlugin);

Sending events from AsyncIterable source

import {FastifySSEPlugin} from "fastify-sse-v2";

const server = fastify();
server.register(FastifySSEPlugin);

server.get("/", function (req, res) {
    res.sse((async function * source () {
          for (let i = 0; i < 10; i++) {
            sleep(2000);
            yield {id: String(i), data: "Some message"};
          }
    })());
});

Sending individual events

import {FastifySSEPlugin} from "fastify-sse-v2";

const server = fastify();
server.register(FastifySSEPlugin);

server.get("/", async function (req, res) {
    for (let i = 0; i < 10; i++) {
      await sleep(2000);
      res.sse({id: String(i), data: "Some message"});
    }
});

fastify.get('/listenForChanges', {}, (request, reply) => {
    const listenStream = fastify.db.watch('doc-uuid')
        .on('data', (data)=>reply.sse({ data: JSON.stringify(data) }))
        .on('delete', () => reply.sse({ event: 'close' }))
    request.socket.on('close', ()=>listenStream.end())
})
Note
  • When sending individual events, the connection is kept open until you call reply.sseContext.source.end() to terminate the stream.
Sending events from EventEmmiters
import {FastifySSEPlugin} from "fastify-sse-v2";
import {on} from "events";

const server = fastify();
server.register(FastifySSEPlugin);

server.get("/", function (req, res) {
    res.sse(
  (async function* () {
    for await (const [event] of on(eventEmmitter, "update")) {
      yield {
        event: event.name,
        data: JSON.stringify(event),
      };
    }
  })()
);
});
Note
  • to remove event listeners (or some other cleanup) when client closes connection, you can listen on connection closing event: request.socket.on('close', () => abortController.abort());
4.0.0

2 months ago

3.1.2

10 months ago

3.1.1

10 months ago

3.1.0

1 year ago

3.0.0

1 year ago

2.2.1

2 years ago

2.2.0

2 years ago

2.0.6

3 years ago

2.0.4

3 years ago

2.0.3

3 years ago

1.0.7

4 years ago

2.0.2

4 years ago

1.0.6

4 years ago

2.0.1

4 years ago

1.0.5

4 years ago

2.0.0

4 years ago

1.0.4

4 years ago

1.0.2

4 years ago

1.0.3

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago