1 import {Player} from '@prisma/client';
2 import axios from 'axios';
3 import { Events } from './events';
4 import { LoginOutputType, AccountCreateType, MoveOutputType } from 'src/routes';
5 import {actionLog} from './components';
7 type ApiResponse<T> = {
8 status: 'ok' | 'error',
13 processingTime: number
18 export class Api extends Events {
20 headers: Record<string, string>;
21 player: Player | null;
23 constructor(root: string) {
27 // we use the headers for auth data
33 async get<T>(endpoint: string, params: Record<string, string> = {}): Promise<ApiResponse<T>> {
34 const res = await axios({
42 if(res.data.status !== 'ok') {
43 throw new Error(res.data.payload.toString());
49 async post<T>(endpoint: string, data: any = {}): Promise<ApiResponse<T>> {
50 const res = await axios({
58 if(res.data.status !== 'ok') {
59 throw new Error(res.data.payload.toString());
65 async signup(username: string, password: string, confirmation: string): Promise<AccountCreateType> {
66 const res = await this.post<AccountCreateType>('/v1/accounts', {
69 confirmation: confirmation
75 async login(username: string, password: string): Promise<LoginOutputType> {
76 const res = await this.post<LoginOutputType>('/v1/accounts/auth', {
81 this.headers['x-auth-token'] = res.payload.token;
82 this.player = res.payload.player;
84 this.emit('player', this.player);
89 async move(): Promise<MoveOutputType> {
90 if(this.player === null) {
91 throw new Error('Not authenicated');
93 const res = await this.post<MoveOutputType>(`/v1/accounts/${this.player.id}/move`);
95 this.player = res.payload.player;
97 this.emit('player', this.player);
99 actionLog(res.payload.displayText, true);