0.6.0 • Published 9 months ago

@sentool/fetch-event-source v0.6.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

English · 中文

npm size

@sentool/fetch-event-source

使用 Fetch API 请求 SSE(Server-Sent Events)端点。它是对 @microsoft/fetch-event-source 项目的重构,代码实现得更为简练,支持在 Node.js 和浏览器中使用。

安装

npm install @sentool/fetch-event-source

使用

import { fetchEventSource } from '@sentool/fetch-event-source';

await fetchEventSource('/api/sse', {
  method: 'POST',
  headers: {
    "Content-Type": "application/json",
    "Authorization": "Bearer <token>",
  },
  body: JSON.stringify({
    input: ""
  }),
  onopen(response) {
    console.log('Request has been opened.');
  },
  onmessage(event) {
    console.log(event);
  },
  onerror(error) {
    console.error(error);
  },
  done() {
    console.log('Stream has completed.');
  },
});

或在浏览器中通过 CDN 的方式引入

<script src="https://unpkg.com/@sentool/fetch-event-source/dist/index.min.js"></script>
<script type="module">
  const { fetchEventSource } = FetchEventSource;
  fetchEventSource(url, options);
</script>

你可以在任意事件中随时中止请求,如:

const eventSource = await fetchEventSource(url, options);

// 这里假设在 3 秒后中止
setTimeout(() => {
  eventSource.abort();
}, 3000);

Options

除了支持 Fetch API 自带的 RequestInit 选项外,我们还添加了以下选项:

选项类型说明
onopenfunction请求成功打开后触发
onmessagefunction接受到事件流数据时触发。
onerrorfunction出错时触发
donefunction事件流完成后触发
parseJsonboolean是否自动解析响应数据中的 JSON 字符。默认 true

License

MIT © sentool

0.6.0

9 months ago

0.5.0

11 months ago

0.4.0

11 months ago

0.3.0

11 months ago

0.2.0

11 months ago

0.1.0

11 months ago