From be195e00a403ea366d00f32e0cff3bf8471d6039 Mon Sep 17 00:00:00 2001 From: Robert Ende Date: Mon, 26 Nov 2018 11:28:38 +0100 Subject: [PATCH] feat: replace/extend default HTTP headers with custom ones Added a new (optional) argument to the pipe() function that adds the ability to replace the default HTTP headers for the request, or add custom ones. Includes additional test and updated README.md --- README.md | 3 ++- index.js | 17 ++++++++++++++--- test/ssestream_test.js | 20 ++++++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f14d30d..04db275 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,11 @@ In a `(req, res)` handler for a [`request`](https://nodejs.org/api/http.html#htt ```javascript const SseStream = require('ssestream') +const customHeaders = {'Cache-Control': 'no-cache, no-transform'} // optional function (req, res) { const sse = new SseStream(req) - sse.pipe(res) + sse.pipe(res, undefined, customHeaders) const message = { data: 'hello\nworld', diff --git a/index.js b/index.js index 8444adb..fc7975e 100644 --- a/index.js +++ b/index.js @@ -30,14 +30,25 @@ class SseStream extends Stream.Transform { } } - pipe(destination, options) { + /** + * Similar to {@link Stream.Transform.push} with the addition of specifying custom HTTP headers. + */ + pipe(destination, options, customHeaders) { if (typeof destination.writeHead === 'function') { - destination.writeHead(200, { + var defaultHeaders = { 'Content-Type': 'text/event-stream; charset=utf-8', 'Transfer-Encoding': 'identity', 'Cache-Control': 'no-cache', Connection: 'keep-alive', - }) + } + + // replace/extend default headers + if (customHeaders) { + for (const header of Object.keys(customHeaders)) { + defaultHeaders[header] = customHeaders[header] + } + } + destination.writeHead(200, defaultHeaders) destination.flushHeaders() } // Some clients (Safari) don't trigger onopen until the first frame is received. diff --git a/test/ssestream_test.js b/test/ssestream_test.js index ed949e4..f1df0bb 100644 --- a/test/ssestream_test.js +++ b/test/ssestream_test.js @@ -103,6 +103,26 @@ data: hello sse.pipe(sink) }) + + it('extends and replaces default headers with custom ones', callback => { + sink.writeHead = (status, headers) => { + assert.deepEqual(headers, { + 'Content-Type': 'text/event-stream; charset=utf-8', + 'Transfer-Encoding': 'identity', + // 'Cache-Control': 'no-cache', + 'Connection': 'keep-alive', + 'Cache-Control': 'no-cache, no-transform', // replace existing header + 'Custom-Header': 'foo' // add custom header + }) + callback() + } + const customHeaders = { + 'Cache-Control': 'no-cache, no-transform', // replace existing header + 'Custom-Header': 'foo' // add custom header + } + sse.pipe(sink, undefined, customHeaders) + }) + it('allows an eventsource to connect', callback => { const server = http.createServer((req, res) => { sse = new SseStream(req)