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 |
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() {
const res = await client.api.me.get();
if (res.status !== 200 || !res.data) return;
isAuthenticated.value = true;
isAuthenticating.value = false;
user.value = res.data.user;
const resActors = res.data.actors;
actors.value = resActors.reduce(
(acc, actor) => {
acc[actor.guild!.discordId!] = actor;
return acc;
},
{} as Record<string, SanitisedActorWithGuild>,
);
guild.value = res.data.actors[0]?.guild;
}
async function waitForAuth() {
while (isAuthenticating.value) {
await getUser();
}
}
return {
isAuthenticated,
isAuthenticating,
waitForAuth,
user,
actors,
getUser,
};
});
|