Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { GameState, isValidGameState } from "./types";
export class GameStateServerClient {
_apiBaseUrl: string;
constructor(apiBaseUrl: string) {
this._apiBaseUrl = apiBaseUrl;
}
async saveState(id: string, gameState: GameState): Promise<boolean> {
try {
await fetch(this._apiBaseUrl + "/game/state/" + id, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "omit",
headers: {
"Content-Type": "application/json",
},
referrerPolicy: "no-referrer",
body: JSON.stringify(gameState),
});
return true;
} catch (saveStateToServerError) {
console.error(
"Failed to save state to server. The following info may help to solve this problem:",
saveStateToServerError
);
return false;
}
}
async loadState(id: string): Promise<GameState> {
try {
const rawResponse = await fetch(this._apiBaseUrl + "/game/state/" + id, {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "omit",
referrerPolicy: "no-referrer",
});
const decodedResponse = await rawResponse.json();
if (!isValidGameState(decodedResponse)) {
throw new TypeError("State from server is not a valid gameState");
}
return decodedResponse;
} catch (loadGameStateFromServerError) {}
}
}