Use a pinia store to manage session state
Replace the convoluted useAccountSession composable with a pinia store that in addition allows for the consolidation of all session related functions to grouped into one module.
This commit is contained in:
parent
c47452a8b4
commit
fae8b4e2e4
21 changed files with 181 additions and 118 deletions
61
stores/session.ts
Normal file
61
stores/session.ts
Normal file
|
@ -0,0 +1,61 @@
|
|||
import { appendResponseHeader } from "h3";
|
||||
import type { H3Event } from "h3";
|
||||
import type { Account } from "~/shared/types/account";
|
||||
|
||||
const fetchSessionWithCookie = async (event?: H3Event) => {
|
||||
// Client side
|
||||
if (!event) {
|
||||
return $fetch("/api/auth/session");
|
||||
}
|
||||
|
||||
// Server side
|
||||
const cookie = useRequestHeader("cookie");
|
||||
const res = await $fetch.raw("/api/auth/session", {
|
||||
headers: cookie ? { cookie } : undefined
|
||||
});
|
||||
for (const cookie of res.headers.getSetCookie()) {
|
||||
appendResponseHeader(event, "set-cookie", cookie);
|
||||
}
|
||||
return res._data;
|
||||
}
|
||||
|
||||
export const useSessionStore = defineStore("session", () => {
|
||||
const state = {
|
||||
account: ref<Account>(),
|
||||
id: ref<number>(),
|
||||
push: ref<boolean>(false),
|
||||
};
|
||||
|
||||
const actions = {
|
||||
async fetch(event?: H3Event) {
|
||||
const session = await fetchSessionWithCookie(event)
|
||||
state.account.value = session?.account;
|
||||
state.id.value = session?.id;
|
||||
state.push.value = session?.push ?? false;
|
||||
},
|
||||
async logIn(name: string) {
|
||||
const res = await $fetch.raw("/api/auth/login", {
|
||||
method: "POST",
|
||||
body: { name },
|
||||
});
|
||||
await actions.fetch();
|
||||
return `/api/auth/login replied: ${res.status} ${res.statusText}`;
|
||||
},
|
||||
async logOut() {
|
||||
try {
|
||||
await $fetch.raw("/api/auth/session", {
|
||||
method: "DELETE",
|
||||
});
|
||||
await actions.fetch();
|
||||
|
||||
} catch (err: any) {
|
||||
alert(`Log out failed: ${err.statusCode} ${err.statusMessage}`);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
...state,
|
||||
...actions,
|
||||
};
|
||||
});
|
Loading…
Add table
Add a link
Reference in a new issue