Open History to see the last commit
1import { expect, it } from 'vitest'
2import { QueryClient } from '@tanstack/query-core'
3import {
4 createCollection,
5 createLiveQueryCollection,
6 createOptimisticAction,
7 createTransaction,
8} from '@tanstack/db'
9import { queryCollectionOptions } from '../src/query'
10
11type Row = { id: string; text: string }
12
13it.each([`insert`, `upsert`] as const)(
14 `keeps repeated optimistic writes valid after direct %s acknowledgement`,
15 async (method) => {
16 const queryClient = new QueryClient({
17 defaultOptions: { queries: { retry: false } },
18 })
19 const source = createCollection(
20 queryCollectionOptions({
21 queryKey: [`optimistic-writeback`, method],
22 queryClient,
23 queryFn: async (): Promise<Array<Row>> => [],
24 getKey: (row) => row.id,
25 }),
26 )
27 const live = createLiveQueryCollection({
28 query: (q) =>
29 q.from({ row: source }).select(({ row }) => ({
30 id: row.id,
31 text: row.text,
32 })),
33 })
34 const batches: Array<Array<string | number>> = []
35 const subscription = source.subscribeChanges((changes) => {
36 batches.push(changes.map((change) => change.key))
37 })
38 const insert = createOptimisticAction<Row>({
39 onMutate: (row) => source.insert(row),
40 mutationFn: async (row) => {
41 await Promise.resolve()
42 if (method === `insert`) source.utils.writeInsert({ ...row })
43 else source.utils.writeUpsert({ ...row })
44 },
45 })
46 const rename = createOptimisticAction<Row>({
47 onMutate: (row) =>
48 source.update(row.id, (draft) => {
49 draft.text = row.text
50 }),
51 mutationFn: async (row) => {
52 await Promise.resolve()
53 source.utils.writeUpdate({ ...row })
54 },
55 })
56 try {
57 await live.preload()
58 await insert({ id: `one`, text: `created` }).when(`settled`)
59 for (const text of [`renamed`, `renamed again`]) {
60 await rename({ id: `one`, text }).when(`settled`)
61 expect([...live.values()].map((row) => row.text)).toEqual([text])
62 }
63 await insert({ id: `two`, text: `second` }).when(`settled`)
64 expect([...live.values()].map((row) => row.text).sort()).toEqual([
65 `renamed again`,
66 `second`,
67 ])
68 for (const keys of batches) expect(new Set(keys).size).toBe(keys.length)
69 } finally {
70 subscription.unsubscribe()
71 await live.cleanup()
72 await source.cleanup()
73 queryClient.clear()
74 }
75 },
76)
77
78it(`keeps repeated optimistic updates valid after direct upsert acknowledgement`, async () => {
79 const queryClient = new QueryClient({
80 defaultOptions: { queries: { retry: false } },
81 })
82 let position = 0
83 const source = createCollection(
84 queryCollectionOptions({
85 queryKey: [`optimistic-upsert-rounds`],
86 queryClient,
87 queryFn: async () => [{ id: `one`, position }],
88 getKey: (row) => row.id,
89 }),
90 )
91 const live = createLiveQueryCollection((q) => q.from({ row: source }))
92 try {
93 await live.preload()
94 for (const next of [1, 2, 3]) {
95 const tx = createTransaction({
96 mutationFn: async () => {
97 position = next
98 source.utils.writeUpsert({ id: `one`, position })
99 },
100 })
101 tx.mutate(() =>
102 source.update(`one`, (draft) => {
103 draft.position += 1
104 }),
105 )
106 await tx.when(`settled`)
107 expect([...live.values()].map((row) => row.position)).toEqual([next])
108 }
109 } finally {
110 await live.cleanup()
111 await source.cleanup()
112 queryClient.clear()
113 }
114})