Skeleton: Use writable store for pbUser object
This commit is contained in:
@ -2,9 +2,13 @@ import Pocketbase, { type RecordModel, type RecordSubscription } from "pocketbas
|
||||
import type { Graphic, User } from "$lib/schema";
|
||||
import { env } from "$env/dynamic/public";
|
||||
import { invalidate } from "$app/navigation";
|
||||
import { get, writable, type Writable } from "svelte/store";
|
||||
|
||||
export let pb = new Pocketbase(env.PUBLIC_PBURL || "http://192.168.86.50:8090");
|
||||
export let pbUser: User | undefined = undefined;
|
||||
|
||||
// Keep this in a writable store, because this is basically a $state.
|
||||
// We can't use $state in non-component files though.
|
||||
export let pbUser: Writable<User | undefined> = writable(undefined);
|
||||
|
||||
const update_user = async (record: RecordModel): Promise<void> => {
|
||||
let avatar_url: string;
|
||||
@ -17,7 +21,7 @@ const update_user = async (record: RecordModel): Promise<void> => {
|
||||
avatar_url = pb.files.getURL(driver_headshot_template, driver_headshot_template.file);
|
||||
}
|
||||
|
||||
pbUser = {
|
||||
pbUser.set({
|
||||
id: record.id,
|
||||
username: record.username,
|
||||
firstname: record.firstname,
|
||||
@ -25,19 +29,19 @@ const update_user = async (record: RecordModel): Promise<void> => {
|
||||
avatar: record.avatar,
|
||||
avatar_url: avatar_url,
|
||||
admin: record.admin,
|
||||
} as User;
|
||||
} as User);
|
||||
};
|
||||
|
||||
// Update the pbUser object when authStore changes (e.g. after logging in)
|
||||
pb.authStore.onChange(async () => {
|
||||
if (!pb.authStore.isValid) {
|
||||
console.log("pb.authStore is invalid: Setting pbUser to undefined");
|
||||
pbUser = undefined;
|
||||
pbUser.set(undefined);
|
||||
return;
|
||||
}
|
||||
if (!pb.authStore.record) {
|
||||
console.log("pb.authStore.record is null: Setting pbUser to undefined");
|
||||
pbUser = undefined;
|
||||
pbUser.set(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -46,9 +50,24 @@ pb.authStore.onChange(async () => {
|
||||
// TODO: If the user has not chosen an avatar,
|
||||
// the page keeps displaying the "Login" button (wtf)
|
||||
console.log("Updating pbUser...");
|
||||
console.dir(pbUser, { depth: null });
|
||||
console.dir(get(pbUser), { depth: null });
|
||||
}, true);
|
||||
|
||||
export const clear_auth = (): void => {
|
||||
console.log("Cleared pb.authStore");
|
||||
pb.authStore.clear();
|
||||
};
|
||||
|
||||
export const refresh_auth = async (): Promise<void> => {
|
||||
if (pb.authStore.isValid) {
|
||||
console.log("Refreshed pb.authStore");
|
||||
await pb.collection("users").authRefresh();
|
||||
} else {
|
||||
console.log("pb.autStore is invalid: Did not refresh pb.authStore");
|
||||
pb.authStore.clear();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Subscribe to PocketBase realtime collections
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user