WFDASH-WEBAPP/src/lib/pocketbase.ts
SJCoetz f9a0d08dab fix(tests): mock scaffold destructure + collection-pool + pocketbase startup
- orders-service.test.ts: destructure capture-group bug on regex match
  (was assigning m[0] to 'field', so filter clauses never matched).
  Two pre-seed tests were masked by the bug.
- quotes-service.test.ts: createQuoteFromEmail now returns 0
  attachments; the n8n flow uploads them in a follow-up step. Update
  the assertion that still expected the old embedded-base64 count.
- collection-pool/page.test.tsx: tests assume ONE supplier group with
  multiple rows; supply that shape and scope the selectors. Also wait
  for data load in the chevron test and gather list items across all
  <ul> elements in the sort control helper.
- pocketbase.ts: wrap authStore.onChange registration defensively so
  the test mock (no authStore) doesn't throw at startup.
- stock-orders/page.tsx: drop the re-export of
  STOCK_PURCHASE_STATUS_VALUES on the page module — Next.js page
  route files only allow the default export.
- collection-confirm/view-model.test.ts: buildConfirmNote input is
  Pick<InvoiceDetails, 'date' | 'number'>; drop the extra setBy fields.

Co-authored-by: Orca <help@stably.ai>
2026-07-31 00:01:24 +02:00

53 lines
1.6 KiB
TypeScript

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;