passing-notes-sse
v1.2.6
Published
A middleware for sending and receiving server-sent events
Downloads
13
Readme
passing-notes-sse
A middleware for sending and receiving server-sent events.
Usage
Install passing-notes-sse by running:
yarn add passing-notes-sse
This library provides a middleware that takes requests and responses with header:
Content-Type: text/event-stream
It serializes/deserializes between raw text event streams and
async iterators
(or ReadableStream
s)
of event objects like so:
import {setTimeout} from 'node:timers/promises'
import {compose} from 'passing-notes'
import * as sse from 'passing-notes-sse'
export default compose(
sse.serialize,
() => (request) => ({
status: 200,
headers: {
'Content-Type': 'text/event-stream'
},
body: new ReadableStream({
async pull(controller) {
await setTimeout(1000)
controller.enqueue({ data: 'Hello World!' })
}
})
})
)
import {compose, sendRequest as sendRequestBase} from 'passing-notes'
import deserializeSse from 'passing-notes-sse'
const sendRequest = compose(
sse.deserialize,
() => sendRequest
)
const response = await sendRequest({
method: 'GET',
url: 'http://localhost:8080'
})
for await (const event of stream) {
console.log(event)
// { data: 'Hello World!' }
}