Sets up global cache and uses it to fetch sessions

This commit is contained in:
2025-07-02 14:46:13 -07:00
parent f8130f0ba9
commit 32c5c40466
10 changed files with 310 additions and 28 deletions

View File

@@ -83,7 +83,7 @@ export function RelationshipList({
queryClient.invalidateQueries({
queryKey: ["relationship", relationshipType, root.id],
});
setItems((prev) => [...prev, doc]);
setItems((prev) => [doc, ...prev]);
} catch (e: any) {
setError(e?.message || "Failed to add document to relationship.");
} finally {
@@ -99,9 +99,7 @@ export function RelationshipList({
if (relationshipId) {
console.debug("Removing from existing relationship", relationshipId);
await pb.collection("relationships").update(relationshipId, {
secondary: items
.map((item) => item.id)
.filter((id) => id !== documentId),
"secondary-": documentId,
});
}
queryClient.invalidateQueries({

View File

@@ -1,15 +1,20 @@
import { AutoSaveTextarea } from "@/components/AutoSaveTextarea";
import { useCache } from "@/context/cache/CacheContext";
import { pb } from "@/lib/pocketbase";
import type { Session } from "@/lib/types";
export const SessionEditForm = ({ session }: { session: Session }) => {
const cache = useCache();
async function saveStrongStart(strongStart: string) {
await pb.collection("documents").update(session.id, {
data: {
...session.data,
strongStart,
},
});
const freshRecord: Session = await pb
.collection("documents")
.update(session.id, {
data: {
...session.data,
strongStart,
},
});
cache.set(freshRecord);
}
return (

74
src/context/cache/CacheContext.tsx vendored Normal file
View File

@@ -0,0 +1,74 @@
import { createContext, use, useContext, useMemo, useRef } from "react";
import type { ReactNode } from "react";
import { RecordCache } from "@/lib/recordCache";
import { pb } from "@/lib/pocketbase";
import { type DocumentId, type AnyDocument, CollectionIds } from "@/lib/types";
import { useQueryClient } from "@tanstack/react-query";
/**
* Context value for the record cache singleton.
*/
export type CacheContextValue = RecordCache;
const CacheContext = createContext<CacheContextValue | undefined>(undefined);
/**
* Provider for the record cache context. Provides a singleton RecordCache instance to children.
*/
export function CacheProvider({ children }: { children: ReactNode }) {
const cacheRef = useRef<RecordCache | undefined>(undefined);
if (!cacheRef.current) {
cacheRef.current = new RecordCache();
}
return (
<CacheContext.Provider value={cacheRef.current}>
{children}
</CacheContext.Provider>
);
}
/**
* Hook to access the record cache context. Throws if used outside of CacheProvider.
*/
export function useCache(): CacheContextValue {
const ctx = useContext(CacheContext);
if (!ctx) throw new Error("useCache must be used within a CacheProvider");
return ctx;
}
export function useDocument(documentId: DocumentId): AnyDocument {
const cache = useCache();
const queryClient = useQueryClient();
async function fetchItems() {
const cacheValue = cache.getDocument(documentId);
if (cacheValue) {
console.info(`Serving ${documentId} from cache.`);
return cacheValue;
}
const { doc } = await queryClient.fetchQuery({
queryKey: [CollectionIds.Documents, documentId],
queryFn: async () => {
const doc: AnyDocument = await pb
.collection("documents")
.getOne(documentId, {
expand:
"relationships_via_primary,relationships_via_primary.secondary",
});
console.info(`Saving ${documentId} to cache.`);
cache.set(doc);
return { doc };
},
});
return doc;
}
const items = useMemo(fetchItems, [documentId, cache, queryClient]);
return use(items);
}

81
src/lib/recordCache.ts Normal file
View File

@@ -0,0 +1,81 @@
import {
type CollectionId,
type AnyDocument,
CollectionIds,
type Relationship,
type DocumentId,
type RelationshipId,
} from "./types";
type CacheKey<C extends CollectionId = CollectionId> = `${C}:${string}`;
type DocumentKey = CacheKey<typeof CollectionIds.Documents>;
type RelationshipKey = CacheKey<typeof CollectionIds.Relationships>;
export class RecordCache {
private cache: Record<
`${CollectionId}:${string}`,
{
record: AnyDocument | Relationship;
subscriptions: ((record: AnyDocument | Relationship | null) => void)[];
}
> = {};
private makeKey<C extends CollectionId>(
collectionId: C,
id: string,
): CacheKey<C> {
return `${collectionId}:${id}`;
}
private docKey = (id: DocumentId): DocumentKey =>
this.makeKey(CollectionIds.Documents, id);
private relationKey = (id: RelationshipId): RelationshipKey =>
this.makeKey(CollectionIds.Relationships, id);
get = (key: CacheKey): AnyDocument | Relationship | undefined =>
this.cache[key]?.record;
set = (record: AnyDocument | Relationship) => {
const key = this.makeKey(record.collectionName, record.id);
if (this.cache[key] === undefined) {
this.cache[key] = {
record,
subscriptions: [],
};
}
const entry = this.cache[key];
entry.record = record;
for (const subscription of entry.subscriptions) {
subscription(record);
}
for (const doc of record.expand?.secondary ?? []) {
this.set(doc);
}
for (const rel of record.expand?.relationships_via_primary ?? []) {
this.set(rel);
}
};
remove = (key: CacheKey) => {
const entry = this.cache[key];
delete this.cache[key];
for (const subscription of entry.subscriptions) {
subscription(null);
}
};
getDocument = (id: DocumentId): AnyDocument | undefined =>
this.get(this.docKey(id)) as AnyDocument | undefined;
getRelationship = (id: RelationshipId): Relationship | undefined =>
this.get(this.relationKey(id)) as Relationship | undefined;
removeDocument = (id: DocumentId) => this.remove(this.docKey(id));
removeRelationship = (id: RelationshipId) =>
this.remove(this.relationKey(id));
}

View File

@@ -5,9 +5,18 @@ export type Id<T extends string> = string & { __type: T };
export type UserId = Id<"User">;
export type CampaignId = Id<"Campaign">;
export type DocumentId = Id<"Document">;
export type RelationshipId = Id<"Relationship">;
export type ISO8601Date = string & { __type: "iso8601date" };
export const CollectionIds = {
Campaigns: "campaigns",
Documents: "documents",
Relationships: "relationships",
} as const;
export type CollectionId = (typeof CollectionIds)[keyof typeof CollectionIds];
export type Campaign = RecordModel & {
id: CampaignId;
name: string;
@@ -32,6 +41,8 @@ export type RelationshipType =
(typeof RelationshipType)[keyof typeof RelationshipType];
export type Relationship = RecordModel & {
id: RelationshipId;
collectionName: typeof CollectionIds.Relationships;
primary: DocumentId;
secondary: DocumentId[];
type: RelationshipType;
@@ -57,6 +68,7 @@ export type DocumentData<Type extends DocumentType, Data> = {
export type Document<Type extends DocumentType, Data> = RecordModel & {
id: DocumentId;
collectionName: typeof CollectionIds.Documents;
campaign: CampaignId;
type: Type;
data: Data;

View File

@@ -1,4 +1,5 @@
import { AuthProvider } from "@/context/auth/AuthContext";
import { CacheProvider } from "@/context/cache/CacheContext";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { Outlet, createRootRoute } from "@tanstack/react-router";
import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
@@ -7,7 +8,9 @@ export const Route = createRootRoute({
component: () => (
<>
<AuthProvider>
<Outlet />
<CacheProvider>
<Outlet />
</CacheProvider>
</AuthProvider>
<TanStackRouterDevtools />
<ReactQueryDevtools buttonPosition="bottom-right" />

View File

@@ -1,5 +1,7 @@
import { Loader } from "@/components/Loader";
import { useAuth } from "@/context/auth/AuthContext";
import { Link, Outlet, createFileRoute } from "@tanstack/react-router";
import { Suspense } from "react";
export const Route = createFileRoute("/_app")({
component: RouteComponent,
@@ -71,7 +73,9 @@ function RouteComponent() {
return (
<>
<AppHeader />
<Outlet />
<Suspense fallback={<Loader />}>
<Outlet />
</Suspense>
</>
);
}

View File

@@ -1,40 +1,34 @@
import { RelationshipList } from "@/components/RelationshipList";
import { DocumentEditForm } from "@/components/documents/DocumentEditForm";
import { pb } from "@/lib/pocketbase";
import { displayName, relationshipsForDocument } from "@/lib/relationships";
import { RelationshipType, type AnyDocument } from "@/lib/types";
import { Tab, TabGroup, TabList, TabPanel, TabPanels } from "@headlessui/react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useDocument } from "@/context/cache/CacheContext";
import type { DocumentId } from "@/lib/types";
export const Route = createFileRoute(
"/_app/_authenticated/document/$documentId",
)({
loader: async ({ params }) => {
const doc = await pb.collection("documents").getOne(params.documentId);
return {
document: doc,
};
},
component: RouteComponent,
});
function RouteComponent() {
const { document } = Route.useLoaderData() as {
document: AnyDocument;
};
const { documentId } = Route.useParams();
const relationshipList = relationshipsForDocument(document);
const doc = useDocument(documentId as DocumentId);
const relationshipList = relationshipsForDocument(doc);
return (
<div key={document.id} className="max-w-xl mx-auto py-2 px-4">
<div key={doc.id} className="max-w-xl mx-auto py-2 px-4">
<Link
to="/document/$documentId/print"
params={{ documentId: document.id }}
params={{ documentId: doc.id }}
className="text-slate-400 hover:text-violet-400 text-sm underline underline-offset-2 transition-colors mb-4"
>
Print
</Link>
<DocumentEditForm document={document} />
<DocumentEditForm document={doc} />
<TabGroup>
<TabList className="flex flex-row flex-wrap gap-1 mt-2">
{relationshipList.map((relationshipType) => (
@@ -51,7 +45,7 @@ function RouteComponent() {
<TabPanel key={relationshipType}>
<RelationshipList
key={relationshipType}
root={document}
root={doc}
relationshipType={relationshipType}
/>
</TabPanel>