From 17c82861f682dd3d854f5fd7faa3b13e9d994e1a Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Sun, 3 May 2020 19:52:01 +1000 Subject: [PATCH] Added database upgrade for blob map files and refactored back to database file --- src/contexts/DatabaseContext.js | 18 ++++------------- src/database.js | 34 +++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 14 deletions(-) create mode 100644 src/database.js diff --git a/src/contexts/DatabaseContext.js b/src/contexts/DatabaseContext.js index 7bbac74..7492682 100644 --- a/src/contexts/DatabaseContext.js +++ b/src/contexts/DatabaseContext.js @@ -1,5 +1,6 @@ import React, { useState, useEffect } from "react"; -import Dexie from "dexie"; + +import { getDatabase } from "../database"; const DatabaseContext = React.createContext(); @@ -7,22 +8,12 @@ export function DatabaseProvider({ children }) { const [database, setDatabase] = useState(); const [databaseStatus, setDatabaseStatus] = useState("loading"); - function loadVersions(db) { - db.version(1).stores({ - maps: "id, owner", - states: "mapId", - tokens: "id, owner", - user: "key", - }); - } - useEffect(() => { // Create a test database and open it to see if indexedDB is enabled let testDBRequest = window.indexedDB.open("__test"); testDBRequest.onsuccess = function () { testDBRequest.result.close(); - let db = new Dexie("OwlbearRodeoDB"); - loadVersions(db); + let db = getDatabase(); setDatabase(db); setDatabaseStatus("loaded"); window.indexedDB.deleteDatabase("__test"); @@ -32,8 +23,7 @@ export function DatabaseProvider({ children }) { console.warn("Database is disabled, no state will be saved"); const indexedDB = await import("fake-indexeddb"); const IDBKeyRange = await import("fake-indexeddb/lib/FDBKeyRange"); - let db = new Dexie("OwlbearRodeoDB", { indexedDB, IDBKeyRange }); - loadVersions(db); + let db = getDatabase({ indexedDB, IDBKeyRange }); setDatabase(db); setDatabaseStatus("disabled"); window.indexedDB.deleteDatabase("__test"); diff --git a/src/database.js b/src/database.js new file mode 100644 index 0000000..b3f1f08 --- /dev/null +++ b/src/database.js @@ -0,0 +1,34 @@ +import Dexie from "dexie"; + +import blobToBuffer from "./helpers/blobToBuffer"; + +function loadVersions(db) { + db.version(1).stores({ + maps: "id, owner", + states: "mapId", + tokens: "id, owner", + user: "key", + }); + // Upgrade move from blob files to array buffers + db.version(2) + .stores({}) + .upgrade((tx) => { + return tx + .table("maps") + .toCollection() + .modify((map) => { + if (map.file instanceof Blob) { + blobToBuffer(map.file).then((buffer) => { + map.file = buffer; + }); + } + }); + }); +} + +// Get the dexie database used in DatabaseContext +export function getDatabase(options) { + let db = new Dexie("OwlbearRodeoDB", options); + loadVersions(db); + return db; +}