Add unambiguous section in the PGN + some fixes + code formatting and fix typos
[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 = {
40 add: function(game) {
41 dbOperation((err,db) => {
934f7f70
BA
42 if (err) return;
43 let objectStore = db
44 .transaction("compgames", "readwrite")
45 .objectStore("compgames");
98b94cc3
BA
46 objectStore.add(game);
47 });
48 },
49
50 // obj: move and/or fen
51 update: function(gameId, obj) {
52 dbOperation((err,db) => {
53 let objectStore = db
54 .transaction("compgames", "readwrite")
55 .objectStore("compgames");
56 objectStore.get(gameId).onsuccess = function(event) {
57 // Ignoring error silently: shouldn't happen now. TODO?
58 if (event.target.result) {
59 const game = event.target.result;
60 Object.keys(obj).forEach(k => {
61 if (k == "move") game.moves.push(obj[k]);
62 else game[k] = obj[k];
63 });
64 objectStore.put(game); //save updated data
65 }
66 };
67 });
68 },
69
70 // Retrieve any game from its identifier (variant name)
71 // NOTE: need callback because result is obtained asynchronously
72 get: function(gameId, callback) {
73 dbOperation((err,db) => {
934f7f70
BA
74 let objectStore = db
75 .transaction("compgames", "readonly")
76 .objectStore("compgames");
98b94cc3
BA
77 objectStore.get(gameId).onsuccess = function(event) {
78 callback(event.target.result);
79 };
80 });
81 },
82
83 // Delete a game in indexedDB
84 remove: function(gameId) {
85 dbOperation((err,db) => {
86 if (!err) {
934f7f70
BA
87 db.transaction("compgames", "readwrite")
88 .objectStore("compgames")
89 .delete(gameId);
98b94cc3
BA
90 }
91 });
92 }
93};