1.0.2 • Published 1 year ago
@sparta-utils/stream-request v1.0.2
@sparta-utils/stream-request
一个支持流式响应(如 SSE、AI 多轮对话等)的轻量级请求工具库,支持自动重试、超时控制、取消请求、自动解析 JSON 行等功能。
✨ 特性
- ✅ 流式逐段处理响应体
- ✅ 支持自动 JSON 行解析
- ✅ 支持请求中断、重试与超时
- ✅ 完全自定义请求头,更通用
安装
你可以通过 npm 或 yarn 直接安装本库:
npm install @sparta-utils/stream-request
# 或
yarn add @sparta-utils/stream-request🚀 使用示例(中文注释)
import { streamRequest } from '@sparta-utils/stream-request';
streamRequest('https://your-api.com/stream', {
method: 'POST',
body: { prompt: '你好 AI' },
headers: {
Authorization: 'Bearer your-token',
'Custom-Header': '自定义内容'
},
autoParseJSON: true,
onMessage: (text) => {
console.log('收到分段数据:', text);
},
onDone: () => {
console.log('✅ 请求完成');
},
onError: (err) => {
console.error('❌ 出错:', err);
},
timeout: 10000, // 10秒超时
retry: 1 // 最多重试1次
});| 参数名 | 类型 | 说明 |
|---|---|---|
url | string | 请求地址 |
method | 'GET' \| 'POST' \| ... | 请求方法,默认 GET |
headers | Record<string, string> | 请求头(完全自定义) |
body | object \| FormData | 请求体 |
onMessage | (text: string) => void | 每段响应数据回调 |
onDone | () => void | 响应结束回调 |
onError | (error: any) => void | 错误回调 |
autoParseJSON | boolean | 自动按行解析 JSON |
decoderEncoding | string | 字符集编码,默认 utf-8 |
timeout | number(毫秒) | 请求超时中断 |
retry | number | 请求失败重试次数 |
signal | AbortSignal | 中断信号对象 |
中断请求示例
const controller = new AbortController();
streamRequest('/api/stream', {
signal: controller.signal,
onMessage: console.log
});
// 调用中断
controller.abort();| 方法 | 说明 |
|---|---|
GET | 获取资源(默认) |
POST | 创建资源或提交数据 |
PUT | 完整更新资源 |
DELETE | 删除资源 |
PATCH | 部分更新资源 |
OPTIONS | 获取通信选项 |
HEAD | 类似 GET 但无响应体 |
示例:使用 PUT / DELETE 方法
// 使用 PUT 请求
streamRequest('/api/item/123', {
method: 'PUT',
body: { name: '新名称' },
headers: {
Authorization: 'Bearer xxx'
},
onMessage: (text) => console.log('PUT响应:', text)
});
// 使用 DELETE 请求
streamRequest('/api/item/123', {
method: 'DELETE',
headers: {
Authorization: 'Bearer xxx'
},
onMessage: (text) => console.log('删除响应:', text)
});