import { StorageSerializers, useStorage } from '@vueuse/core'; import { defineStore } from 'pinia' import { useAPI } from './api'; interface State { Session: Session | null Budgets: Map, } interface Session { Token: string User: string } export interface Budget { ID: string Name: string AvailableBalance: number } export const useSessionStore = defineStore('session', { state: () => ({ Session: useStorage('session', null, undefined, { serializer: StorageSerializers.object }), Budgets: useStorage>('budgets', new Map()), }), getters: { BudgetsList: (state) => [ ...state.Budgets.values() ], AuthHeaders: (state) => ({'Authorization': 'Bearer ' + state.Session.Token}), LoggedIn: (state) => state.Session != null, }, actions: { setTitle(title : string) { document.title = "Budgeteer - " + title; }, loginSuccess(x : any) { this.Session = { User: x.User, Token: x.Token, }, this.Budgets = x.Budgets; }, async login(login: any) { const api = useAPI(); const response = await api.POST("/user/login", JSON.stringify(login)); const result = await response.json(); return this.loginSuccess(result); }, async register(login : any) { const api = useAPI(); const response = await api.POST("/user/register", JSON.stringify(login)); const result = await response.json(); return this.loginSuccess(result); }, logout() { this.$reset() }, } })