2021-02-14 02:36:00 +00:00
|
|
|
// eslint-disable-next-line no-unused-vars
|
2021-05-01 02:54:00 +00:00
|
|
|
import Dexie, { DexieOptions } from "dexie";
|
2021-04-22 06:53:35 +00:00
|
|
|
import { v4 as uuid } from "uuid";
|
2021-05-01 02:54:00 +00:00
|
|
|
import "dexie-observable";
|
2021-02-14 02:36:00 +00:00
|
|
|
|
2021-05-01 02:54:00 +00:00
|
|
|
import { loadVersions, latestVersion } from "./upgrade";
|
|
|
|
import { getDefaultMaps } from "./maps";
|
|
|
|
import { getDefaultTokens } from "./tokens";
|
2021-02-14 02:36:00 +00:00
|
|
|
|
|
|
|
/**
|
2021-05-01 02:54:00 +00:00
|
|
|
* Populate DB with initial data
|
2021-02-14 02:36:00 +00:00
|
|
|
* @param {Dexie} db
|
|
|
|
*/
|
2021-05-01 02:54:00 +00:00
|
|
|
function populate(db) {
|
|
|
|
db.on("populate", () => {
|
|
|
|
const userId = uuid();
|
|
|
|
db.table("user").add({ key: "userId", value: userId });
|
|
|
|
const { maps, mapStates } = getDefaultMaps(userId);
|
|
|
|
db.table("maps").bulkAdd(maps);
|
|
|
|
db.table("states").bulkAdd(mapStates);
|
|
|
|
const tokens = getDefaultTokens(userId);
|
|
|
|
db.table("tokens").bulkAdd(tokens);
|
2021-05-13 06:27:21 +00:00
|
|
|
db.table("groups").bulkAdd([
|
|
|
|
{ id: "maps", data: maps.map((map) => map.id) },
|
|
|
|
{ id: "tokens", data: tokens.map((token) => token.id) },
|
|
|
|
]);
|
2021-05-01 02:54:00 +00:00
|
|
|
});
|
2020-05-03 09:52:01 +00:00
|
|
|
}
|
|
|
|
|
2021-02-14 02:36:00 +00:00
|
|
|
/**
|
|
|
|
* Get a Dexie database with a name and versions applied
|
|
|
|
* @param {DexieOptions} options
|
|
|
|
* @param {string=} name
|
|
|
|
* @param {number=} versionNumber
|
2021-05-01 02:54:00 +00:00
|
|
|
* @param {boolean=} populateData
|
2021-02-14 02:36:00 +00:00
|
|
|
* @returns {Dexie}
|
|
|
|
*/
|
|
|
|
export function getDatabase(
|
|
|
|
options,
|
|
|
|
name = "OwlbearRodeoDB",
|
2021-05-01 02:54:00 +00:00
|
|
|
versionNumber = latestVersion,
|
|
|
|
populateData = true
|
2021-02-14 02:36:00 +00:00
|
|
|
) {
|
2021-02-13 10:51:31 +00:00
|
|
|
let db = new Dexie(name, options);
|
2021-02-14 02:36:00 +00:00
|
|
|
loadVersions(db, versionNumber);
|
2021-05-01 02:54:00 +00:00
|
|
|
if (populateData) {
|
|
|
|
populate(db);
|
|
|
|
}
|
2020-05-03 09:52:01 +00:00
|
|
|
return db;
|
|
|
|
}
|