all repos — stealth-developers @ f8ee1bb02ee0c98c52a0ac3c5fbd70b6b7e27eaa

apps/web/src/stores/api.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
import type { App, SanitisedActorWithGuild, SanitisedUser } from "@stealth-developers/api";

import { treaty } from "@elysia/eden";
import { defineStore } from "pinia";
import { ref } from "vue";

export const client = treaty<App>(window.location.host);

export const useApiStore = defineStore("api", () => {
	const isAuthenticated = ref(false);
	const isAuthenticating = ref(true);

	const user = ref<SanitisedUser | null>(null);
	const actors = ref<Record<string, SanitisedActorWithGuild>>({});
	const guild = ref<unknown | null>(null);

	async function getUser() {
		try {
			const res = await client.api.me.get();

			if (res.status === 200 && res.data) {
				isAuthenticated.value = true;
				user.value = res.data.user;

				const resActors = res.data.actors;
				actors.value = resActors.reduce(
					(acc, actor) => {
						if (actor.guild?.discordId) {
							acc[actor.guild.discordId] = actor;
						}
						return acc;
					},
					{} as Record<string, SanitisedActorWithGuild>,
				);

				guild.value = res.data.actors[0]?.guild;
			}
		} catch (error) {
			console.error(error);
		} finally {
			isAuthenticating.value = false;
		}
	}

	async function waitForAuth() {
		while (isAuthenticating.value) {
			await getUser();
		}
	}

	return {
		isAuthenticated,
		isAuthenticating,
		waitForAuth,

		user,
		actors,
		getUser,
	};
});