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
= {
36 // Optional callback to get error status
37 add: function(game
, callback
) {
38 dbOperation((err
, db
) => {
43 let transaction
= db
.transaction("importgames", "readwrite");
44 transaction
.oncomplete = function() {
48 transaction
.onerror = function(err
) {
49 // Duplicate key error (most likely)
52 transaction
.objectStore("importgames").add(game
);
56 // Retrieve next imported games
57 getNext: function(upperDt
, callback
) {
58 dbOperation((err
, db
) => {
60 .transaction("importgames", "readonly")
61 .objectStore("importgames");
62 let index
= objectStore
.index("created");
63 const range
= IDBKeyRange
.upperBound(upperDt
);
65 index
.openCursor(range
).onsuccess = function(event
) {
66 let cursor
= event
.target
.result
;
68 // Most recent games first:
69 games
= games
.sort((g1
, g2
) => g2
.created
- g1
.created
);
70 // TODO: 20 games showed per request is arbitrary
71 callback(games
.slice(0, 20));
74 // If there is still another cursor to go, keep running this code
76 // Do not retrieve moves or clocks (unused in list mode)
77 g
.movesCount
= g
.moves
.length
;
88 // Retrieve any game from its identifier.
89 // NOTE: need callback because result is obtained asynchronously
90 get: function(gameId
, callback
) {
91 dbOperation((err
, db
) => {
93 db
.transaction("importgames").objectStore("importgames");
94 objectStore
.get(gameId
).onsuccess = function(event
) {
95 // event.target.result is null if game not found
96 callback(event
.target
.result
);
101 // Delete a game in indexedDB
102 remove: function(gameId
, callback
) {
103 dbOperation((err
, db
) => {
105 let transaction
= db
.transaction("importgames", "readwrite");
106 transaction
.oncomplete = function() {
107 callback(); //everything's fine
109 transaction
.objectStore("importgames").delete(gameId
);