wsse-sdk
v3.0.0
Published
A browser SSE client with EventSource and Fetch ReadableStream transports.
Maintainers
Readme
wsse-sdk
浏览器 SSE 客户端,支持原生 EventSource 和 fetch + ReadableStream 两种模式。
EventSource 模式
默认使用原生 EventSource:
import SSEClient from 'wsse-sdk'
const client = new SSEClient('/events', {
withCredentials: true
})
client.on('open', event => {
console.log('连接成功', event)
})
client.on('message', event => {
console.log(event.data)
})
client.on('error', event => {
console.error('连接异常', event)
})也可以显式指定模式:
const client = new SSEClient('/events', {
mode: 'eventsource',
withCredentials: true
})适合以下情况:
- 不需要设置
Authorization等自定义请求头; - 使用 Cookie 或 URL 参数完成身份认证;
- 希望直接使用浏览器原生 SSE 和自动重连能力。
Fetch + ReadableStream 模式
需要自定义请求头时使用 Fetch 模式:
import SSEClient from 'wsse-sdk'
const client = new SSEClient('/events', {
mode: 'fetch',
fetchOptions: {
headers: {
Authorization: `Bearer ${token}`
},
credentials: 'include'
},
reconnect: true,
reconnectDelay: 3000,
maxRetries: Infinity
})
client.on('open', event => {
console.log('连接成功', event)
})
client.on('message', event => {
console.log(event.data)
console.log(event.lastEventId)
})
client.on('error', event => {
console.error('连接异常', event.error)
console.log('HTTP 响应', event.response)
})适合以下情况:
- 需要设置
Authorization或其他自定义请求头; - 需要获取 HTTP 状态和响应对象;
- 需要自行配置重连间隔、最大重试次数或初始
Last-Event-ID。
Fetch 模式支持解析 event:、data:、id:、retry:,并在重连时自动携带 Last-Event-ID。
自定义事件
服务端设置了 event: 字段时,使用相同名称监听:
client.on('progress', event => {
console.log(event.data)
})SDK 不自动解析 JSON,需要时由调用方处理:
client.on('message', event => {
const data = JSON.parse(event.data)
console.log(data)
})移除监听与关闭连接
const handleMessage = event => console.log(event.data)
client.on('message', handleMessage)
client.off('message', handleMessage)
client.close()off() 需要传入注册时的同一个函数。close() 会关闭当前连接并停止后续重连。
API
SSEClient Attributes
const client = new SSEClient(url, options)通用配置
| 属性名 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| url | SSE 接口地址,支持相对地址、绝对地址或 URL 对象 | string \| URL | — |
| mode | 连接模式 | 'eventsource' \| 'fetch' | 'eventsource' |
| withCredentials | 是否携带跨域凭证。EventSource 模式直接使用;Fetch 模式未配置 fetchOptions.credentials 时,true 会映射为 'include' | boolean | false |
Fetch 模式配置
以下配置仅在 mode: 'fetch' 时生效。
| 属性名 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| fetchOptions | Fetch 请求配置 | RequestInit | {} |
| reconnect | 连接失败或流结束后是否自动重连 | boolean | true |
| reconnectDelay | 默认重连间隔,单位为毫秒;服务端发送 retry: 后会更新该值 | number | 3000 |
| maxRetries | 连续连接失败的最大重试次数;连接成功后重新计数,设置为 0 表示不重试 | number \| Infinity | Infinity |
| lastEventId | 首次请求携带的事件 ID,后续会根据服务端 id: 自动更新 | string | '' |
fetchOptions
fetchOptions 支持标准 RequestInit 配置,常用属性如下:
| 属性名 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| headers | 自定义请求头,例如 Authorization | HeadersInit | { Accept: 'text/event-stream' } |
| credentials | Cookie 等凭证的携带方式 | 'omit' \| 'same-origin' \| 'include' | 'same-origin' |
| cache | Fetch 缓存模式 | RequestCache | 'no-store' |
| signal | 外部中止信号;触发后会停止当前连接和后续重连 | AbortSignal | — |
Fetch 模式固定使用 GET,不支持设置 body。fetchOptions 中的其他标准 Fetch 配置会原样传递。
Events
通过 client.on(eventName, handler) 监听事件。
| 事件名 | 说明 | 回调参数 | 支持模式 |
| --- | --- | --- | --- |
| open | SSE 连接建立成功 | Event | 全部 |
| message | 接收到未指定 event: 的默认消息 | MessageEvent<string> | 全部 |
| error | 连接、响应或流读取发生异常 | Event | 全部 |
| 服务端自定义事件名 | 接收到与服务端 event: 字段同名的消息 | MessageEvent<string> | 全部 |
MessageEvent
| 属性名 | 说明 | 类型 |
| --- | --- | --- |
| data | 服务端发送的消息字符串,SDK 不自动解析 JSON | string |
| lastEventId | 当前消息的 SSE 事件 ID | string |
| origin | 响应地址的源 | string |
| type | message 或服务端指定的自定义事件名 | string |
Fetch error event
Fetch 模式的 error 事件额外提供以下属性:
| 属性名 | 说明 | 类型 |
| --- | --- | --- |
| error | 请求失败、响应格式错误或流中断产生的错误 | Error |
| response | Fetch 响应对象;网络请求尚未获得响应时为 null | Response \| null |
EventSource 模式的 error 为浏览器原生事件,通常不能读取 HTTP 状态码或响应内容。
Methods
| 方法名 | 说明 | 参数 | 返回值 |
| --- | --- | --- | --- |
| on(type, handler) | 注册事件监听器;同一事件和函数不会重复注册 | type: stringhandler: Function | SSEClient |
| off(type, handler) | 移除事件监听器,需要传入注册时的同一个函数 | type: stringhandler: Function | SSEClient |
| close() | 关闭或中止当前连接、移除监听器并停止后续重连 | — | void |
两种模式的区别
| 特性 | EventSource 模式 | Fetch 模式 |
| --- | --- | --- |
| 配置方式 | 默认或 mode: 'eventsource' | mode: 'fetch' |
| 自定义请求头 | 不支持 | 支持 |
| Cookie | withCredentials | fetchOptions.credentials |
| SSE 解析 | 浏览器处理 | SDK 处理 |
| 自动重连 | 浏览器处理 | SDK 处理,可配置 |
| Last-Event-ID | 浏览器处理 | SDK 自动维护 |
| HTTP 状态和响应对象 | 无法可靠获取 | 可通过 error 事件获取 |
不需要自定义请求头时优先使用 EventSource 模式;需要 Token Header 或更细的请求、重连控制时使用 Fetch 模式。
