forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection.test.ts
More file actions
1579 lines (1365 loc) · 48.8 KB
/
collection.test.ts
File metadata and controls
1579 lines (1365 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { type } from "arktype"
import mitt from "mitt"
import { describe, expect, expectTypeOf, it, vi } from "vitest"
import { z } from "zod"
import { createCollection } from "../src/collection"
import {
CollectionRequiresConfigError,
DuplicateKeyError,
KeyUpdateNotAllowedError,
MissingDeleteHandlerError,
MissingInsertHandlerError,
MissingUpdateHandlerError,
SchemaValidationError,
} from "../src/errors"
import { createTransaction } from "../src/transactions"
import {
flushPromises,
mockSyncCollectionOptionsNoInitialState,
withExpectedRejection,
} from "./utils"
import type {
ChangeMessage,
MutationFn,
OperationType,
PendingMutation,
ResolveTransactionChanges,
} from "../src/types"
describe(`Collection`, () => {
it(`should throw if there's no sync config`, () => {
// @ts-expect-error we're testing for throwing when there's no config passed in
expect(() => createCollection()).toThrow(CollectionRequiresConfigError)
})
it(`should throw an error when trying to use mutation operations outside of a transaction`, async () => {
// Create a collection with sync but no mutationFn
const collection = createCollection<{ value: string }>({
id: `foo`,
getKey: (item) => item.value,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
// Immediately execute the sync cycle
begin()
write({
type: `insert`,
value: { value: `initial value` },
})
commit()
},
},
})
// Wait for the collection to be ready
await collection.stateWhenReady()
// Verify initial state
expect(Array.from(collection.state.values())).toEqual([
{ value: `initial value` },
])
// Verify that insert throws an error
expect(() => {
collection.insert({ value: `new value` })
}).toThrow(MissingInsertHandlerError)
// Verify that update throws an error
expect(() => {
collection.update(`initial`, (draft) => {
draft.value = `updated value`
})
}).toThrow(MissingUpdateHandlerError)
// Verify that delete throws an error
expect(() => {
collection.delete(`initial`)
}).toThrow(MissingDeleteHandlerError)
})
it(`should throw an error when trying to update an item's ID`, async () => {
const collection = createCollection<{ id: string; value: string }>({
id: `id-update-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
begin()
write({
type: `insert`,
value: { id: `item-1`, value: `initial value` },
})
commit()
},
},
})
await collection.stateWhenReady()
const tx = createTransaction({
mutationFn: async () => {
// No-op mutationFn for this test, as we expect a client-side error
},
})
expect(() => {
tx.mutate(() => {
collection.update(`item-1`, (draft) => {
draft.id = `item-2` // Attempt to change the ID
draft.value = `updated value`
})
})
}).toThrow(KeyUpdateNotAllowedError)
})
it(`It shouldn't expose any state until the initial sync is finished`, () => {
// Create a collection with a mock sync plugin
createCollection<{ name: string }>({
id: `foo`,
getKey: (item) => item.name,
startSync: true,
sync: {
sync: ({ collection, begin, write, commit }) => {
// Initial state should be empty
expect(collection.state).toEqual(new Map())
// Start a batch of operations
begin()
// Write some test data
const operations: Array<
Omit<ChangeMessage<{ name: string }>, `key`>
> = [
{ value: { name: `Alice` }, type: `insert` },
{ value: { name: `Bob` }, type: `insert` },
]
for (const op of operations) {
write(op)
// Data should still be empty during writes
expect(collection.state).toEqual(new Map())
}
// Commit the changes
commit()
// Now the data should be visible
const expectedData = [{ name: `Alice` }, { name: `Bob` }]
expect(Array.from(collection.state.values())).toEqual(expectedData)
},
},
})
})
it(`Calling mutation operators should trigger creating & persisting a new transaction`, async () => {
const emitter = mitt()
// Create mock functions that will capture the data for later assertions
const persistMock = vi.fn()
const syncMock = vi.fn()
// new collection w/ mock sync/mutation
const collection = createCollection<{
id: number
value: string
boolean?: boolean
newProp?: string
}>({
id: `mock`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
// @ts-expect-error don't trust mitt's typing
emitter.on(`*`, (_, changes: Array<PendingMutation>) => {
begin()
changes.forEach((change) => {
write({
type: change.type,
// @ts-expect-error TODO type changes
value: change.modified,
})
})
commit()
})
},
},
})
const mutationFn: MutationFn = ({ transaction }) => {
// Redact time-based and random fields
const redactedTransaction = {
...transaction,
mutations: {
...transaction.mutations.map((mutation) => {
return {
...mutation,
createdAt: `[REDACTED]`,
updatedAt: `[REDACTED]`,
mutationId: `[REDACTED]`,
}
}),
},
}
// Call the mock function with the redacted transaction
persistMock({ transaction: redactedTransaction })
// Call the mock function with the transaction
syncMock({ transaction })
emitter.emit(`sync`, transaction.mutations)
return Promise.resolve()
}
// Test insert with auto-generated key
const data = { id: 1, value: `bar` }
// TODO create transaction manually with the above mutationFn & get assertions passing.
const tx = createTransaction({ mutationFn })
tx.mutate(() => collection.insert(data))
// @ts-expect-error possibly undefined is ok in test
const insertedKey = tx.mutations[0].key as string
// The merged value should immediately contain the new insert
expect(collection.state).toEqual(
new Map([[insertedKey, { id: 1, value: `bar` }]])
)
// check there's a transaction in peristing state
expect(
// @ts-expect-error possibly undefined is ok in test
tx.mutations[0].changes
).toEqual({
id: 1,
value: `bar`,
})
// Check the optimistic operation is there
const insertKey = 1
expect(collection.optimisticUpserts.has(insertKey)).toBe(true)
expect(collection.optimisticUpserts.get(insertKey)).toEqual({
id: 1,
value: `bar`,
})
// Check persist data (moved outside the persist callback)
// @ts-expect-error possibly undefined is ok in test
const persistData = persistMock.mock.calls[0][0]
// Check that the transaction is in the right state during persist
expect(persistData.transaction.state).toBe(`persisting`)
// Check mutation type is correct
expect(persistData.transaction.mutations[0].type).toBe(`insert`)
// Check changes are correct
expect(persistData.transaction.mutations[0].changes).toEqual({
id: 1,
value: `bar`,
})
await tx.isPersisted.promise
// @ts-expect-error possibly undefined is ok in test
const syncData = syncMock.mock.calls[0][0]
// Check that the transaction is in the right state during sync waiting
expect(syncData.transaction.state).toBe(`completed`)
// Check mutation type is correct
expect(syncData.transaction.mutations[0].type).toBe(`insert`)
// Check changes are correct
expect(syncData.transaction.mutations[0].changes).toEqual({
id: 1,
value: `bar`,
})
// after mutationFn returns, check that the transaction is cleaned up,
// optimistic update is gone & synced data & combined state are all updated.
expect(collection.transactions.size).toEqual(0) // Transaction should be cleaned up
expect(collection.state).toEqual(
new Map([[insertedKey, { id: 1, value: `bar` }]])
)
expect(collection.optimisticUpserts.size).toEqual(0)
// Test insert with provided key
const tx2 = createTransaction({ mutationFn })
tx2.mutate(() => collection.insert({ id: 2, value: `baz` }))
expect(collection.state.get(2)).toEqual({
id: 2,
value: `baz`,
})
await tx2.isPersisted.promise
// Test bulk insert
const tx3 = createTransaction({ mutationFn })
const bulkData = [
{ id: 3, value: `item1` },
{ id: 4, value: `item2` },
]
tx3.mutate(() => collection.insert(bulkData))
const keys = Array.from(collection.state.keys())
// @ts-expect-error possibly undefined is ok in test
expect(collection.state.get(keys[2])).toEqual(bulkData[0])
// @ts-expect-error possibly undefined is ok in test
expect(collection.state.get(keys[3])).toEqual(bulkData[1])
await tx3.isPersisted.promise
const tx4 = createTransaction({ mutationFn })
// Test update with callback
tx4.mutate(() =>
collection.update([1], (item) => {
// @ts-expect-error possibly undefined is ok in test
item[0].value = `bar2`
})
)
// The merged value should contain the update.
expect(collection.state.get(insertedKey)).toEqual({ id: 1, value: `bar2` })
await tx4.isPersisted.promise
const tx5 = createTransaction({ mutationFn })
// Test update with config and callback
tx5.mutate(() =>
collection.update(
insertedKey,
{ metadata: { updated: true } },
(item) => {
item.value = `bar3`
item.newProp = `new value`
}
)
)
// The merged value should contain the update
expect(collection.state.get(insertedKey)).toEqual({
id: 1,
value: `bar3`,
newProp: `new value`,
})
await tx5.isPersisted.promise
// If there are two updates, the second should overwrite the first.
const tx55 = createTransaction({ mutationFn })
// Test update with config and callback
tx55.mutate(() => {
collection.update(
insertedKey,
{ metadata: { updated: true } },
(item) => {
item.value = `bar3.1`
item.newProp = `new value.1`
}
)
collection.update(
insertedKey,
{ metadata: { updated: true } },
(item) => {
item.value = `bar3`
item.newProp = `new value`
}
)
})
// The merged value should contain the update
expect(collection.state.get(insertedKey)).toEqual({
id: 1,
value: `bar3`,
newProp: `new value`,
})
expect(tx55.mutations).toHaveLength(1)
await tx55.isPersisted.promise
const tx6 = createTransaction({ mutationFn })
// Test bulk update
tx6.mutate(() =>
collection.update(
[keys[2], keys[3]],
{ metadata: { bulkUpdate: true } },
(drafts) => {
drafts.forEach((draft) => {
draft.value += `-updated`
draft.boolean = true
})
}
)
)
// Check bulk updates
// @ts-expect-error possibly undefined is ok in test
expect(collection.state.get(keys[2])).toEqual({
boolean: true,
id: 3,
value: `item1-updated`,
})
// @ts-expect-error possibly undefined is ok in test
expect(collection.state.get(keys[3])).toEqual({
boolean: true,
id: 4,
value: `item2-updated`,
})
await tx6.isPersisted.promise
const tx7 = createTransaction({ mutationFn })
// Test delete single item
tx7.mutate(() => collection.delete(insertedKey))
expect(collection.state.has(insertedKey)).toBe(false)
// objectKeyMap check removed as it no longer exists
await tx7.isPersisted.promise
// Test delete with metadata
const tx8Insert = createTransaction({ mutationFn })
tx8Insert.mutate(() => collection.insert({ id: 5, value: `foostyle` }))
// @ts-expect-error possibly undefined is ok in test
const tx8insertKey = tx8Insert.mutations[0].key
await tx8Insert.isPersisted.promise
const tx8 = createTransaction({ mutationFn })
tx8.mutate(() =>
collection.delete(tx8insertKey, {
metadata: { reason: `test delete` },
})
)
expect(tx8.mutations[0]?.metadata).toEqual({ reason: `test delete` })
expect(collection.state.has(tx8insertKey)).toBe(false)
await tx8.isPersisted.promise
// Test bulk delete
const tx9 = createTransaction({ mutationFn })
tx9.mutate(() => collection.delete([keys[2]!, keys[3]!]))
// @ts-expect-error possibly undefined is ok in test
expect(collection.state.has(keys[2])).toBe(false)
// @ts-expect-error possibly undefined is ok in test
expect(collection.state.has(keys[3])).toBe(false)
await tx9.isPersisted.promise
})
it(`synced updates should *not* be applied while there's a persisting transaction`, async () => {
const emitter = mitt()
// new collection w/ mock sync/mutation
const collection = createCollection<{ id: number; value: string }>({
id: `mock`,
getKey: (item) => {
return item.id
},
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
// @ts-expect-error don't trust Mitt's typing and this works.
emitter.on(`*`, (_, changes: Array<PendingMutation>) => {
begin()
changes.forEach((change) => {
write({
type: change.type,
// @ts-expect-error TODO type changes
value: change.changes,
})
})
commit()
})
},
},
})
const mutationFn: MutationFn = ({ transaction }) => {
// Sync something and check that that it isn't applied because
// we're still in the middle of persisting a transaction.
emitter.emit(`update`, [
// This update is ignored because the optimistic update overrides it.
{ type: `insert`, changes: { id: 2, bar: `value2` } },
])
expect(collection.state).toEqual(new Map([[1, { id: 1, value: `bar` }]]))
// Remove it so we don't have to assert against it below
emitter.emit(`update`, [{ changes: { id: 2 }, type: `delete` }])
emitter.emit(`update`, transaction.mutations)
return Promise.resolve()
}
const tx1 = createTransaction({ mutationFn })
// insert
tx1.mutate(() =>
collection.insert({
id: 1,
value: `bar`,
})
)
// The merged value should immediately contain the new insert
expect(collection.state).toEqual(new Map([[1, { id: 1, value: `bar` }]]))
// check there's a transaction in peristing state
expect(
// @ts-expect-error possibly undefined is ok in test
Array.from(collection.transactions.values())[0].mutations[0].changes
).toEqual({
id: 1,
value: `bar`,
})
// Check the optimistic operation is there
const insertKey = 1
expect(collection.optimisticUpserts.has(insertKey)).toBe(true)
expect(collection.optimisticUpserts.get(insertKey)).toEqual({
id: 1,
value: `bar`,
})
await tx1.isPersisted.promise
expect(collection.state).toEqual(new Map([[1, { id: 1, value: `bar` }]]))
})
it(`should throw errors when deleting items not in the collection`, () => {
const collection = createCollection<{ name: string }>({
id: `delete-errors`,
getKey: (val) => val.name,
startSync: true,
sync: {
sync: ({ begin, commit }) => {
begin()
commit()
},
},
})
const mutationFn = () => Promise.resolve()
// Add an item to the collection
const item = { name: `Test Item` }
const tx1 = createTransaction({ mutationFn })
tx1.mutate(() => collection.insert(item))
// Throw when trying to delete a non-existent ID
const tx2 = createTransaction({ mutationFn })
expect(() =>
tx2.mutate(() => collection.delete(`non-existent-id`))
).toThrow()
// Should not throw when deleting by ID
const tx5 = createTransaction({ mutationFn })
// Get the ID from the first item that was inserted
const itemId = Array.from(collection.state.keys())[0]
expect(() => tx5.mutate(() => collection.delete(itemId!))).not.toThrow()
})
it(`should not allow inserting documents with IDs that already exist`, async () => {
const collection = createCollection<{ id: number; value: string }>({
id: `duplicate-id-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
begin()
write({
type: `insert`,
value: { id: 1, value: `initial value` },
})
commit()
},
},
})
await collection.stateWhenReady()
const mutationFn = async () => {}
const tx = createTransaction({ mutationFn })
// Try to insert a document with the same ID
expect(() => {
tx.mutate(() => collection.insert({ id: 1, value: `duplicate value` }))
}).toThrow(DuplicateKeyError)
// Should be able to insert a document with a different ID
const tx2 = createTransaction({ mutationFn })
expect(() => {
tx2.mutate(() => collection.insert({ id: 2, value: `new value` }))
}).not.toThrow()
})
it(`should support operation handler functions`, async () => {
// Create mock handler functions
const onInsertMock = vi.fn()
const onUpdateMock = vi.fn()
const onDeleteMock = vi.fn()
// Create a collection with handler functions
const collection = createCollection<{ id: number; value: string }>({
id: `handlers-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
begin()
write({
type: `insert`,
value: { id: 1, value: `initial value` },
})
commit()
},
},
// Add the new handler functions
onInsert: onInsertMock,
onUpdate: onUpdateMock,
onDelete: onDeleteMock,
})
await collection.stateWhenReady()
// Create a transaction to test the handlers
const mutationFn = async () => {}
const tx = createTransaction({ mutationFn, autoCommit: false })
// Test insert handler
tx.mutate(() => collection.insert({ id: 2, value: `new value` }))
// Test update handler
tx.mutate(() =>
collection.update(1, (draft) => {
draft.value = `updated value`
})
)
// Test delete handler
tx.mutate(() => collection.delete(1))
// Verify the handler functions were defined correctly
// We're not testing actual invocation since that would require modifying the Collection class
expect(typeof collection.config.onInsert).toBe(`function`)
expect(typeof collection.config.onUpdate).toBe(`function`)
expect(typeof collection.config.onDelete).toBe(`function`)
})
it(`should execute operations outside of explicit transactions using handlers`, async () => {
// Create handler functions that resolve after a short delay to simulate async operations
const onInsertMock = vi.fn().mockImplementation(async () => {
// Wait a bit to simulate an async operation
await new Promise((resolve) => setTimeout(resolve, 10))
return { success: true, operation: `insert` }
})
const onUpdateMock = vi.fn().mockImplementation(async () => {
await new Promise((resolve) => setTimeout(resolve, 10))
return { success: true, operation: `update` }
})
const onDeleteMock = vi.fn().mockImplementation(async () => {
await new Promise((resolve) => setTimeout(resolve, 10))
return { success: true, operation: `delete` }
})
// Create a collection with handler functions
const collection = createCollection<{ id: number; value: string }>({
id: `direct-operations-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
begin()
write({
type: `insert`,
value: { id: 1, value: `initial value` },
})
commit()
},
},
// Add the handler functions
onInsert: onInsertMock,
onUpdate: onUpdateMock,
onDelete: onDeleteMock,
})
await collection.stateWhenReady()
// Test direct insert operation
const insertTx = collection.insert({ id: 2, value: `inserted directly` })
expect(insertTx).toBeDefined()
expect(onInsertMock).toHaveBeenCalledTimes(1)
// Test direct update operation
const updateTx = collection.update(1, (draft) => {
draft.value = `updated directly`
})
expect(updateTx).toBeDefined()
expect(onUpdateMock).toHaveBeenCalledTimes(1)
// Test direct delete operation
const deleteTx = collection.delete(1)
expect(deleteTx).toBeDefined()
expect(onDeleteMock).toHaveBeenCalledTimes(1)
// Wait for all transactions to complete
await Promise.all([
insertTx.isPersisted.promise,
updateTx.isPersisted.promise,
deleteTx.isPersisted.promise,
])
// Verify the transactions were created with the correct configuration
expect(insertTx.autoCommit).toBe(true)
expect(updateTx.autoCommit).toBe(true)
expect(deleteTx.autoCommit).toBe(true)
})
it(`should throw errors when operations are called outside transactions without handlers`, async () => {
// Create a collection without handler functions
const collection = createCollection<{ id: number; value: string }>({
id: `no-handlers-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
begin()
write({
type: `insert`,
value: { id: 1, value: `initial value` },
})
commit()
},
},
// No handler functions defined
})
await collection.stateWhenReady()
// Test insert without handler
expect(() => {
collection.insert({ id: 2, value: `should fail` })
}).toThrow(MissingInsertHandlerError)
// Test update without handler
expect(() => {
collection.update(1, (draft) => {
draft.value = `should fail`
})
}).toThrow(MissingUpdateHandlerError)
// Test delete without handler
expect(() => {
collection.delete(`1`) // Convert number to string to match expected type
}).toThrow(MissingDeleteHandlerError)
})
it(`should not apply optimistic updates when optimistic: false`, async () => {
const emitter = mitt()
const pendingMutations: Array<() => void> = []
const mutationFn = vi.fn().mockImplementation(async ({ transaction }) => {
// Don't sync immediately - return a promise that can be resolved later
return new Promise<void>((resolve) => {
pendingMutations.push(() => {
emitter.emit(`sync`, transaction.mutations)
resolve()
})
})
})
const collection = createCollection<{ id: number; value: string }>({
id: `non-optimistic-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
// Initialize with some data
begin()
write({
type: `insert`,
value: { id: 1, value: `initial value` },
})
commit()
// @ts-expect-error don't trust mitt's typing
emitter.on(`*`, (_, changes: Array<PendingMutation>) => {
begin()
changes.forEach((change) => {
write({
type: change.type,
// @ts-expect-error TODO type changes
value: change.modified,
})
})
commit()
})
},
},
onInsert: mutationFn,
onUpdate: mutationFn,
onDelete: mutationFn,
})
await collection.stateWhenReady()
// Test non-optimistic insert
const nonOptimisticInsertTx = collection.insert(
{ id: 2, value: `non-optimistic insert` },
{ optimistic: false }
)
// Debug: Check the mutation was created with optimistic: false
expect(nonOptimisticInsertTx.mutations[0]?.optimistic).toBe(false)
// The item should NOT appear in the collection state immediately
expect(collection.state.has(2)).toBe(false)
expect(collection.optimisticUpserts.has(2)).toBe(false)
expect(collection.state.size).toBe(1) // Only the initial item
// Now resolve the mutation and wait for completion
pendingMutations[0]?.()
await nonOptimisticInsertTx.isPersisted.promise
// Now the item should appear after server confirmation
expect(collection.state.has(2)).toBe(true)
expect(collection.state.get(2)).toEqual({
id: 2,
value: `non-optimistic insert`,
})
// Test non-optimistic update
const nonOptimisticUpdateTx = collection.update(
1,
{ optimistic: false },
(draft) => {
draft.value = `non-optimistic update`
}
)
// The original value should still be there immediately
expect(collection.state.get(1)?.value).toBe(`initial value`)
expect(collection.optimisticUpserts.has(1)).toBe(false)
// Now resolve the update mutation and wait for completion
pendingMutations[1]?.()
await nonOptimisticUpdateTx.isPersisted.promise
// Now the update should be reflected
expect(collection.state.get(1)?.value).toBe(`non-optimistic update`)
// Test non-optimistic delete
const nonOptimisticDeleteTx = collection.delete(2, { optimistic: false })
// The item should still be there immediately
expect(collection.state.has(2)).toBe(true)
expect(collection.optimisticDeletes.has(2)).toBe(false)
// Now resolve the delete mutation and wait for completion
pendingMutations[2]?.()
await nonOptimisticDeleteTx.isPersisted.promise
// Now the item should be gone
expect(collection.state.has(2)).toBe(false)
})
it(`should apply optimistic updates by default and with explicit optimistic: true`, async () => {
const emitter = mitt()
const mutationFn = vi.fn().mockImplementation(async ({ transaction }) => {
// Simulate server persistence
emitter.emit(`sync`, transaction.mutations)
return Promise.resolve()
})
const collection = createCollection<{ id: number; value: string }>({
id: `optimistic-test`,
getKey: (item) => item.id,
startSync: true,
sync: {
sync: ({ begin, write, commit }) => {
// Initialize with some data
begin()
write({
type: `insert`,
value: { id: 1, value: `initial value` },
})
commit()
// @ts-expect-error don't trust mitt's typing
emitter.on(`*`, (_, changes: Array<PendingMutation>) => {
begin()
changes.forEach((change) => {
write({
type: change.type,
// @ts-expect-error TODO type changes
value: change.modified,
})
})
commit()
})
},
},
onInsert: mutationFn,
onUpdate: mutationFn,
onDelete: mutationFn,
})
await collection.stateWhenReady()
// Test default optimistic behavior (should be true)
const defaultOptimisticTx = collection.insert({
id: 2,
value: `default optimistic`,
})
// The item should appear immediately
expect(collection.state.has(2)).toBe(true)
expect(collection.optimisticUpserts.has(2)).toBe(true)
expect(collection.state.get(2)).toEqual({
id: 2,
value: `default optimistic`,
})
await defaultOptimisticTx.isPersisted.promise
// Test explicit optimistic: true
const explicitOptimisticTx = collection.insert(
{ id: 3, value: `explicit optimistic` },
{ optimistic: true }
)
// The item should appear immediately
expect(collection.state.has(3)).toBe(true)
expect(collection.optimisticUpserts.has(3)).toBe(true)
expect(collection.state.get(3)).toEqual({
id: 3,
value: `explicit optimistic`,
})
await explicitOptimisticTx.isPersisted.promise
// Test optimistic update
const optimisticUpdateTx = collection.update(
1,
{ optimistic: true },
(draft) => {
draft.value = `optimistic update`
}
)
// The update should be reflected immediately
expect(collection.state.get(1)?.value).toBe(`optimistic update`)
expect(collection.optimisticUpserts.has(1)).toBe(true)
await optimisticUpdateTx.isPersisted.promise
// Test optimistic delete
const optimisticDeleteTx = collection.delete(3, { optimistic: true })
// The item should be gone immediately
expect(collection.state.has(3)).toBe(false)
expect(collection.optimisticDeletes.has(3)).toBe(true)
await optimisticDeleteTx.isPersisted.promise
})
})
describe(`Collection with schema validation`, () => {
it(`should validate data against arktype schema on insert`, () => {
// Create a Zod schema for a user
const userSchema = type({
name: `string > 0`,
age: `number.integer > 0`,
"email?": `string.email`,
})
// Create a collection with the schema
const collection = createCollection<typeof userSchema.infer>({
id: `test`,
getKey: (item) => item.name,
startSync: true,
sync: {
sync: ({ begin, commit }) => {
begin()
commit()
},
},
schema: userSchema,
})
const mutationFn = async () => {}
// Valid data should work
const validUser = {
name: `Alice`,
age: 30,
email: `alice@example.com`,
}
const tx1 = createTransaction({ mutationFn })
tx1.mutate(() => collection.insert(validUser))
// Invalid data should throw SchemaValidationError
const invalidUser = {
name: ``, // Empty name (fails min length)
age: -5, // Negative age (fails positive)
email: `not-an-email`, // Invalid email
}
try {
const tx2 = createTransaction({ mutationFn })
tx2.mutate(() => collection.insert(invalidUser))
// Should not reach here
expect(true).toBe(false)
} catch (error) {
expect(error).toBeInstanceOf(SchemaValidationError)
if (error instanceof SchemaValidationError) {
expect(error.type).toBe(`insert`)