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
620import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
describe('IndexedDB', () => {
// ============================================================
// UTILITY FUNCTIONS - PROMISIFY PATTERN
// From indexeddb.mdx lines 359-389
// ============================================================
describe('Promise Wrapper Utilities', () => {
// From lines 366-371: promisifyRequest helper function
describe('promisifyRequest', () => {
it('should resolve with the result on success', async () => {
function promisifyRequest(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
}
// Mock an IDBRequest-like object
const mockRequest = {
result: 'test-data',
onsuccess: null,
onerror: null
}
const promise = promisifyRequest(mockRequest)
// Trigger success
mockRequest.onsuccess()
const result = await promise
expect(result).toBe('test-data')
})
it('should reject with error on failure', async () => {
function promisifyRequest(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
}
const mockError = new Error('Database error')
const mockRequest = {
result: null,
error: mockError,
onsuccess: null,
onerror: null
}
const promise = promisifyRequest(mockRequest)
// Trigger error
mockRequest.onerror()
await expect(promise).rejects.toThrow('Database error')
})
})
// From lines 374-383: openDatabase helper function
describe('openDatabase', () => {
it('should resolve with db on success and call onUpgrade', async () => {
function openDatabase(name, version, onUpgrade) {
return new Promise((resolve, reject) => {
// Simulate the IndexedDB open behavior
const mockDb = { name, version, objectStoreNames: { contains: () => false } }
const request = {
result: mockDb,
onupgradeneeded: null,
onsuccess: null,
onerror: null
}
// Simulate upgrade needed
setTimeout(() => {
if (request.onupgradeneeded) {
request.onupgradeneeded({ target: { result: mockDb } })
}
if (request.onsuccess) {
request.onsuccess()
}
}, 0)
request.onupgradeneeded = (event) => onUpgrade(event.target.result)
request.onsuccess = () => resolve(request.result)
request.onerror = () => reject(request.error)
})
}
let upgradeCalled = false
const db = await openDatabase('TestDB', 1, (db) => {
upgradeCalled = true
expect(db.name).toBe('TestDB')
})
expect(db.name).toBe('TestDB')
expect(db.version).toBe(1)
expect(upgradeCalled).toBe(true)
})
})
})
// ============================================================
// KEY RANGE UTILITIES
// From indexeddb.mdx lines 296-310
// ============================================================
describe('IDBKeyRange Patterns', () => {
// Simulated IDBKeyRange for testing purposes
const IDBKeyRange = {
only: (value) => ({ type: 'only', value }),
lowerBound: (value, open = false) => ({ type: 'lowerBound', value, open }),
upperBound: (value, open = false) => ({ type: 'upperBound', value, open }),
bound: (lower, upper, lowerOpen = false, upperOpen = false) => ({
type: 'bound',
lower,
upper,
lowerOpen,
upperOpen
})
}
it('should create only range for exact match', () => {
const range = IDBKeyRange.only(5)
expect(range.type).toBe('only')
expect(range.value).toBe(5)
})
it('should create lowerBound range (inclusive by default)', () => {
const range = IDBKeyRange.lowerBound(5)
expect(range.type).toBe('lowerBound')
expect(range.value).toBe(5)
expect(range.open).toBe(false)
})
it('should create lowerBound range (exclusive)', () => {
const range = IDBKeyRange.lowerBound(5, true)
expect(range.type).toBe('lowerBound')
expect(range.value).toBe(5)
expect(range.open).toBe(true)
})
it('should create upperBound range (inclusive by default)', () => {
const range = IDBKeyRange.upperBound(10)
expect(range.type).toBe('upperBound')
expect(range.value).toBe(10)
expect(range.open).toBe(false)
})
it('should create bound range with both bounds', () => {
const range = IDBKeyRange.bound(5, 10)
expect(range.type).toBe('bound')
expect(range.lower).toBe(5)
expect(range.upper).toBe(10)
expect(range.lowerOpen).toBe(false)
expect(range.upperOpen).toBe(false)
})
it('should create bound range with open bounds', () => {
const range = IDBKeyRange.bound(5, 10, true, false)
expect(range.type).toBe('bound')
expect(range.lower).toBe(5)
expect(range.upper).toBe(10)
expect(range.lowerOpen).toBe(true)
expect(range.upperOpen).toBe(false)
})
})
// ============================================================
// DATABASE HELPER CLASS PATTERN
// From indexeddb.mdx lines 440-478
// ============================================================
describe('UserDatabase Helper Class Pattern', () => {
// From lines 440-478: UserDatabase class implementation
it('should demonstrate the helper class pattern', () => {
// Mock database object for testing the pattern
const mockStore = new Map()
class UserDatabase {
constructor() {
this.store = mockStore
}
async add(user) {
if (this.store.has(user.id)) {
throw new Error('User already exists')
}
this.store.set(user.id, user)
return user.id
}
async get(id) {
return this.store.get(id)
}
async getByEmail(email) {
for (const user of this.store.values()) {
if (user.email === email) return user
}
return undefined
}
async update(user) {
this.store.set(user.id, user)
return user.id
}
async delete(id) {
this.store.delete(id)
}
async getAll() {
return Array.from(this.store.values())
}
}
const users = new UserDatabase()
// Verify the class has the expected methods
expect(typeof users.add).toBe('function')
expect(typeof users.get).toBe('function')
expect(typeof users.getByEmail).toBe('function')
expect(typeof users.update).toBe('function')
expect(typeof users.delete).toBe('function')
expect(typeof users.getAll).toBe('function')
})
it('should perform CRUD operations correctly', async () => {
const mockStore = new Map()
class UserDatabase {
constructor() {
this.store = mockStore
}
async add(user) {
if (this.store.has(user.id)) {
throw new Error('User already exists')
}
this.store.set(user.id, user)
return user.id
}
async get(id) {
return this.store.get(id)
}
async getByEmail(email) {
for (const user of this.store.values()) {
if (user.email === email) return user
}
return undefined
}
async update(user) {
this.store.set(user.id, user)
return user.id
}
async delete(id) {
this.store.delete(id)
}
async getAll() {
return Array.from(this.store.values())
}
}
const users = new UserDatabase()
// Add
await users.add({ id: 1, name: 'Alice', email: 'alice@example.com' })
expect(await users.get(1)).toEqual({ id: 1, name: 'Alice', email: 'alice@example.com' })
// Get by email
const alice = await users.getByEmail('alice@example.com')
expect(alice.name).toBe('Alice')
// Update
await users.update({ id: 1, name: 'Alice Updated', email: 'alice@example.com' })
expect((await users.get(1)).name).toBe('Alice Updated')
// Get all
await users.add({ id: 2, name: 'Bob', email: 'bob@example.com' })
const allUsers = await users.getAll()
expect(allUsers).toHaveLength(2)
// Delete
await users.delete(1)
expect(await users.get(1)).toBeUndefined()
})
})
// ============================================================
// SYNC QUEUE PATTERN
// From indexeddb.mdx lines 410-433
// ============================================================
describe('Sync Queue Pattern', () => {
// From lines 410-433: Offline sync queue pattern
it('should queue actions for later sync', async () => {
const syncQueue = []
async function queueAction(action) {
syncQueue.push({
action,
timestamp: Date.now(),
status: 'pending'
})
}
await queueAction({ type: 'CREATE_POST', data: { title: 'Hello' } })
await queueAction({ type: 'UPDATE_USER', data: { name: 'Alice' } })
expect(syncQueue).toHaveLength(2)
expect(syncQueue[0].action.type).toBe('CREATE_POST')
expect(syncQueue[0].status).toBe('pending')
expect(syncQueue[1].action.type).toBe('UPDATE_USER')
})
it('should filter pending actions for sync', async () => {
const syncQueue = [
{ id: 1, action: { type: 'A' }, status: 'pending' },
{ id: 2, action: { type: 'B' }, status: 'synced' },
{ id: 3, action: { type: 'C' }, status: 'pending' }
]
const pending = syncQueue.filter(item => item.status === 'pending')
expect(pending).toHaveLength(2)
expect(pending[0].action.type).toBe('A')
expect(pending[1].action.type).toBe('C')
})
})
// ============================================================
// TRANSACTION MODE CONCEPTS
// From indexeddb.mdx lines 227-261
// ============================================================
describe('Transaction Mode Concepts', () => {
it('should understand readonly vs readwrite modes', () => {
const transactionModes = {
readonly: {
canRead: true,
canWrite: false,
canRunInParallel: true,
description: 'Only reading data (faster, can run in parallel)'
},
readwrite: {
canRead: true,
canWrite: true,
canRunInParallel: false,
description: 'Reading and writing (locks the store)'
}
}
// Readonly mode
expect(transactionModes.readonly.canRead).toBe(true)
expect(transactionModes.readonly.canWrite).toBe(false)
expect(transactionModes.readonly.canRunInParallel).toBe(true)
// Readwrite mode
expect(transactionModes.readwrite.canRead).toBe(true)
expect(transactionModes.readwrite.canWrite).toBe(true)
expect(transactionModes.readwrite.canRunInParallel).toBe(false)
})
})
// ============================================================
// STORAGE COMPARISON DATA
// From indexeddb.mdx lines 318-330
// ============================================================
describe('Storage Comparison Data', () => {
it('should correctly represent storage feature differences', () => {
const storageOptions = {
localStorage: {
storageLimit: '~5MB',
dataTypes: 'Strings only',
async: false,
queryable: false,
transactions: false,
persists: 'Until cleared',
workerAccess: false
},
sessionStorage: {
storageLimit: '~5MB',
dataTypes: 'Strings only',
async: false,
queryable: false,
transactions: false,
persists: 'Until tab closes',
workerAccess: false
},
indexedDB: {
storageLimit: 'Gigabytes',
dataTypes: 'Any JS value',
async: true,
queryable: true,
transactions: true,
persists: 'Until cleared',
workerAccess: true
},
cookies: {
storageLimit: '~4KB',
dataTypes: 'Strings only',
async: false,
queryable: false,
transactions: false,
persists: 'Configurable',
workerAccess: false
}
}
// IndexedDB advantages
expect(storageOptions.indexedDB.async).toBe(true)
expect(storageOptions.indexedDB.queryable).toBe(true)
expect(storageOptions.indexedDB.transactions).toBe(true)
expect(storageOptions.indexedDB.workerAccess).toBe(true)
// localStorage limitations
expect(storageOptions.localStorage.async).toBe(false)
expect(storageOptions.localStorage.dataTypes).toBe('Strings only')
// Cookies limitation
expect(storageOptions.cookies.storageLimit).toBe('~4KB')
})
})
// ============================================================
// VERSION MIGRATION PATTERN
// From indexeddb.mdx lines 130-150
// ============================================================
describe('Database Version Migration Pattern', () => {
it('should handle version-based migrations correctly', () => {
function runMigrations(db, oldVersion) {
const migrations = []
if (oldVersion < 1) {
migrations.push('create users store')
}
if (oldVersion < 2) {
migrations.push('create posts store')
}
if (oldVersion < 3) {
migrations.push('add email index to users')
}
return migrations
}
// Fresh install (version 0 -> 3)
expect(runMigrations({}, 0)).toEqual([
'create users store',
'create posts store',
'add email index to users'
])
// Upgrade from version 1 -> 3
expect(runMigrations({}, 1)).toEqual([
'create posts store',
'add email index to users'
])
// Upgrade from version 2 -> 3
expect(runMigrations({}, 2)).toEqual([
'add email index to users'
])
// Already at version 3
expect(runMigrations({}, 3)).toEqual([])
})
})
// ============================================================
// ADD VS PUT BEHAVIOR
// From indexeddb.mdx lines 185-188
// ============================================================
describe('add() vs put() Behavior', () => {
it('should demonstrate add() fails on duplicate keys', async () => {
const store = new Map()
function add(key, value) {
if (store.has(key)) {
throw new Error('Key already exists')
}
store.set(key, value)
}
add(1, { name: 'Alice' })
expect(store.get(1)).toEqual({ name: 'Alice' })
// Adding same key should throw
expect(() => add(1, { name: 'Bob' })).toThrow('Key already exists')
})
it('should demonstrate put() inserts or updates', () => {
const store = new Map()
function put(key, value) {
store.set(key, value) // Always succeeds
}
put(1, { name: 'Alice' })
expect(store.get(1)).toEqual({ name: 'Alice' })
// Put with same key should update
put(1, { name: 'Alice Updated' })
expect(store.get(1)).toEqual({ name: 'Alice Updated' })
})
})
// ============================================================
// OBJECT STORE CONFIGURATION
// From indexeddb.mdx lines 154-178
// ============================================================
describe('Object Store Configuration Options', () => {
it('should understand keyPath option', () => {
const config = { keyPath: 'id' }
// Records must have the keyPath property
const validRecord = { id: 1, name: 'Alice' }
const invalidRecord = { name: 'Bob' } // Missing 'id'
expect(validRecord[config.keyPath]).toBe(1)
expect(invalidRecord[config.keyPath]).toBeUndefined()
})
it('should understand autoIncrement option', () => {
const config = { autoIncrement: true }
let counter = 0
function generateKey() {
return ++counter
}
expect(generateKey()).toBe(1)
expect(generateKey()).toBe(2)
expect(generateKey()).toBe(3)
})
it('should understand combined keyPath and autoIncrement', () => {
const config = { keyPath: 'id', autoIncrement: true }
let counter = 0
function addRecord(record) {
if (!record[config.keyPath]) {
record[config.keyPath] = ++counter
}
return record
}
const record1 = addRecord({ name: 'Alice' })
expect(record1.id).toBe(1)
const record2 = addRecord({ name: 'Bob' })
expect(record2.id).toBe(2)
// If id is already provided, use it
const record3 = addRecord({ id: 100, name: 'Charlie' })
expect(record3.id).toBe(100)
})
})
// ============================================================
// CURSOR ITERATION PATTERN
// From indexeddb.mdx lines 272-292
// ============================================================
describe('Cursor Iteration Pattern', () => {
it('should iterate through records one at a time', () => {
const records = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
]
let index = 0
const results = []
// Simulating cursor behavior
function openCursor() {
return {
get current() {
if (index < records.length) {
return {
key: records[index].id,
value: records[index]
}
}
return null
},
continue() {
index++
}
}
}
const cursor = openCursor()
while (cursor.current) {
results.push({ key: cursor.current.key, value: cursor.current.value })
cursor.continue()
}
expect(results).toHaveLength(3)
expect(results[0].key).toBe(1)
expect(results[0].value.name).toBe('Alice')
expect(results[2].key).toBe(3)
expect(results[2].value.name).toBe('Charlie')
})
})
})