forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-storage.test.ts
More file actions
775 lines (649 loc) · 22.6 KB
/
local-storage.test.ts
File metadata and controls
775 lines (649 loc) · 22.6 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
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createCollection } from "../src/index"
import { localStorageCollectionOptions } from "../src/local-storage"
import {
NoStorageAvailableError,
NoStorageEventApiError,
StorageKeyRequiredError,
} from "../src/errors"
import type { StorageEventApi } from "../src/local-storage"
// Mock storage implementation for testing that properly implements Storage interface
class MockStorage implements Storage {
private store: Record<string, string> = {}
get length(): number {
return Object.keys(this.store).length
}
getItem(key: string): string | null {
return this.store[key] || null
}
setItem(key: string, value: string): void {
this.store[key] = value
}
removeItem(key: string): void {
delete this.store[key]
}
clear(): void {
this.store = {}
}
key(index: number): string | null {
const keys = Object.keys(this.store)
return keys[index] || null
}
}
// Mock storage event API for testing
class MockStorageEventApi implements StorageEventApi {
private listeners: Array<(event: StorageEvent) => void> = []
addEventListener(
type: `storage`,
listener: (event: StorageEvent) => void
): void {
this.listeners.push(listener)
}
removeEventListener(
type: `storage`,
listener: (event: StorageEvent) => void
): void {
const index = this.listeners.indexOf(listener)
if (index > -1) {
this.listeners.splice(index, 1)
}
}
// Helper method for tests to trigger storage events
triggerStorageEvent(event: StorageEvent): void {
this.listeners.forEach((listener) => listener(event))
}
}
// Test interface for todo items
interface Todo {
id: string
title: string
completed: boolean
createdAt: Date
}
describe(`localStorage collection`, () => {
let mockStorage: MockStorage
let mockStorageEventApi: MockStorageEventApi
beforeEach(() => {
mockStorage = new MockStorage()
mockStorageEventApi = new MockStorageEventApi()
})
afterEach(() => {
mockStorage.clear()
vi.clearAllMocks()
})
describe(`basic functionality`, () => {
it(`should create a localStorage collection with required config`, () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
expect(collection).toBeDefined()
expect(collection.utils.clearStorage).toBeDefined()
expect(collection.utils.getStorageSize).toBeDefined()
})
it(`should default id to local-collection:storageKey pattern`, () => {
const options = localStorageCollectionOptions<Todo>({
storageKey: `my-todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
expect(options.id).toBe(`local-collection:my-todos`)
})
it(`should use provided id when specified`, () => {
const options = localStorageCollectionOptions<Todo>({
storageKey: `my-todos`,
id: `custom-collection-id`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
expect(options.id).toBe(`custom-collection-id`)
})
it(`should throw error when storageKey is missing`, () => {
expect(() =>
localStorageCollectionOptions({
storageKey: ``,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (item: any) => item.id,
})
).toThrow(StorageKeyRequiredError)
})
it(`should throw error when no storage is available`, () => {
// Mock window to be undefined globally
const originalWindow = globalThis.window
// @ts-ignore - Temporarily delete window to test error condition
delete globalThis.window
expect(() =>
localStorageCollectionOptions({
storageKey: `test`,
storageEventApi: mockStorageEventApi,
getKey: (item: any) => item.id,
})
).toThrow(NoStorageAvailableError)
// Restore window
globalThis.window = originalWindow
})
it(`should throw error when no storage event API is available`, () => {
// Mock window to be undefined globally
const originalWindow = globalThis.window
// @ts-ignore - Temporarily delete window to test error condition
delete globalThis.window
expect(() =>
localStorageCollectionOptions({
storageKey: `test`,
storage: mockStorage,
getKey: (item: any) => item.id,
})
).toThrow(NoStorageEventApiError)
// Restore window
globalThis.window = originalWindow
})
})
describe(`data persistence`, () => {
it(`should load existing data from storage on initialization`, () => {
// Pre-populate storage with new versioned format
const existingTodos = {
"1": {
versionKey: `test-version-1`,
data: {
id: `1`,
title: `Existing Todo`,
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(existingTodos))
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
// Should load the existing data
expect(collection.size).toBe(1)
expect(collection.get(`1`)?.title).toBe(`Existing Todo`)
unsubscribe()
})
it(`should handle corrupted storage data gracefully`, () => {
// Set invalid JSON data
mockStorage.setItem(`todos`, `invalid json data`)
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Should initialize with empty collection
expect(collection.size).toBe(0)
})
it(`should handle empty storage gracefully`, () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Should initialize with empty collection
expect(collection.size).toBe(0)
})
})
describe(`mutation handlers with storage operations`, () => {
it(`should persist data even without mutation handlers`, async () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
// No onInsert, onUpdate, or onDelete handlers provided
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
const todo: Todo = {
id: `1`,
title: `Test Todo Without Handlers`,
completed: false,
createdAt: new Date(),
}
// Insert without handlers should still persist
const insertTx = collection.insert(todo)
await insertTx.isPersisted.promise
// Check that it was saved to storage
let storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
let parsed = JSON.parse(storedData!)
expect(parsed[`1`].data.title).toBe(`Test Todo Without Handlers`)
// Update without handlers should still persist
const updateTx = collection.update(`1`, (draft) => {
draft.title = `Updated Without Handlers`
})
await updateTx.isPersisted.promise
// Check that update was saved to storage
storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
parsed = JSON.parse(storedData!)
expect(parsed[`1`].data.title).toBe(`Updated Without Handlers`)
// Delete without handlers should still persist
const deleteTx = collection.delete(`1`)
await deleteTx.isPersisted.promise
// Check that deletion was saved to storage
storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
parsed = JSON.parse(storedData!)
expect(parsed[`1`]).toBeUndefined()
unsubscribe()
})
it(`should call mutation handlers when provided and still persist data`, async () => {
const insertSpy = vi.fn().mockResolvedValue({ success: true })
const updateSpy = vi.fn().mockResolvedValue({ success: true })
const deleteSpy = vi.fn().mockResolvedValue({ success: true })
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
onInsert: insertSpy,
onUpdate: updateSpy,
onDelete: deleteSpy,
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
const todo: Todo = {
id: `1`,
title: `Test Todo With Handlers`,
completed: false,
createdAt: new Date(),
}
// Insert should call handler AND persist
const insertTx = collection.insert(todo)
await insertTx.isPersisted.promise
expect(insertSpy).toHaveBeenCalledOnce()
let storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
let parsed = JSON.parse(storedData!)
expect(parsed[`1`].data.title).toBe(`Test Todo With Handlers`)
// Update should call handler AND persist
const updateTx = collection.update(`1`, (draft) => {
draft.title = `Updated With Handlers`
})
await updateTx.isPersisted.promise
expect(updateSpy).toHaveBeenCalledOnce()
storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
parsed = JSON.parse(storedData!)
expect(parsed[`1`].data.title).toBe(`Updated With Handlers`)
// Delete should call handler AND persist
const deleteTx = collection.delete(`1`)
await deleteTx.isPersisted.promise
expect(deleteSpy).toHaveBeenCalledOnce()
storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
parsed = JSON.parse(storedData!)
expect(parsed[`1`]).toBeUndefined()
unsubscribe()
})
it(`should perform insert operations and update storage`, async () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
onInsert: () => Promise.resolve({ success: true }),
})
)
const todo: Todo = {
id: `1`,
title: `Test Todo`,
completed: false,
createdAt: new Date(),
}
// When a collection has mutation handlers, calling insert() automatically creates
// a transaction and calls the onInsert handler
const tx = collection.insert(todo)
await tx.isPersisted.promise
// Check that it was saved to storage with version key structure
const storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
const parsed = JSON.parse(storedData!)
expect(typeof parsed).toBe(`object`)
expect(parsed[`1`]).toBeDefined()
expect(parsed[`1`].versionKey).toBeDefined()
expect(typeof parsed[`1`].versionKey).toBe(`string`)
expect(parsed[`1`].data.id).toBe(`1`)
expect(parsed[`1`].data.title).toBe(`Test Todo`)
})
it(`should perform update operations and update storage`, async () => {
// Pre-populate storage
const initialData = {
"1": {
versionKey: `initial-version`,
data: {
id: `1`,
title: `Initial Todo`,
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(initialData))
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
onUpdate: () => Promise.resolve({ success: true }),
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
// Update the todo - this automatically creates a transaction and calls onUpdate
const tx = collection.update(`1`, (draft) => {
draft.title = `Updated Todo`
})
await tx.isPersisted.promise
// Check that it was updated in storage with a new version key
const storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
const parsed = JSON.parse(storedData!)
expect(parsed[`1`].versionKey).not.toBe(`initial-version`) // Should have new version key
expect(parsed[`1`].data.title).toBe(`Updated Todo`)
unsubscribe()
})
it(`should perform delete operations and update storage`, async () => {
// Pre-populate storage
const initialData = {
"1": {
versionKey: `test-version`,
data: {
id: `1`,
title: `To Delete`,
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(initialData))
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
onDelete: () => Promise.resolve({ success: true }),
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
// Delete the todo - this automatically creates a transaction and calls onDelete
const tx = collection.delete(`1`)
await tx.isPersisted.promise
// Check that it was removed from storage
const storedData = mockStorage.getItem(`todos`)
expect(storedData).toBeDefined()
const parsed = JSON.parse(storedData!)
expect(parsed[`1`]).toBeUndefined()
unsubscribe()
})
})
describe(`cross-tab synchronization`, () => {
it(`should detect changes from other tabs using version keys`, () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
// Simulate data being added from another tab
const newTodoData = {
"1": {
versionKey: `from-other-tab`,
data: {
id: `1`,
title: `From Another Tab`,
completed: false,
createdAt: new Date(),
},
},
}
// Directly update storage (simulating another tab)
mockStorage.setItem(`todos`, JSON.stringify(newTodoData))
// Create a mock storage event (avoiding JSDOM constructor issues)
const storageEvent = {
type: `storage`,
key: `todos`,
oldValue: null,
newValue: JSON.stringify(newTodoData),
url: `http://localhost`,
storageArea: mockStorage,
} as unknown as StorageEvent
// Trigger the storage event
mockStorageEventApi.triggerStorageEvent(storageEvent)
// The collection should now have the new todo
expect(collection.size).toBe(1)
expect(collection.get(`1`)?.title).toBe(`From Another Tab`)
unsubscribe()
})
it(`should ignore storage events for different keys`, () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Create a mock storage event for different key
const storageEvent = {
type: `storage`,
key: `other-key`,
oldValue: null,
newValue: JSON.stringify({ test: `data` }),
url: `http://localhost`,
storageArea: mockStorage,
} as unknown as StorageEvent
// Trigger the storage event
mockStorageEventApi.triggerStorageEvent(storageEvent)
// Collection should remain empty
expect(collection.size).toBe(0)
})
it(`should ignore storage events from different storage areas`, () => {
const otherStorage = new MockStorage()
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Create a mock storage event from different storage area
const storageEvent = {
type: `storage`,
key: `todos`,
oldValue: null,
newValue: JSON.stringify({ test: `data` }),
url: `http://localhost`,
storageArea: otherStorage,
} as unknown as StorageEvent
// Trigger the storage event
mockStorageEventApi.triggerStorageEvent(storageEvent)
// Collection should remain empty
expect(collection.size).toBe(0)
})
})
describe(`utility functions`, () => {
it(`should clear storage`, () => {
mockStorage.setItem(`todos`, JSON.stringify({ test: `data` }))
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
collection.utils.clearStorage()
expect(mockStorage.getItem(`todos`)).toBeNull()
})
it(`should get storage size`, () => {
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
expect(collection.utils.getStorageSize()).toBe(0)
mockStorage.setItem(`todos`, JSON.stringify({ test: `data` }))
const size = collection.utils.getStorageSize()
expect(size).toBeGreaterThan(0)
})
})
describe(`getSyncMetadata`, () => {
it(`should return correct metadata`, () => {
const options = localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
const metadata = options.sync.getSyncMetadata?.()
expect(metadata).toEqual({
storageKey: `todos`,
storageType: `custom`,
})
})
})
describe(`version key change detection`, () => {
it(`should detect version key changes for updates`, () => {
// Pre-populate storage
const initialData = {
"1": {
versionKey: `version-1`,
data: {
id: `1`,
title: `Initial`,
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(initialData))
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Subscribe to trigger sync
const unsubscribe = collection.subscribeChanges(() => {})
expect(collection.size).toBe(1)
expect(collection.get(`1`)?.title).toBe(`Initial`)
// Simulate change from another tab with different version key but same data
const updatedData = {
"1": {
versionKey: `version-2`, // Different version key
data: {
id: `1`,
title: `Updated`, // Different title
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(updatedData))
// Create a mock storage event
const storageEvent = {
type: `storage`,
key: `todos`,
oldValue: JSON.stringify(initialData),
newValue: JSON.stringify(updatedData),
url: `http://localhost`,
storageArea: mockStorage,
} as unknown as StorageEvent
mockStorageEventApi.triggerStorageEvent(storageEvent)
// Should detect the change based on version key difference
expect(collection.size).toBe(1)
expect(collection.get(`1`)?.title).toBe(`Updated`)
unsubscribe()
})
it(`should not trigger unnecessary updates for same version key`, () => {
const changesSpy = vi.fn()
// Pre-populate storage
const initialData = {
"1": {
versionKey: `version-1`,
data: {
id: `1`,
title: `Same`,
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(initialData))
const collection = createCollection(
localStorageCollectionOptions<Todo>({
storageKey: `todos`,
storage: mockStorage,
storageEventApi: mockStorageEventApi,
getKey: (todo) => todo.id,
})
)
// Subscribe to changes to monitor
collection.subscribeChanges(changesSpy)
// Simulate "change" from another tab with same version key
const sameData = {
"1": {
versionKey: `version-1`, // Same version key
data: {
id: `1`,
title: `Same`,
completed: false,
createdAt: new Date(),
},
},
}
mockStorage.setItem(`todos`, JSON.stringify(sameData))
// Create a mock storage event
const storageEvent = {
type: `storage`,
key: `todos`,
oldValue: JSON.stringify(initialData),
newValue: JSON.stringify(sameData),
url: `http://localhost`,
storageArea: mockStorage,
} as unknown as StorageEvent
mockStorageEventApi.triggerStorageEvent(storageEvent)
// Should not trigger any changes since version key is the same
expect(changesSpy).not.toHaveBeenCalled()
})
})
})