Open History to see the last commit
1import { createCollection } from "@tanstack/db";
2import { queryCollectionOptions } from "@tanstack/query-db-collection";
3import { toast } from "sonner";
4import type { ProjectRecord } from "@/db/schema";
5import * as TanstackQuery from "@/integrations/tanstack-query/root-provider";
6import type { ProjectUpdateData } from "@/local-api/api.projects";
7import { projectErrorNames } from "@/utils/errorNames";
8
9export class ProjectsNotFoundFromAPIError extends Error {
10 constructor(message: string) {
11 super(message);
12 this.name = "ProjectsNotFoundError";
13 }
14}
15
16export const projectsCollection = createCollection(
17 queryCollectionOptions({
18 queryKey: ["projects"],
19 queryFn: getProjects,
20 queryClient: TanstackQuery.getContext().queryClient,
21 onUpdate: async ({ transaction }) => {
22 const { original, changes } = transaction.mutations[0];
23 try {
24 await updateProject({ original, changes });
25 } catch (error) {
26 if (
27 error instanceof Error &&
28 error.message.startsWith(projectErrorNames.PROJECT_NAME_EXISTS)
29 ) {
30 toast.error(
31 `Couldn't rename "${original.name}" to "${changes.name}", because a project with that name already exists.`,
32 );
33 } else {
34 // TODO: handle error
35 console.error("Failed to update todo item:", error);
36 }
37 }
38 },
39 getKey: (item) => item.id,
40 }),
41);
42
43async function getProjects() {
44 const res = await fetch("/api/projects");
45 if (res.status !== 200) {
46 if (res.status === 404) {
47 /*
48 Sometimes the service worker serving responding to the
49 API requests is acting up, causing 404s.
50 */
51 throw new ProjectsNotFoundFromAPIError("No projects found");
52 } else {
53 throw new Error("Failed to fetch projects");
54 }
55 }
56
57 const data: ProjectRecord[] = await res.json();
58 return data;
59}
60
61async function updateProject({
62 changes,
63 original,
64}: {
65 changes: Partial<ProjectRecord>;
66 original: ProjectRecord;
67}) {
68 /*
69 NOTE: we're intentionally not using server functions to make
70 it easier to inspect the requests in the networks panel.
71 */
72
73 const res = await fetch("/api/projects", {
74 method: "PATCH",
75 headers: {
76 "Content-Type": "application/json",
77 },
78 body: JSON.stringify({
79 id: original.id,
80 ...changes,
81 } satisfies ProjectUpdateData),
82 });
83
84 if (res.status !== 200) {
85 // biome-ignore lint/suspicious/noExplicitAny: it's okay
86 const errorData: any = await res.text();
87 throw new Error(errorData);
88 }
89}