PerudoClient/src/services/PerudoApi.ts
2021-12-02 02:43:32 +01:00

100 lines
3.1 KiB
TypeScript

import axios, {AxiosPromise, AxiosResponse} from 'axios'
import {
JoinCreateGameObject,
IsStartedObject,
ApiObject,
GameStateObject,
MyTurnObject,
GuessAction,
GameRules
} from "@/objects/objects";
export default class PerudoApi {
private static baseUrl = process.env.VUE_APP_BASE_URL;
private static objectInstance?: PerudoApi;
public static get instance(): PerudoApi {
if (typeof PerudoApi.objectInstance === 'undefined') {
PerudoApi.objectInstance = new PerudoApi();
}
return PerudoApi.objectInstance;
}
public createGame(name: string): Promise<JoinCreateGameObject> {
return this.get<JoinCreateGameObject>('game/create?name=' + name)
.then((response: AxiosResponse<JoinCreateGameObject>) => {
return response.data;
})
}
public joinGame(name: string, code: string): Promise<JoinCreateGameObject> {
return this.get<JoinCreateGameObject>('game/join/' + code + '?name=' + name)
.then((response: AxiosResponse<JoinCreateGameObject>) => {
return response.data;
})
}
public setGameRules(playerId: string, rules: GameRules): Promise<ApiObject> {
return this.post<ApiObject>('game/rules/' + playerId, rules)
.then((response: AxiosResponse<ApiObject>) => {
return response.data;
});
}
public gameStarted(playerId: string): Promise<IsStartedObject> {
return this.get<IsStartedObject>('game/started/' + playerId)
.then((response: AxiosResponse<IsStartedObject>) => {
return response.data;
})
}
public startGame(playerId: string): Promise<ApiObject> {
return this.get<ApiObject>('game/start/' + playerId)
.then((response: AxiosResponse<ApiObject>) => {
return response.data;
});
}
public myTurn(playerId: string): Promise<MyTurnObject> {
return this.get<MyTurnObject>('player/turn/' + playerId)
.then((response: AxiosResponse<MyTurnObject>) => {
return response.data;
})
}
public makeGuess(playerId: string, guess: GuessAction): Promise<MyTurnObject> {
return this.post<MyTurnObject>('player/guess/' + playerId, guess)
.then((response: AxiosResponse<MyTurnObject>) => {
return response.data;
});
}
public callBluff(playerId: string): Promise<MyTurnObject> {
return this.post<MyTurnObject>('player/call/' + playerId)
.then((response: AxiosResponse<MyTurnObject>) => {
return response.data;
});
}
private get<T extends ApiObject>(url: string, getParameters?: Record<string, any>): AxiosPromise<T> {
return axios.get(PerudoApi.baseUrl + url).then((response: AxiosResponse<T>) => {
// @ts-ignore
if (response?.data?.errors?.length > 0) {
throw response.data.errors?.join();
}
return response;
})
}
private post<T extends ApiObject>(url: string, data?: any,): AxiosPromise<T> {
return axios.post(PerudoApi.baseUrl + url, data).then((response: AxiosResponse) => {
// @ts-ignore
if (response?.data?.errors?.length > 0) {
throw response.data.errors?.join();
}
return response;
});
}
}