Lib: Update pocketbase auth handling
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
import Pocketbase, { type AuthRecord, type RecordModel, type RecordSubscription } from "pocketbase";
|
||||
import Pocketbase, { type RecordModel, type RecordSubscription } from "pocketbase";
|
||||
import type { Graphic, User } from "$lib/schema";
|
||||
import { env } from "$env/dynamic/public";
|
||||
import { invalidate } from "$app/navigation";
|
||||
@ -6,13 +6,7 @@ import { invalidate } from "$app/navigation";
|
||||
export let pb = new Pocketbase(env.PUBLIC_PBURL || "http://192.168.86.50:8090");
|
||||
export let pbUser: User | undefined = undefined;
|
||||
|
||||
const update_user = async (record: AuthRecord): Promise<void> => {
|
||||
if (!record) {
|
||||
pbUser = undefined;
|
||||
console.log("Returning with pbUser = undefined");
|
||||
return;
|
||||
}
|
||||
|
||||
const update_user = async (record: RecordModel): Promise<void> => {
|
||||
let avatar_url: string;
|
||||
if (record.avatar) {
|
||||
avatar_url = pb.files.getURL(record, record.avatar);
|
||||
@ -27,6 +21,7 @@ const update_user = async (record: AuthRecord): Promise<void> => {
|
||||
id: record.id,
|
||||
username: record.username,
|
||||
firstname: record.firstname,
|
||||
email: record.email ?? "",
|
||||
avatar: record.avatar,
|
||||
avatar_url: avatar_url,
|
||||
admin: record.admin,
|
||||
@ -35,6 +30,17 @@ const update_user = async (record: AuthRecord): Promise<void> => {
|
||||
|
||||
// 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;
|
||||
return;
|
||||
}
|
||||
if (!pb.authStore.record) {
|
||||
console.log("pb.authStore.record is null: Setting pbUser to undefined");
|
||||
pbUser = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
await update_user(pb.authStore.record);
|
||||
|
||||
// TODO: If the user has not chosen an avatar,
|
||||
@ -43,6 +49,9 @@ pb.authStore.onChange(async () => {
|
||||
console.dir(pbUser, { depth: null });
|
||||
}, true);
|
||||
|
||||
/**
|
||||
* Subscribe to PocketBase realtime collections
|
||||
*/
|
||||
export const subscribe = (collections: string[]) => {
|
||||
collections.forEach((collection: string) => {
|
||||
pb.collection(collection).subscribe("*", (event: RecordSubscription<RecordModel>) => {
|
||||
@ -51,6 +60,9 @@ export const subscribe = (collections: string[]) => {
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Unsubscribe from PocketBase realtime collections
|
||||
*/
|
||||
export const unsubscribe = (collections: string[]) => {
|
||||
collections.forEach((collection: string) => {
|
||||
pb.collection(collection).unsubscribe("*");
|
||||
|
Reference in New Issue
Block a user