Created
October 27, 2023 01:01
-
-
Save pelly-ryu/a217fac0950dee2fdc19d35304d14907 to your computer and use it in GitHub Desktop.
/adapters/indexedDB/core.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { captureException } from "@sentry/vue"; | |
import { type DBSchema, openDB } from "idb"; | |
import { IDBPDatabase } from "idb/build/entry"; | |
export enum StoreName { | |
VisitLocation = "visitLocation", | |
ActionLog = "actionLog", | |
} | |
export interface LocationWithTimestamp { | |
location: Partial<Location>; | |
timestamp: Date; | |
} | |
export interface ActionLog { | |
action: string; | |
at: Date; | |
} | |
export interface DefaultDB extends DBSchema { | |
[StoreName.VisitLocation]: { | |
key: number; | |
value: LocationWithTimestamp; | |
}; | |
[StoreName.ActionLog]: { | |
key: number; | |
value: ActionLog; | |
}; | |
} | |
const DBName = "db"; | |
let dbPromise: Promise<IDBPDatabase<DefaultDB>> | null = null; | |
export async function getDb() { | |
if (!dbPromise) { | |
const dbVersion = 2; | |
dbPromise = openDB<DefaultDB>(DBName, dbVersion, { | |
upgrade(db, oldVersion) { | |
if (oldVersion < 1) { | |
try { | |
db.createObjectStore(StoreName.VisitLocation, { | |
keyPath: "id", | |
autoIncrement: true, | |
}); | |
} catch (e) { | |
captureException(e); | |
} | |
} | |
if (oldVersion < 2) { | |
try { | |
db.createObjectStore(StoreName.ActionLog, { | |
keyPath: "id", | |
autoIncrement: true, | |
}); | |
} catch (e) { | |
captureException(e); | |
} | |
} | |
}, | |
}); | |
} | |
return await dbPromise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment