Open History to see the last commit
1import { describe, expectTypeOf, it } from 'vitest'
2import { createCollection } from '@tanstack/db'
3import { persistedCollectionOptions } from '../src'
4import type { PersistedCollectionUtils, PersistenceAdapter } from '../src'
5import type { SyncConfig, UtilsRecord } from '@tanstack/db'
6
7type Todo = {
8 id: string
9 title: string
10}
11
12interface LocalExtraUtils extends UtilsRecord {
13 existingUtil: () => number
14}
15
16interface SyncExtraUtils extends UtilsRecord {
17 refetch: () => Promise<void>
18}
19
20const adapter: PersistenceAdapter = {
21 loadSubset: () => Promise.resolve([]),
22 applyCommittedTx: () => Promise.resolve(),
23 ensureIndex: () => Promise.resolve(),
24}
25
26describe(`persisted collection types`, () => {
27 it(`adds persisted utils in sync-absent mode`, () => {
28 const options = persistedCollectionOptions<
29 Todo,
30 string,
31 never,
32 LocalExtraUtils
33 >({
34 id: `persisted-local-only`,
35 schemaVersion: 1,
36 getKey: (item) => item.id,
37 utils: {
38 existingUtil: () => 42,
39 },
40 persistence: {
41 adapter,
42 },
43 })
44
45 expectTypeOf(options.utils.existingUtil).toBeFunction()
46 expectTypeOf(options.utils.existingUtil).returns.toEqualTypeOf<number>()
47 expectTypeOf(options.utils.acceptMutations).toBeFunction()
48 expectTypeOf(options.utils.getLeadershipState).toEqualTypeOf<
49 (() => { nodeId: string; isLeader: boolean }) | undefined
50 >()
51
52 const collection = createCollection(options)
53 expectTypeOf(collection.utils.acceptMutations).toBeFunction()
54 expectTypeOf(collection.utils).toMatchTypeOf<PersistedCollectionUtils>()
55 })
56
57 it(`preserves sync-present utility typing`, () => {
58 const sync: SyncConfig<Todo, string> = {
59 sync: ({ markReady }) => {
60 markReady()
61 },
62 }
63
64 const options = persistedCollectionOptions<
65 Todo,
66 string,
67 never,
68 SyncExtraUtils
69 >({
70 id: `persisted-sync-present`,
71 schemaVersion: 2,
72 getKey: (item) => item.id,
73 sync,
74 utils: {
75 refetch: async () => {},
76 },
77 persistence: {
78 adapter,
79 },
80 })
81
82 expectTypeOf(options.sync).toEqualTypeOf<SyncConfig<Todo, string>>()
83 expectTypeOf(options.utils).toEqualTypeOf<SyncExtraUtils | undefined>()
84
85 const collection = createCollection(options)
86 expectTypeOf(collection.utils.refetch).toBeFunction()
87 })
88
89 it(`requires persistence config`, () => {
90 // @ts-expect-error persistedCollectionOptions requires a persistence config
91 persistedCollectionOptions({
92 getKey: (item: Todo) => item.id,
93 sync: {
94 sync: ({ markReady }: { markReady: () => void }) => {
95 markReady()
96 },
97 },
98 })
99 })
100
101 it(`requires a valid sync config when sync key is present`, () => {
102 persistedCollectionOptions({
103 getKey: (item: Todo) => item.id,
104 // @ts-expect-error sync must be a valid SyncConfig object when provided
105 sync: null,
106 persistence: {
107 adapter,
108 },
109 })
110 })
111})