Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

notification-laws-oracle.ts

54 lines1.8 KB

1import { expect } from 'vitest'
2​
3export type Notification<Row> = {
4 events: Array<{
5 type: string
6 key: string | number
7 value: Row
8 previousValue?: Row
9 }>
10 rows: Array<Row>
12​
13/** Deltas from a subscription with an initial snapshot must reconstruct every
14 * callback's rows. Callers including the initial-state callback start from [].
15 */
16export function expectNotificationHistory<Row extends { id: string }>(
17 initial: ReadonlyArray<Row>,
18 callbacks: ReadonlyArray<Notification<Row>>,
19 final: ReadonlyArray<Row>,
20): void {
21 const byId = (a: Row, b: Row) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
22 const state = new Map(initial.map((row) => [row.id, row]))
23 expect(state.size).toBe(initial.length)
24 for (const callback of callbacks) {
25 for (const event of callback.events) {
26 expect(event.key).toBe(event.value.id)
27 if (event.type === 'insert') {
28 expect(state.has(event.value.id)).toBe(false)
29 state.set(event.value.id, event.value)
30 } else if (event.type === 'update') {
31 expect(state.has(event.value.id)).toBe(true)
32 expect(event.previousValue).toStrictEqual(state.get(event.value.id))
33 state.set(event.value.id, event.value)
34 } else if (event.type === 'delete') {
35 expect(state.has(event.value.id)).toBe(true)
36 expect(event.value).toStrictEqual(state.get(event.value.id))
37 state.delete(event.value.id)
38 } else {
39 throw new Error(`Unknown change type: ${event.type}`)
40 }
41 }
42 expect([...state.values()].sort(byId)).toStrictEqual(
43 [...callback.rows].sort(byId),
44 )
45 }
46 expect([...state.values()].sort(byId)).toStrictEqual([...final].sort(byId))
48​
49export function expectNotificationsStopped<Row>(
50 callbacks: ReadonlyArray<Notification<Row>>,
51 archived: ReadonlyArray<Notification<Row>>,
52): void {
53 expect(callbacks).toStrictEqual(archived)