1
1
import _ from 'lodash' ;
2
- import Constants from 'src/commons/utils/Constants ' ;
2
+ import { Cadet } from 'src/commons/api ' ;
3
3
4
4
import SourceAcademyGame from '../SourceAcademyGame' ;
5
5
import { createEmptySaveState } from './GameSaveHelper' ;
@@ -11,22 +11,14 @@ import { FullSaveState } from './GameSaveTypes';
11
11
* @param fullSaveState - the entire game data that needs to be saved, including game state and userstate
12
12
*/
13
13
export async function saveData ( fullSaveState : FullSaveState ) {
14
- if ( SourceAcademyGame . getInstance ( ) . getAccountInfo ( ) . role !== 'student' ) {
14
+ const { role, accessToken, refreshToken } = SourceAcademyGame . getInstance ( ) . getAccountInfo ( ) ;
15
+ if ( role !== 'student' ) {
15
16
return ;
16
17
}
17
18
18
- // TODO: use Cadet
19
- const options = {
20
- method : 'PUT' ,
21
- headers : createHeaders ( SourceAcademyGame . getInstance ( ) . getAccountInfo ( ) . accessToken ) ,
22
- body : JSON . stringify ( {
23
- gameStates : fullSaveState
24
- } )
25
- } ;
19
+ const resp = await Cadet . user . updateGameStates ( fullSaveState , { accessToken, refreshToken } ) ;
26
20
27
- const resp = await fetch ( `${ Constants . backendUrl } /v2/user/game_states` , options ) ;
28
-
29
- if ( resp && resp . ok ) {
21
+ if ( resp . ok ) {
30
22
return resp ;
31
23
}
32
24
return ;
@@ -36,27 +28,11 @@ export async function saveData(fullSaveState: FullSaveState) {
36
28
* This function fetches data from the backend.
37
29
*/
38
30
export async function loadData ( ) : Promise < FullSaveState > {
39
- const options = {
40
- method : 'GET' ,
41
- headers : createHeaders ( SourceAcademyGame . getInstance ( ) . getAccountInfo ( ) . accessToken )
42
- } ;
43
-
44
- const resp = await fetch ( `${ Constants . backendUrl } /v2/user/` , options ) ;
45
- const message = await resp . text ( ) ;
31
+ const { accessToken, refreshToken } = SourceAcademyGame . getInstance ( ) . getAccountInfo ( ) ;
46
32
47
- const json = JSON . parse ( message ) . gameStates ;
48
- return _ . isEmpty ( json ) ? createEmptySaveState ( ) : json ;
49
- }
33
+ const resp = await Cadet . user . index ( { accessToken, refreshToken } ) ;
34
+ const gameStates = resp . data . game_states ;
50
35
51
- /**
52
- * Format a header object.
53
- *
54
- * @param accessToken access token to be used
55
- */
56
- function createHeaders ( accessToken : string ) : Headers {
57
- const headers = new Headers ( ) ;
58
- headers . append ( 'Accept' , 'application/json' ) ;
59
- headers . append ( 'Authorization' , `Bearer ${ accessToken } ` ) ;
60
- headers . append ( 'Content-Type' , 'application/json' ) ;
61
- return headers ;
36
+ // TODO: add FullSaveState to backend Swagger API?
37
+ return _ . isEmpty ( gameStates ) ? createEmptySaveState ( ) : ( gameStates as FullSaveState ) ;
62
38
}
0 commit comments