Commit | Line | Data |
---|---|---|
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 | ||
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"]); | |
934f7f70 | 19 | callback("error", null); |
98b94cc3 BA |
20 | }; |
21 | ||
22 | DBOpenRequest.onsuccess = function(event) { | |
23 | db = DBOpenRequest.result; | |
934f7f70 | 24 | callback(null, db); |
98b94cc3 BA |
25 | db.close(); |
26 | }; | |
27 | ||
28 | DBOpenRequest.onupgradeneeded = function(event) { | |
29 | let db = event.target.result; | |
934f7f70 | 30 | db.createObjectStore("compgames", { keyPath: "vname" }); |
98b94cc3 BA |
31 | }; |
32 | } | |
33 | ||
34 | export const CompgameStorage = { | |
35 | add: function(game) { | |
36 | dbOperation((err,db) => { | |
934f7f70 BA |
37 | if (err) return; |
38 | let objectStore = db | |
39 | .transaction("compgames", "readwrite") | |
40 | .objectStore("compgames"); | |
98b94cc3 BA |
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) => { | |
934f7f70 BA |
69 | let objectStore = db |
70 | .transaction("compgames", "readonly") | |
71 | .objectStore("compgames"); | |
98b94cc3 BA |
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) { | |
934f7f70 BA |
82 | db.transaction("compgames", "readwrite") |
83 | .objectStore("compgames") | |
84 | .delete(gameId); | |
98b94cc3 BA |
85 | } |
86 | }); | |
87 | } | |
88 | }; |