(config: EffectConfig<TRow, TKey>)
| 182 | * ``` |
| 183 | */ |
| 184 | export function createEffect< |
| 185 | TRow extends object = Record<string, unknown>, |
| 186 | TKey extends string | number = string | number, |
| 187 | >(config: EffectConfig<TRow, TKey>): Effect { |
| 188 | const id = config.id ?? `live-query-effect-${++effectCounter}` |
| 189 | |
| 190 | // AbortController for signalling disposal to handlers |
| 191 | const abortController = new AbortController() |
| 192 | |
| 193 | const ctx: EffectContext = { |
| 194 | effectId: id, |
| 195 | signal: abortController.signal, |
| 196 | } |
| 197 | |
| 198 | // Track in-flight async handler promises so dispose() can await them |
| 199 | const inFlightHandlers = new Set<Promise<void>>() |
| 200 | let disposed = false |
| 201 | |
| 202 | // Callback invoked by the pipeline runner with each batch of delta events |
| 203 | const onBatchProcessed = (events: Array<DeltaEvent<TRow, TKey>>) => { |
| 204 | if (disposed) return |
| 205 | if (events.length === 0) return |
| 206 | |
| 207 | // Batch handler |
| 208 | if (config.onBatch) { |
| 209 | try { |
| 210 | const result = config.onBatch(events, ctx) |
| 211 | if (result instanceof Promise) { |
| 212 | const tracked = result.catch((error) => { |
| 213 | reportError(error, events[0]!, config.onError) |
| 214 | }) |
| 215 | trackPromise(tracked, inFlightHandlers) |
| 216 | } |
| 217 | } catch (error) { |
| 218 | // For batch handler errors, report with first event as context |
| 219 | reportError(error, events[0]!, config.onError) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | for (const event of events) { |
| 224 | if (abortController.signal.aborted) break |
| 225 | |
| 226 | const handler = getHandlerForEvent(event, config) |
| 227 | if (!handler) continue |
| 228 | |
| 229 | try { |
| 230 | const result = handler(event, ctx) |
| 231 | if (result instanceof Promise) { |
| 232 | const tracked = result.catch((error) => { |
| 233 | reportError(error, event, config.onError) |
| 234 | }) |
| 235 | trackPromise(tracked, inFlightHandlers) |
| 236 | } |
| 237 | } catch (error) { |
| 238 | reportError(error, event, config.onError) |
| 239 | } |
| 240 | } |
| 241 | } |
no test coverage detected
searching dependent graphs…