refactor(playground): extract stream ready state checks

- move SSE ready-state status handling into stream utilities.
- keep weak source status typing outside the stream request hook.
This commit is contained in:
QuentinHsu
2026-05-29 23:45:57 +08:00
parent 6b5ee783f1
commit 1f3eb1e419
2 changed files with 27 additions and 9 deletions
@@ -20,7 +20,11 @@ import { useCallback, useRef, useState } from 'react'
import { SSE } from 'sse.js'
import { getCommonHeaders } from '@/lib/api'
import { API_ENDPOINTS, ERROR_MESSAGES } from '../constants'
import { parseStreamErrorDetails, parseStreamMessageUpdates } from '../lib'
import {
getStreamReadyStateError,
parseStreamErrorDetails,
parseStreamMessageUpdates,
} from '../lib'
import type { ChatCompletionRequest } from '../types'
/**
@@ -99,14 +103,10 @@ export function useStreamRequest() {
source.addEventListener(
'readystatechange',
(e: Event & { readyState?: number }) => {
const status = (source as unknown as { status?: number }).status
if (
e.readyState !== undefined &&
e.readyState >= 2 &&
status !== undefined &&
status !== 200
) {
handleError(`HTTP ${status}: ${ERROR_MESSAGES.CONNECTION_CLOSED}`)
const errorMessage = getStreamReadyStateError(e.readyState, source)
if (errorMessage) {
handleError(errorMessage)
}
}
)
+18
View File
@@ -81,3 +81,21 @@ export function parseStreamMessageUpdates(data: string): StreamMessageUpdate[] {
return updates
}
export function getStreamReadyStateError(
eventReadyState: number | undefined,
source: unknown
): string | null {
const status = (source as { status?: number }).status
if (
eventReadyState !== undefined &&
eventReadyState >= 2 &&
status !== undefined &&
status !== 200
) {
return `HTTP ${status}: ${ERROR_MESSAGES.CONNECTION_CLOSED}`
}
return null
}