Open edson-gaspar opened 6 years ago
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?
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).
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,
});
});
@ancmikesmullin that's already quite a lot of code to come up with without mistakes.
Also, shouldn't SSE set the TCP keepalive flag?
I should add I am using HTTP/2 :)
@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?
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.
Any plan to upgrade to version 1.x of fastify dependence?