From c44aeca2fb9bb8f3fca342f4a2c5c5089497d323 Mon Sep 17 00:00:00 2001 From: Justin Leider Date: Thu, 5 Jun 2025 13:30:16 -0400 Subject: [PATCH] Fix schema upgrade handling --- package.json | 2 +- src/database.ts | 7 ++++++- test/database.test.ts | 21 ++++++++++++++++++--- 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index e608956..600a571 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "fp-ts-indexeddb", - "version": "0.2.2", + "version": "0.2.3", "description": "Simple FP-TS based wrapper around indexedDB", "main": "dist/lib/index.js", "module": "dist/es2015/index.js", diff --git a/src/database.ts b/src/database.ts index 8d36d93..6df78f8 100644 --- a/src/database.ts +++ b/src/database.ts @@ -47,7 +47,10 @@ export const open = ( const req = window.indexedDB.open(dbName, schema.version); req.onupgradeneeded = () => pipe( schema.stores, - R.mapWithIndex((storeName: string, v: Store) => req.result.createObjectStore(storeName, { keyPath: v.key })) + R.mapWithIndex((storeName: string, v: Store) => { + req.result.objectStoreNames.contains(storeName) && req.result.deleteObjectStore(storeName); + req.result.createObjectStore(storeName, { keyPath: v.key }); + }) ); req.onsuccess = () => resolve({ database: req.result, schema: schema }); @@ -194,3 +197,5 @@ export const clearStore = ( }), handlePromiseError, ); + +export const close = (db: DatabaseInfo): void => db.database.close(); \ No newline at end of file diff --git a/test/database.test.ts b/test/database.test.ts index 7ec17a4..7fe3e7d 100644 --- a/test/database.test.ts +++ b/test/database.test.ts @@ -4,6 +4,7 @@ import * as t from 'io-ts'; import { DBSchema, + close, get, getAll, insert, @@ -20,7 +21,7 @@ const userC = t.type({ type UserC = typeof userC; type User = t.TypeOf; -const schema: DBSchema = { +const schema1: DBSchema = { version: 1, stores: { 'users': { @@ -29,6 +30,7 @@ const schema: DBSchema = { } } }; +const schema2: DBSchema = { ...schema1, version: 2 }; const dbErrorTe = TE.left(new DOMException('Error loading database')); @@ -36,7 +38,7 @@ describe('IndexedDb - Tests', () => { it('Crud - Functions', async () => { // Set Database await pipe( - open('my-db31', schema), + open('my-db31', schema1), TE.match( fail, async (db) => { @@ -68,7 +70,7 @@ describe('IndexedDb - Tests', () => { (rows) => { expect(rows.length).toBeGreaterThanOrEqual(1); pipe( - O.fromNullable(schema.stores.users?.codec), + O.fromNullable(schema1.stores.users?.codec), O.map((c) => { expect(t.array(c).is(rows)).toBeTruthy(); }) @@ -107,7 +109,20 @@ describe('IndexedDb - Tests', () => { }, ) )(); + + close(db); }, + ), + )(); + + // Upgrade schema + await pipe( + open('my-db31', schema2), + TE.match( + fail, + (db) => { + expect(db.schema.version).toEqual(schema2.version); + } ) )(); });