1.0.2 • Published 1 year ago

@sparta-utils/stream-request v1.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

@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次
});
参数名类型说明
urlstring请求地址
method'GET' \| 'POST' \| ...请求方法,默认 GET
headersRecord<string, string>请求头(完全自定义)
bodyobject \| FormData请求体
onMessage(text: string) => void每段响应数据回调
onDone() => void响应结束回调
onError(error: any) => void错误回调
autoParseJSONboolean自动按行解析 JSON
decoderEncodingstring字符集编码,默认 utf-8
timeoutnumber(毫秒)请求超时中断
retrynumber请求失败重试次数
signalAbortSignal中断信号对象

中断请求示例

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)
});
1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago