Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

on-demand-notes.ts

51 lines1.9 KB

1import { and, createCollection, eq, isNull } from "@tanstack/react-db";
2import type { InitialQueryBuilder } from "@tanstack/react-db";
3import { parseLoadSubsetOptions, queryCollectionOptions } from "@tanstack/query-db-collection";
4​
5import { api } from "@/api/client";
6​
7import { queryClient } from "./query-client";
8import { noteSchema } from "./schema";
9import type { Note } from "./schema";
10​
11/**
12 * The query-driven sync deep dive: the same notes as `notesCollection`, but
13 * loaded on demand. The Notes app itself doesn't use this collection.
14 */
15​
16// #region on-demand-collection
17export const onDemandNotesCollection = createCollection(
18 queryCollectionOptions({
19 id: "notes-on-demand",
20 queryKey: ["notes-on-demand"],
21 // Load nothing up front: only the notes that live queries ask for.
22 syncMode: "on-demand",
23 queryFn: ({ signal, meta }) => {
24 // The live query's `where`, as a list of simple comparisons.
25 const { filters } = parseLoadSubsetOptions(meta?.loadSubsetOptions);
26 const params = new URLSearchParams();
27 for (const { field, operator, value } of filters) {
28 // The API can only filter by folder. Every other condition is
29 // still applied by the live query, in the browser.
30 if (field.join(".") === "folderId" && operator === "eq") {
31 params.set("folderId", String(value));
32 }
33 }
34 return api.get<Note[]>(`/api/notes?${params}`, { signal });
35 },
36 queryClient,
37 schema: noteSchema,
38 getKey: (note) => note.id,
39 }),
40);
41// #endregion on-demand-collection
42​
43// #region folder-notes-query
44export function folderNotesQuery(folderId: string) {
45 return (q: InitialQueryBuilder) =>
46 q
47 .from({ note: onDemandNotesCollection })
48 .where(({ note }) => and(eq(note.folderId, folderId), isNull(note.deletedAt)))
49 .orderBy(({ note }) => note.updatedAt, "desc");
51// #endregion folder-notes-query