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

notification-laws-oracle.ts

59 lines2.0 KB

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