优化(直播履约): 改为订单快照事件驱动
This commit is contained in:
@@ -5,6 +5,8 @@ export type RealtimeEvent = {
|
||||
version: number
|
||||
type:
|
||||
| 'admin_notification.changed'
|
||||
| 'customer_order.changed'
|
||||
| 'fulfillment_pipeline.changed'
|
||||
| 'order.changed'
|
||||
| 'work_order.changed'
|
||||
| 'worker_finance_request.changed'
|
||||
@@ -18,7 +20,8 @@ export type RealtimeEvent = {
|
||||
|
||||
type UseRealtimeEventsOptions = {
|
||||
url: string
|
||||
token: string
|
||||
token?: string
|
||||
allowAnonymous?: boolean
|
||||
onEvent: (event: RealtimeEvent) => void
|
||||
onConnected?: () => void
|
||||
/**
|
||||
@@ -38,6 +41,7 @@ const RECONNECT_DELAY_MS = 3_000
|
||||
export function useRealtimeEvents({
|
||||
url,
|
||||
token,
|
||||
allowAnonymous,
|
||||
onEvent,
|
||||
onConnected,
|
||||
onResync,
|
||||
@@ -53,7 +57,7 @@ export function useRealtimeEvents({
|
||||
onAuthExpiredRef.current = onAuthExpired
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
if (!token && !allowAnonymous) return
|
||||
|
||||
let stopped = false
|
||||
let abortController: AbortController | null = null
|
||||
@@ -67,8 +71,8 @@ export function useRealtimeEvents({
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'text/event-stream',
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
if (lastEventId > 0) headers['Last-Event-ID'] = String(lastEventId)
|
||||
let authExpired = false
|
||||
void fetch(url, {
|
||||
@@ -101,8 +105,8 @@ export function useRealtimeEvents({
|
||||
if (eventName !== 'realtime') return
|
||||
const event = normalizeRealtimeEvent(data)
|
||||
if (event) {
|
||||
if (event.eventId <= lastEventId) return
|
||||
lastEventId = Math.max(lastEventId, event.eventId)
|
||||
if (event.eventId > 0 && event.eventId <= lastEventId) return
|
||||
if (event.eventId > 0) lastEventId = Math.max(lastEventId, event.eventId)
|
||||
onEventRef.current(event)
|
||||
}
|
||||
})
|
||||
@@ -131,7 +135,7 @@ export function useRealtimeEvents({
|
||||
abortController?.abort()
|
||||
window.clearTimeout(reconnectTimer)
|
||||
}
|
||||
}, [token, url])
|
||||
}, [allowAnonymous, token, url])
|
||||
}
|
||||
|
||||
async function readSseStream(
|
||||
@@ -189,6 +193,8 @@ function normalizeRealtimeEvent(value: string): RealtimeEvent | null {
|
||||
if (
|
||||
![
|
||||
'admin_notification.changed',
|
||||
'customer_order.changed',
|
||||
'fulfillment_pipeline.changed',
|
||||
'order.changed',
|
||||
'work_order.changed',
|
||||
'worker_finance_request.changed',
|
||||
|
||||
Reference in New Issue
Block a user