diff options
author | Florian Dold <florian.dold@gmail.com> | 2020-08-03 13:00:48 +0530 |
---|---|---|
committer | Florian Dold <florian.dold@gmail.com> | 2020-08-03 13:01:05 +0530 |
commit | ffd2a62c3f7df94365980302fef3bc3376b48182 (patch) | |
tree | 270af6f16b4cc7f5da2afdba55c8bc9dbea5eca5 /packages/taler-wallet-core/src/db.ts | |
parent | aa481e42675fb7c4dcbbeec0ba1c61e1953b9596 (diff) | |
download | wallet-core-ffd2a62c3f7df94365980302fef3bc3376b48182.tar.xz |
modularize repo, use pnpm, improve typechecking
Diffstat (limited to 'packages/taler-wallet-core/src/db.ts')
-rw-r--r-- | packages/taler-wallet-core/src/db.ts | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/packages/taler-wallet-core/src/db.ts b/packages/taler-wallet-core/src/db.ts new file mode 100644 index 000000000..a6eeb1205 --- /dev/null +++ b/packages/taler-wallet-core/src/db.ts @@ -0,0 +1,66 @@ +import { Stores } from "./types/dbTypes"; +import { openDatabase, Database, Store, Index } from "./util/query"; +import type { idbtypes } from "idb-bridge"; + +/** + * Name of the Taler database. The name includes the + * major version of the DB schema. The version should be incremented + * with each major change. When incrementing the major version, + * the wallet should import data from the previous version. + */ +const TALER_DB_NAME = "taler-walletdb-v7"; + +/** + * Current database minor version, should be incremented + * each time we do minor schema changes on the database. + * A change is considered minor when fields are added in a + * backwards-compatible way or object stores and indices + * are added. + */ +export const WALLET_DB_MINOR_VERSION = 1; + +/** + * Return a promise that resolves + * to the taler wallet db. + */ +export function openTalerDatabase( + idbFactory: idbtypes.IDBFactory, + onVersionChange: () => void, +): Promise<idbtypes.IDBDatabase> { + const onUpgradeNeeded = ( + db: idbtypes.IDBDatabase, + oldVersion: number, + newVersion: number, + ): void => { + switch (oldVersion) { + case 0: // DB does not exist yet + for (const n in Stores) { + if ((Stores as any)[n] instanceof Store) { + const si: Store<any> = (Stores as any)[n]; + const s = db.createObjectStore(si.name, si.storeParams); + for (const indexName in si as any) { + if ((si as any)[indexName] instanceof Index) { + const ii: Index<any, any> = (si as any)[indexName]; + s.createIndex(ii.indexName, ii.keyPath, ii.options); + } + } + } + } + break; + default: + throw Error("unsupported existig DB version"); + } + }; + + return openDatabase( + idbFactory, + TALER_DB_NAME, + WALLET_DB_MINOR_VERSION, + onVersionChange, + onUpgradeNeeded, + ); +} + +export function deleteTalerDatabase(idbFactory: idbtypes.IDBFactory): void { + Database.deleteDatabase(idbFactory, TALER_DB_NAME); +} |