servicepoint-tanks/tank-frontend/src/serverCalls.tsx

52 lines
1.3 KiB
TypeScript
Raw Normal View History

import {Guid} from './Guid.ts';
2024-04-21 14:34:45 +02:00
export function makeApiUrl(path: string, protocol: 'http' | 'ws' = 'http') {
return new URL(`${protocol}://${window.location.hostname}${path}`);
}
export type ServerResponse<T> = {
ok: boolean;
statusCode: number;
statusText: string;
additionalErrorText?: string;
successResult?: T;
}
export type Player = {
2024-04-13 17:56:33 +02:00
readonly name: string;
2024-04-13 23:07:08 +02:00
readonly id: Guid;
readonly scores: {
readonly kills: number;
readonly deaths: number;
2024-04-19 13:34:56 +02:00
readonly wallsDestroyed: number;
};
};
export type NameId = {
name: string,
id: Guid
2024-04-13 17:56:33 +02:00
};
export async function fetchTyped<T>({url, method}: { url: URL; method: string; }): Promise<ServerResponse<T>> {
const response = await fetch(url, {method});
const result: ServerResponse<T> = {
ok: response.ok,
statusCode: response.status,
statusText: response.statusText
2024-04-21 14:34:45 +02:00
};
if (response.ok)
result.successResult = await response.json();
else
result.additionalErrorText = await response.text();
return result;
2024-04-13 17:56:33 +02:00
}
export function postPlayer({name, id}: NameId) {
2024-04-21 14:34:45 +02:00
const url = makeApiUrl('/player');
2024-04-13 17:56:33 +02:00
url.searchParams.set('name', name);
url.searchParams.set('id', id);
return fetchTyped<NameId>({url, method: 'POST'});
2024-04-13 17:56:33 +02:00
}