fastify-sse icon indicating copy to clipboard operation
fastify-sse copied to clipboard

Upgrade to 1.x of fastify

Open edson-gaspar opened this issue 6 years ago • 7 comments

Any plan to upgrade to version 1.x of fastify dependence?

edson-gaspar avatar Mar 29 '18 15:03 edson-gaspar

Any update on this? There are three forks of this project and all of them are just to add this fix... Can it be merged?

piranna avatar Dec 19 '18 18:12 piranna

This can be clossed, just only it would be nice to publish a new version in npm (ideally with my new pull-request to add support for fastify 2.0).

piranna avatar Jan 11 '19 06:01 piranna

ppl you don't need an npm module for this. its basics.

// RFC: https://www.w3.org/TR/eventsource/

const EventStream = {
  setup(req, reply, closeCb) {
    reply.type('text/event-stream');
    reply.header('content-encoding', 'identity');
    reply.header('cache-control', 'no-cache');
    const stream = new require('stream').PassThrough({ allowHalfOpen: false });
    stream.on('error', e => {
      console.error(`EventStream Error: ${e.stack}`);
    });		
    stream.write('\n');
    req.raw.stream.on('close', async (...args) => {
      stream.ended = true;
      stream.end();
      await closeCb(...args);
    });
    reply.send(stream);
    return stream;
  },

  emit(stream, id, data) {
    if (null == stream || true === stream.ended) return;
    stream.write(`id: ${id}\n`);
    stream.write(`data: ${JSON.stringify(data)}\n\n`);
  },
};

app.get('/event-stream', async (req, reply) => {
  console.debug('user connected to event stream');
  const stream = EventStream.setup(req, reply, () => {
    console.debug('user disconnected from event stream.');
  });

  EventStream.emit(stream, 'userAdd', {
    name: req.user.name,
  });
});

ancms2600 avatar Jul 27 '19 19:07 ancms2600

@ancmikesmullin that's already quite a lot of code to come up with without mistakes.

Also, shouldn't SSE set the TCP keepalive flag?

wmertens avatar Aug 12 '19 20:08 wmertens

I should add I am using HTTP/2 :)

ancms2600 avatar Aug 12 '19 21:08 ancms2600

@ancmikesmullin That's why I'm looking into SSE, because websockets are so complex and SSE over HTTP/2 is so much simpler :)

I'm trying to find the best way to do GraphQL subscriptions and I think I'll be able to do a POST resulting in an event stream. Browsers don't support that but https://github.com/mpetazzoni/sse.js does.

So what you mean is that with HTTP/2, setting TCP keepalive is not needed/not an option, right?

wmertens avatar Aug 13 '19 03:08 wmertens

Yes and I learned about it because I initially tried to set it, but got warnings in Firefox or something. Can't recall specifics but the error message was informative. Try it and see.

ancms2600 avatar Aug 13 '19 15:08 ancms2600