Store state of games VS computer
[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) {
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 let objectStore = db.createObjectStore("compgames", { keyPath: "vname" });
31 };
32}
33
34export const CompgameStorage = {
35 add: function(game) {
36 dbOperation((err,db) => {
37 if (err)
38 return;
39 let transaction = db.transaction("compgames", "readwrite");
40 let objectStore = transaction.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.transaction("compgames").objectStore("compgames");
70 objectStore.get(gameId).onsuccess = function(event) {
71 callback(event.target.result);
72 };
73 });
74 },
75
76 // Delete a game in indexedDB
77 remove: function(gameId) {
78 dbOperation((err,db) => {
79 if (!err) {
80 let transaction = db.transaction(["compgames"], "readwrite");
81 transaction.objectStore("compgames").delete(gameId);
82 }
83 });
84 }
85};