WFDASH-WEBAPP/src/lib/pocketbase.ts

54 lines
1.6 KiB
TypeScript
Raw Normal View History

import PocketBase from "pocketbase";
const POCKETBASE_URL = process.env.NEXT_PUBLIC_POCKETBASE_URL || "http://127.0.0.1:8090";
let pb: PocketBase | null = null;
export function getPocketBase(): PocketBase {
if (typeof window === "undefined") {
// Server-side: create new instance each time
return new PocketBase(POCKETBASE_URL);
}
// Client-side: reuse singleton
if (!pb) {
pb = new PocketBase(POCKETBASE_URL);
pb.autoCancellation(false);
// Load auth from localStorage
const storedAuth = localStorage.getItem("pocketbase_auth");
if (storedAuth) {
try {
const authData = JSON.parse(storedAuth);
pb.authStore.save(authData.token, authData.record);
} catch {
localStorage.removeItem("pocketbase_auth");
}
}
// Persist auth changes to localStorage. The tests don't always
// provide a full `authStore.onChange`, so wrap defensively rather
// than throw at module-load time.
try {
if (pb && pb.authStore && typeof pb.authStore.onChange === "function") {
pb.authStore.onChange(() => {
if (pb && pb.authStore && pb.authStore.isValid) {
localStorage.setItem("pocketbase_auth", JSON.stringify({
token: pb.authStore.token,
record: pb.authStore.record,
}));
} else {
localStorage.removeItem("pocketbase_auth");
}
});
}
} catch {
// Best-effort persistence only; never block startup.
}
}
return pb;
}
export { PocketBase };
export default getPocketBase;