Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,106 @@ const data2 = await cachedApi.get('/users', {}, { cache: { ttl: 5000 } }) // cac
const otherApi = new Request('/api') // isolated cache
```

## SSE (Server-Sent Events)

Supports SSE streaming requests, built on Fetch API with these advantages over native EventSource:
- ✅ Custom Headers support
- ✅ POST requests support
- ✅ All HTTP methods supported

### Basic usage

```ts
import { Request } from '@cc-heart/utils'

const api = new Request('https://api.example.com')

// GET SSE
const handle = api.sse('/events', {
onMessage(event) {
console.log('Received:', event.data)
},
onOpen() {
console.log('Connection opened')
},
onError(error) {
console.error('Connection error:', error)
},
onClose() {
console.log('Connection closed')
}
})

// Cancel connection
handle.abort()
```

### POST SSE (e.g., AI streaming chat)

```ts
const handle = api.sse('/chat/completions', {
method: 'POST',
data: {
prompt: 'Hello',
model: 'gpt-4'
},
onMessage(event) {
// Parse JSON data
try {
const data = JSON.parse(event.data)
console.log('AI reply:', data.content)
} catch {
console.log('Raw data:', event.data)
}
},
onError(err) {
console.error('Request failed:', err)
}
})
```

### With interceptors

```ts
import type { RequestInterceptor } from '@cc-heart/utils'

const addAuth: RequestInterceptor = (config) => ({
...config,
headers: {
...config.headers,
Authorization: `Bearer ${getToken()}`
}
})

const api = new Request('https://api.example.com')
api.useRequestInterceptor(addAuth)

// SSE requests automatically include interceptor headers
const handle = api.sse('/protected/events', {
onMessage(event) {
console.log(event.data)
}
})
```

### SSE Type definitions

```ts
interface SSEMessageEvent {
event?: string // Event type
data: string // Message data
id?: string // Last event ID
retry?: number // Retry interval (ms)
}

interface SSECallbacks {
onMessage?: (event: SSEMessageEvent) => void
onOpen?: () => void
onError?: (error: unknown) => void
onClose?: () => void
}
```

## LICENSE

`@cc-heart/utils` is licensed under the [MIT License](./LICENSE).
100 changes: 100 additions & 0 deletions README_ZH.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,106 @@ interface RequestConfig {
}
```

## SSE (Server-Sent Events)

支持 SSE 流式请求,基于 Fetch API 实现,相比原生 EventSource 有以下优势:
- ✅ 支持自定义 Headers
- ✅ 支持 POST 请求
- ✅ 支持所有 HTTP 方法

### 基础用法

```ts
import { Request } from '@cc-heart/utils'

const api = new Request('https://api.example.com')

// GET SSE
const handle = api.sse('/events', {
onMessage(event) {
console.log('收到消息:', event.data)
},
onOpen() {
console.log('连接已建立')
},
onError(error) {
console.error('连接错误:', error)
},
onClose() {
console.log('连接已关闭')
}
})

// 取消连接
handle.abort()
```

### POST SSE (如 AI 流式对话)

```ts
const handle = api.sse('/chat/completions', {
method: 'POST',
data: {
prompt: '你好',
model: 'gpt-4'
},
onMessage(event) {
// 解析 JSON 数据
try {
const data = JSON.parse(event.data)
console.log('AI 回复:', data.content)
} catch {
console.log('原始数据:', event.data)
}
},
onError(err) {
console.error('请求失败:', err)
}
})
```

### 搭配拦截器使用

```ts
import type { RequestInterceptor } from '@cc-heart/utils'

const addAuth: RequestInterceptor = (config) => ({
...config,
headers: {
...config.headers,
Authorization: `Bearer ${getToken()}`
}
})

const api = new Request('https://api.example.com')
api.useRequestInterceptor(addAuth)

// SSE 请求会自动携带拦截器添加的 Headers
const handle = api.sse('/protected/events', {
onMessage(event) {
console.log(event.data)
}
})
```

### SSE 类型定义

```ts
interface SSEMessageEvent {
event?: string // 事件类型
data: string // 消息数据
id?: string // 最后事件 ID
retry?: number // 重连间隔(毫秒)
}

interface SSECallbacks {
onMessage?: (event: SSEMessageEvent) => void
onOpen?: () => void
onError?: (error: unknown) => void
onClose?: () => void
}
```

## 返回类型

```ts
Expand Down
Loading
Loading