More intuitive variants-by-name page
[vchess.git] / client / src / utils / compgameStorage.js
CommitLineData
98b94cc3
BA
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
11import { store } from "@/store";
12
13function dbOperation(callback) {
14 let db = null;
15 let DBOpenRequest = window.indexedDB.open("vchess_comp", 4);
16
17 DBOpenRequest.onerror = function(event) {
2c5d7b20
BA
18 alert(store.state.tr[
19 "Database error: stop private browsing, or update your browser"]);
934f7f70 20 callback("error", null);
98b94cc3
BA
21 };
22
23 DBOpenRequest.onsuccess = function(event) {
24 db = DBOpenRequest.result;
934f7f70 25 callback(null, db);
98b94cc3
BA
26 db.close();
27 };
28
29 DBOpenRequest.onupgradeneeded = function(event) {
30 let db = event.target.result;
bee36510
BA
31 let upgradeTransaction = event.target.transaction;
32 if (!db.objectStoreNames.contains("compgames"))
33 db.createObjectStore("compgames", { keyPath: "vname" });
34 else
35 upgradeTransaction.objectStore("compgames");
98b94cc3
BA
36 };
37}
38
39export const CompgameStorage = {
937c24ab 40
98b94cc3 41 add: function(game) {
5f918a27 42 dbOperation((err, db) => {
934f7f70
BA
43 if (err) return;
44 let objectStore = db
45 .transaction("compgames", "readwrite")
46 .objectStore("compgames");
98b94cc3
BA
47 objectStore.add(game);
48 });
49 },
50
51 // obj: move and/or fen
52 update: function(gameId, obj) {
5f918a27 53 dbOperation((err, db) => {
98b94cc3
BA
54 let objectStore = db
55 .transaction("compgames", "readwrite")
56 .objectStore("compgames");
57 objectStore.get(gameId).onsuccess = function(event) {
58 // Ignoring error silently: shouldn't happen now. TODO?
cc25444a 59 if (!!event.target.result) {
98b94cc3
BA
60 const game = event.target.result;
61 Object.keys(obj).forEach(k => {
62 if (k == "move") game.moves.push(obj[k]);
63 else game[k] = obj[k];
64 });
65 objectStore.put(game); //save updated data
66 }
67 };
68 });
69 },
70
71 // Retrieve any game from its identifier (variant name)
72 // NOTE: need callback because result is obtained asynchronously
73 get: function(gameId, callback) {
5f918a27 74 dbOperation((err, db) => {
934f7f70
BA
75 let objectStore = db
76 .transaction("compgames", "readonly")
77 .objectStore("compgames");
98b94cc3
BA
78 objectStore.get(gameId).onsuccess = function(event) {
79 callback(event.target.result);
80 };
81 });
82 },
83
84 // Delete a game in indexedDB
85 remove: function(gameId) {
5f918a27 86 dbOperation((err, db) => {
98b94cc3 87 if (!err) {
934f7f70
BA
88 db.transaction("compgames", "readwrite")
89 .objectStore("compgames")
90 .delete(gameId);
98b94cc3
BA
91 }
92 });
93 }
937c24ab 94
98b94cc3 95};