PerudoClient/src/services/PerudoApi.ts
2021-07-05 04:37:28 +02:00

53 lines
1.8 KiB
TypeScript

import axios, {AxiosPromise, AxiosRequestConfig, AxiosResponse} from 'axios'
import {JoinCreateGameObject, IsStartedObject, ApiObject} from "@/objects/objects";
export default class PerudoApi {
private static baseUrl = 'http://localhost:8000/'
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>(PerudoApi.baseUrl + 'game/create?name=' + name)
.then((response: AxiosResponse<JoinCreateGameObject>) => {
return response.data;
})
}
public joinGame(name: string, code: string): Promise<JoinCreateGameObject> {
return this.get<JoinCreateGameObject>(PerudoApi.baseUrl + 'game/join/' + code + '?name=' + name)
.then((response: AxiosResponse<JoinCreateGameObject>) => {
return response.data;
})
}
public startedGame(playerId: string): Promise<IsStartedObject> {
return this.get<IsStartedObject>(PerudoApi.baseUrl + 'game/started/' + playerId)
.then((response: AxiosResponse<IsStartedObject>) => {
return response.data;
})
}
public startGame(playerId: string): Promise<ApiObject> {
return this.get<ApiObject>(PerudoApi.baseUrl + 'game/start/' + playerId)
.then((response: AxiosResponse<ApiObject>) => {
return response.data;
});
}
private get<T extends ApiObject>(url: string, getParameters?: Record<string, any>): AxiosPromise<T> {
return axios.get(url).then((response: AxiosResponse<T>) => {
if (response?.data?.errors?.length > 0) {
throw response.data.errors?.join();
}
return response;
})
}
}