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";
|
2020-05-03 09:52:01 +00:00
|
|
|
|
2021-07-16 04:55:33 +00:00
|
|
|
import { loadVersions, UpgradeEventHandler } from "./upgrade";
|
2021-05-01 02:54:00 +00:00
|
|
|
import { getDefaultMaps } from "./maps";
|
|
|
|
import { getDefaultTokens } from "./tokens";
|
2021-07-17 23:13:10 +00:00
|
|
|
import { getRandomMonster } from "./helpers/monsters";
|
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-07-16 04:55:33 +00:00
|
|
|
function populate(db: Dexie) {
|
2021-05-01 02:54:00 +00:00
|
|
|
db.on("populate", () => {
|
|
|
|
const userId = uuid();
|
|
|
|
db.table("user").add({ key: "userId", value: userId });
|
2021-07-17 23:13:10 +00:00
|
|
|
const nickname = getRandomMonster();
|
|
|
|
db.table("user").add({ key: "nickname", value: nickname });
|
2021-05-01 02:54:00 +00:00
|
|
|
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([
|
2021-05-14 08:02:50 +00:00
|
|
|
{ id: "maps", items: maps.map((map) => ({ id: map.id, type: "item" })) },
|
|
|
|
{
|
|
|
|
id: "tokens",
|
|
|
|
items: tokens.map((token) => ({ id: token.id, type: "item" })),
|
|
|
|
},
|
2021-05-13 06:27:21 +00:00
|
|
|
]);
|
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-07-16 04:55:33 +00:00
|
|
|
* @param {UpgradeEventHandler=} onUpgrade
|
2021-02-14 02:36:00 +00:00
|
|
|
* @returns {Dexie}
|
|
|
|
*/
|
|
|
|
export function getDatabase(
|
2021-05-25 07:35:26 +00:00
|
|
|
options: DexieOptions,
|
2021-07-16 04:55:33 +00:00
|
|
|
name: string | undefined = "OwlbearRodeoDB",
|
|
|
|
versionNumber: number | undefined = undefined,
|
|
|
|
populateData: boolean | undefined = true,
|
|
|
|
onUpgrade: UpgradeEventHandler | undefined = undefined
|
|
|
|
): Dexie {
|
2021-02-13 10:51:31 +00:00
|
|
|
let db = new Dexie(name, options);
|
2021-06-24 06:14:20 +00:00
|
|
|
loadVersions(db, versionNumber, onUpgrade);
|
2021-05-01 02:54:00 +00:00
|
|
|
if (populateData) {
|
|
|
|
populate(db);
|
|
|
|
}
|
2020-05-03 09:52:01 +00:00
|
|
|
return db;
|
|
|
|
}
|