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:
@@ -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)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user