67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import type { Game, User } from "./interfaces";
|
|
|
|
export function subscribe(endpoint: string) {
|
|
const config = useRuntimeConfig();
|
|
const evtSource = new EventSource(new URL(endpoint, config.public.endpoint), {
|
|
withCredentials: true,
|
|
});
|
|
|
|
return evtSource;
|
|
}
|
|
|
|
export async function getLobby() {
|
|
const config = useRuntimeConfig();
|
|
const req = await useFetch<Array<Game>>(
|
|
new URL("/games", config.public.endpoint).href,
|
|
{
|
|
credentials: "include",
|
|
}
|
|
);
|
|
if (req.data.value == null) {
|
|
throw new Error("Lobby answer is empty");
|
|
}
|
|
return req.data as Ref<Game[]>;
|
|
}
|
|
|
|
export async function whoami() {
|
|
const config = useRuntimeConfig();
|
|
const { data, pending, error, refresh } = await useFetch<User>(
|
|
new URL("/whoami", config.public.endpoint).href,
|
|
{
|
|
credentials: "include",
|
|
}
|
|
);
|
|
if (error.value?.statusCode && [401].includes(error.value.statusCode)) {
|
|
// await navigateTo(config.public.discordLoginEndpoint, {
|
|
// external: true,
|
|
// });
|
|
throw new Error("You are not logged in");
|
|
}
|
|
if (error.value) {
|
|
throw new Error(
|
|
"Something went wrong while trying to get user information"
|
|
);
|
|
}
|
|
|
|
return data;
|
|
}
|
|
|
|
export async function createGame() {
|
|
const config = useRuntimeConfig();
|
|
await $fetch<User>(new URL("/games", config.public.endpoint).href, {
|
|
method: "POST",
|
|
credentials: "include",
|
|
});
|
|
}
|
|
|
|
export async function endTurn(game: string) {
|
|
const config = useRuntimeConfig();
|
|
await $fetch<User>(
|
|
new URL(`games/${game}/endTurn`, config.public.endpoint).href,
|
|
{
|
|
method: "POST",
|
|
credentials: "include",
|
|
}
|
|
);
|
|
}
|