1 // Game object struct: see gameStorgae.js
3 import { store
} from "@/store";
5 function dbOperation(callback
) {
7 let DBOpenRequest
= window
.indexedDB
.open("vchess_import", 4);
9 DBOpenRequest
.onerror = function(event
) {
11 "Database error: stop private browsing, or update your browser"]);
12 callback("error", null);
15 DBOpenRequest
.onsuccess = function() {
16 db
= DBOpenRequest
.result
;
21 DBOpenRequest
.onupgradeneeded = function(event
) {
22 let db
= event
.target
.result
;
23 let upgradeTransaction
= event
.target
.transaction
;
24 let objectStore
= undefined;
25 if (!db
.objectStoreNames
.contains("importgames"))
26 objectStore
= db
.createObjectStore("importgames", { keyPath: "id" });
28 objectStore
= upgradeTransaction
.objectStore("importgames");
29 if (!objectStore
.indexNames
.contains("created"))
30 // To search by date intervals. Two games could start at the same time
31 objectStore
.createIndex("created", "created", { unique: false });
35 export const ImportgameStorage
= {
37 // Optional callback to get error status
38 add: function(game
, callback
) {
39 dbOperation((err
, db
) => {
44 let transaction
= db
.transaction("importgames", "readwrite");
45 transaction
.oncomplete = function() {
49 transaction
.onerror = function(err
) {
50 // Duplicate key error (most likely)
51 callback(err
.target
.error
);
53 transaction
.objectStore("importgames").add(game
);
57 // Retrieve next imported games
58 getNext: function(upperDt
, callback
) {
59 dbOperation((err
, db
) => {
61 .transaction("importgames", "readonly")
62 .objectStore("importgames");
63 let index
= objectStore
.index("created");
64 const range
= IDBKeyRange
.upperBound(upperDt
);
66 index
.openCursor(range
).onsuccess = function(event
) {
67 let cursor
= event
.target
.result
;
69 // Most recent games first:
70 games
= games
.sort((g1
, g2
) => g2
.created
- g1
.created
);
71 // TODO: 20 games showed per request is arbitrary
72 callback(games
.slice(0, 20));
75 // If there is still another cursor to go, keep running this code
77 // Do not retrieve moves or clocks (unused in list mode)
78 g
.movesCount
= g
.moves
.length
;
89 // Retrieve any game from its identifier.
90 // NOTE: need callback because result is obtained asynchronously
91 get: function(gameId
, callback
) {
92 dbOperation((err
, db
) => {
94 db
.transaction("importgames").objectStore("importgames");
95 objectStore
.get(gameId
).onsuccess = function(event
) {
96 // event.target.result is null if game not found
97 callback(event
.target
.result
);
102 // Delete a game in indexedDB
103 remove: function(gameId
, callback
) {
104 dbOperation((err
, db
) => {
106 let transaction
= db
.transaction("importgames", "readwrite");
107 transaction
.oncomplete = function() {
108 callback(); //everything's fine
110 transaction
.objectStore("importgames").delete(gameId
);