budgeteer/web/src/stores/session.ts
2022-03-15 12:52:23 +00:00

75 lines
2.0 KiB
TypeScript

import { StorageSerializers, useStorage } from "@vueuse/core";
import { defineStore } from "pinia";
import { POST } from "../api";
interface State {
Session: Session | null;
Budgets: Map<string, Budget>;
}
interface Session {
Token: string;
User: string;
}
export interface Budget {
ID: string;
Name: string;
AvailableBalance: number;
IncomeCategoryID: string;
}
export const useSessionStore = defineStore("session", {
state: () => ({
Session: useStorage<Session | null>("session", null, undefined, {
serializer: StorageSerializers.object,
}),
Budgets: useStorage<Map<string, Budget>>(
"budgets",
new Map<string, Budget>(),
undefined,
{ serializer: StorageSerializers.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,
};
for (const budget of x.Budgets) {
this.Budgets.set(budget.ID, budget);
}
},
async login(login: any) {
const response = await POST("/user/login", JSON.stringify(login));
const result = await response.json();
this.loginSuccess(result);
return result;
},
async register(login: any) {
const response = await POST(
"/user/register",
JSON.stringify(login)
);
const result = await response.json();
this.loginSuccess(result);
return result;
},
logout() {
this.Session = null;
this.Budgets.clear();
},
},
});