@nestjs/core
Version:
Nest - modern, fast, powerful node.js web framework (@core)
122 lines (121 loc) • 4.45 kB
JavaScript
import { Transform } from 'stream';
import { isNil, isObject, isUndefined } from '@nestjs/common/internal';
function serializeSseLines(value, prefix) {
return value
.split(/\r\n|\r|\n/)
.map(line => `${prefix}${line}\n`)
.join('');
}
function toDataString(data) {
if (isObject(data)) {
return toDataString(JSON.stringify(data));
}
return serializeSseLines(data, 'data: ');
}
function toCommentString(comment) {
return serializeSseLines(comment, ': ');
}
function isCommentOnly(message) {
return (!isNil(message.comment) &&
isUndefined(message.data) &&
isUndefined(message.type) &&
isUndefined(message.retry));
}
/**
* Adapted from https://raw.githubusercontent.com/EventSource/node-ssestream
* Transforms "messages" to W3C event stream content.
* See https://html.spec.whatwg.org/multipage/server-sent-events.html
* A message is an object with one or more of the following properties:
* - data (String or object, which gets turned into JSON)
* - type
* - id
* - retry
* - comment
*
* If constructed with a HTTP Request, it will optimise the socket for streaming.
* If this stream is piped to an HTTP Response, it will set appropriate headers.
*/
export class SseStream extends Transform {
lastEventId = null;
_headersCommitted = false;
_destination = null;
_statusCode = 200;
_additionalHeaders;
constructor(req) {
super({ objectMode: true });
if (req && req.socket) {
req.socket.setKeepAlive(true);
req.socket.setNoDelay(true);
req.socket.setTimeout(0);
}
}
get headersCommitted() {
return this._headersCommitted;
}
pipe(destination, options) {
this._destination = destination;
this._statusCode = options?.statusCode ?? 200;
this._additionalHeaders = options?.additionalHeaders;
return super.pipe(destination, options);
}
/**
* Writes SSE headers to the destination if they have not been sent yet.
* Headers are deferred until the first message so that, if the observable
* errors before any data is emitted, the HTTP status code can still be
* changed by an exception filter.
*/
commitHeaders() {
if (this._headersCommitted || !this._destination) {
return;
}
if (this._destination.writableEnded) {
return;
}
this._headersCommitted = true;
const statusCode = this._statusCode ?? 200;
const additionalHeaders = this._additionalHeaders;
if (this._destination.writeHead) {
this._destination.writeHead(statusCode, {
...additionalHeaders,
// See https://github.com/dunglas/mercure/blob/main/subscribe.go#L347-L362
'Content-Type': 'text/event-stream',
Connection: 'keep-alive',
// Disable cache, even for old browsers and proxies
'Cache-Control': 'private, no-cache, no-store, must-revalidate, max-age=0, no-transform',
Pragma: 'no-cache',
Expire: '0',
// NGINX support https://www.nginx.com/resources/wiki/start/topics/examples/x-accel/#x-accel-buffering
'X-Accel-Buffering': 'no',
});
this._destination.flushHeaders?.();
}
this._destination.write('\n');
}
_transform(message, encoding, callback) {
this.commitHeaders();
const sanitize = (val) => String(val).replace(/[\r\n]/g, '');
let data = message.type ? `event: ${sanitize(message.type)}\n` : '';
data += !isNil(message.id) ? `id: ${sanitize(message.id)}\n` : '';
data += !isNil(message.retry) ? `retry: ${sanitize(message.retry)}\n` : '';
data += !isNil(message.comment) ? toCommentString(message.comment) : '';
data += !isNil(message.data) ? toDataString(message.data) : '';
data += '\n';
this.push(data);
callback();
}
/**
* Calls `.write` but handles the drain if needed
*/
writeMessage(message, cb) {
if (isNil(message.id) && !isCommentOnly(message)) {
this.lastEventId++;
message.id = this.lastEventId.toString();
}
if (!this.write(message, 'utf-8')) {
this.once('drain', cb);
}
else {
process.nextTick(cb);
}
}
}