(
persistFn: (key: TKey, data: TData) => Promise<void>,
options: QueueOptions<TData> = {}
)
| 63 | } |
| 64 | |
| 65 | export function createPersistenceQueue<TKey extends string, TData>( |
| 66 | persistFn: (key: TKey, data: TData) => Promise<void>, |
| 67 | options: QueueOptions<TData> = {} |
| 68 | ): PersistenceQueue<TKey, TData> { |
| 69 | const { |
| 70 | debounceMs = 300, |
| 71 | maxDelayMs = 2000, |
| 72 | maxRetries = 3, |
| 73 | initialRetryDelay = 1000, |
| 74 | mergePending |
| 75 | } = options |
| 76 | |
| 77 | const pending = new Map<TKey, WriteTask<TData>>() |
| 78 | const timers = new Map<TKey, ReturnType<typeof setTimeout>>() |
| 79 | const firstQueueTime = new Map<TKey, number>() |
| 80 | const writing = new Map<TKey, Promise<void>>() |
| 81 | |
| 82 | function enqueue(key: TKey, data: TData): void { |
| 83 | const now = Date.now() |
| 84 | const current = pending.get(key) |
| 85 | const mergedData = current && mergePending ? mergePending(current.data, data) : data |
| 86 | pending.set(key, { data: mergedData, timestamp: current?.timestamp ?? now }) |
| 87 | |
| 88 | if (!firstQueueTime.has(key)) { |
| 89 | firstQueueTime.set(key, now) |
| 90 | } |
| 91 | |
| 92 | const existingTimer = timers.get(key) |
| 93 | if (existingTimer) { |
| 94 | clearTimeout(existingTimer) |
| 95 | } |
| 96 | |
| 97 | const firstTime = firstQueueTime.get(key) ?? now |
| 98 | const elapsed = now - firstTime |
| 99 | |
| 100 | if (elapsed >= maxDelayMs) { |
| 101 | void flush(key) |
| 102 | } else { |
| 103 | const delay = Math.min(debounceMs, maxDelayMs - elapsed) |
| 104 | const timer = setTimeout(() => { |
| 105 | void flush(key) |
| 106 | }, delay) |
| 107 | timers.set(key, timer) |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | async function flush(key: TKey): Promise<void> { |
| 112 | const timer = timers.get(key) |
| 113 | if (timer) { |
| 114 | clearTimeout(timer) |
| 115 | timers.delete(key) |
| 116 | } |
| 117 | |
| 118 | const inflight = writing.get(key) |
| 119 | if (inflight) { |
| 120 | await inflight |
| 121 | } |
| 122 |
no outgoing calls
no test coverage detected