loadMore button for my local games as well
[vchess.git] / client / src / utils / compgameStorage.js
1 // (Comp)Game object: {
2 // // Static informations:
3 // vname: string (this is the ID)
4 // fenStart: string,
5 // mycolor: "w" or "b"
6 // // Game (dynamic) state:
7 // fen: string,
8 // moves: array of Move objects,
9 // }
10
11 import { store } from "@/store";
12
13 function dbOperation(callback) {
14 let db = null;
15 let DBOpenRequest = window.indexedDB.open("vchess_comp", 4);
16
17 DBOpenRequest.onerror = function(event) {
18 alert(store.state.tr["Database error: stop private browsing, or update your browser"]);
19 callback("error", null);
20 };
21
22 DBOpenRequest.onsuccess = function(event) {
23 db = DBOpenRequest.result;
24 callback(null, db);
25 db.close();
26 };
27
28 DBOpenRequest.onupgradeneeded = function(event) {
29 let db = event.target.result;
30 db.createObjectStore("compgames", { keyPath: "vname" });
31 };
32 }
33
34 export const CompgameStorage = {
35 add: function(game) {
36 dbOperation((err,db) => {
37 if (err) return;
38 let objectStore = db
39 .transaction("compgames", "readwrite")
40 .objectStore("compgames");
41 objectStore.add(game);
42 });
43 },
44
45 // obj: move and/or fen
46 update: function(gameId, obj) {
47 dbOperation((err,db) => {
48 let objectStore = db
49 .transaction("compgames", "readwrite")
50 .objectStore("compgames");
51 objectStore.get(gameId).onsuccess = function(event) {
52 // Ignoring error silently: shouldn't happen now. TODO?
53 if (event.target.result) {
54 const game = event.target.result;
55 Object.keys(obj).forEach(k => {
56 if (k == "move") game.moves.push(obj[k]);
57 else game[k] = obj[k];
58 });
59 objectStore.put(game); //save updated data
60 }
61 };
62 });
63 },
64
65 // Retrieve any game from its identifier (variant name)
66 // NOTE: need callback because result is obtained asynchronously
67 get: function(gameId, callback) {
68 dbOperation((err,db) => {
69 let objectStore = db
70 .transaction("compgames", "readonly")
71 .objectStore("compgames");
72 objectStore.get(gameId).onsuccess = function(event) {
73 callback(event.target.result);
74 };
75 });
76 },
77
78 // Delete a game in indexedDB
79 remove: function(gameId) {
80 dbOperation((err,db) => {
81 if (!err) {
82 db.transaction("compgames", "readwrite")
83 .objectStore("compgames")
84 .delete(gameId);
85 }
86 });
87 }
88 };