Appearance
基于 @microsoft/fetch-event-source 的 SSE 请求工具,提供事件监听、请求发送、连接关闭和统一错误对象。
安装
bash
pnpm add @mingto/mt-sse快速开始
typescript
import SSEClient from '@mingto/mt-sse'
const client = new SSEClient('https://example.com/sse')
client.on('start', (response) => {
console.log('连接已建立', response)
})
client.on('message', (data) => {
console.log('收到消息', data)
})
client.on('end', (data) => {
console.log('服务端结束', data)
})
client.on('error', (error) => {
console.error(error.code, error.message)
})
client.on('close', () => {
console.log('连接关闭')
})
client.send({ message: 'hello' })创建客户端
typescript
const client = new SSEClient('https://example.com/sse', {
method: 'POST',
headers: {
'cache-control': 'no-cache',
'Connection': 'keep-alive',
'content-type': 'application/json',
'Language': 'zh',
},
})| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
headers | SSEHeaders | 内置 JSON SSE 请求头 | 请求头配置 |
method | 'POST' | 'GET' | 'DELETE' | 'PUT' | 'POST' | 请求方法 |
默认请求头:
typescript
const headers = {
'cache-control': 'no-cache',
'Connection': 'keep-alive',
'content-type': 'application/json',
'Language': 'zh',
}实例方法
send(data)
发起 SSE 请求,请求体会通过 JSON.stringify(data) 序列化。
typescript
client.send({ sessionId: '1', message: 'hello' })closeSSE()
通过 AbortController 关闭当前连接。
typescript
client.closeSSE()on(type, callback)
添加事件监听,返回当前实例,支持链式调用。
typescript
client.on('message', data => console.log(data))off(type, callback?)
移除指定事件监听。传入 callback 时移除对应回调,不传时移除该事件的所有回调。
typescript
const onMessage = (data: unknown) => console.log(data)
client.on('message', onMessage)
client.off('message', onMessage)
client.off('message')事件
| 事件名 | 回调参数 | 触发时机 |
|---|---|---|
start | Response | 连接建立且响应状态为 200 |
message | any | 收到普通消息 |
end | any | 收到 type 为 114 的消息 |
error | SSEError | 浏览器不支持、连接失败或执行异常 |
close | - | 连接正常关闭 |
状态码
| 状态码 | 说明 |
|---|---|
114 | 结束消息,会触发 end 事件 |
错误码
| 错误码 | 说明 |
|---|---|
4001 | 浏览器不支持 SSE |
4002 | SSE 执行错误 |
4003 | SSE 连接错误 |
4004 | 未知错误 |
4005 | 用户被停用 |