改造实时事件缓存同步
This commit is contained in:
@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react'
|
||||
|
||||
export type RealtimeEvent = {
|
||||
eventId: number
|
||||
version: number
|
||||
type:
|
||||
| 'admin_notification.changed'
|
||||
| 'order.changed'
|
||||
@@ -10,6 +11,8 @@ export type RealtimeEvent = {
|
||||
| 'worker_wallet.changed'
|
||||
entityId: number
|
||||
scopes: string[]
|
||||
operation: 'upsert' | 'remove' | 'refresh'
|
||||
data?: unknown
|
||||
occurredAt: string
|
||||
}
|
||||
|
||||
@@ -35,18 +38,21 @@ export function useRealtimeEvents({ url, token, onEvent, onConnected }: UseRealt
|
||||
let stopped = false
|
||||
let abortController: AbortController | null = null
|
||||
let reconnectTimer = 0
|
||||
let lastEventId = 0
|
||||
|
||||
const connect = () => {
|
||||
if (stopped || document.visibilityState !== 'visible') return
|
||||
abortController?.abort()
|
||||
abortController = new AbortController()
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
Accept: 'text/event-stream',
|
||||
Authorization: `Bearer ${token}`,
|
||||
}
|
||||
if (lastEventId > 0) headers['Last-Event-ID'] = String(lastEventId)
|
||||
void fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'text/event-stream',
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
signal: abortController.signal,
|
||||
})
|
||||
@@ -58,7 +64,11 @@ export function useRealtimeEvents({ url, token, onEvent, onConnected }: UseRealt
|
||||
await readSseStream(response.body, (eventName, data) => {
|
||||
if (eventName !== 'realtime') return
|
||||
const event = normalizeRealtimeEvent(data)
|
||||
if (event) onEventRef.current(event)
|
||||
if (event) {
|
||||
if (event.eventId <= lastEventId) return
|
||||
lastEventId = Math.max(lastEventId, event.eventId)
|
||||
onEventRef.current(event)
|
||||
}
|
||||
})
|
||||
})
|
||||
.catch(() => undefined)
|
||||
@@ -153,11 +163,17 @@ function normalizeRealtimeEvent(value: string): RealtimeEvent | null {
|
||||
}
|
||||
return {
|
||||
eventId: Number(parsed.eventId || 0),
|
||||
version: Number(parsed.version || parsed.eventId || 0),
|
||||
type: type as RealtimeEvent['type'],
|
||||
entityId: Number(parsed.entityId || 0),
|
||||
scopes: Array.isArray(parsed.scopes)
|
||||
? parsed.scopes.map((item) => String(item || '')).filter(Boolean)
|
||||
: [],
|
||||
operation:
|
||||
parsed.operation === 'upsert' || parsed.operation === 'remove'
|
||||
? parsed.operation
|
||||
: 'refresh',
|
||||
data: parsed.data,
|
||||
occurredAt: String(parsed.occurredAt || ''),
|
||||
}
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user