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 // Re-throw to trigger immediate rollback of optimistic update
38 throw error;
39 }
40 },
41 getKey: (item) => item.id,
42 }),
43);
44
45async function getProjects() {
46 const res = await fetch("/api/projects");
47 if (res.status !== 200) {
48 if (res.status === 404) {
49 /*
50 Sometimes the service worker serving responding to the
51 API requests is acting up, causing 404s.
52 */
53 throw new ProjectsNotFoundFromAPIError("No projects found");
54 } else {
55 throw new Error("Failed to fetch projects");
56 }
57 }
58
59 const data: ProjectRecord[] = await res.json();
60 return data;
61}
62
63async function updateProject({
64 changes,
65 original,
66}: {
67 changes: Partial<ProjectRecord>;
68 original: ProjectRecord;
69}) {
70 /*
71 NOTE: we're intentionally not using server functions to make
72 it easier to inspect the requests in the networks panel.
73 */
74
75 const res = await fetch("/api/projects", {
76 method: "PATCH",
77 headers: {
78 "Content-Type": "application/json",
79 },
80 body: JSON.stringify({
81 id: original.id,
82 ...changes,
83 } satisfies ProjectUpdateData),
84 });
85
86 if (res.status !== 200) {
87 // biome-ignore lint/suspicious/noExplicitAny: it's okay
88 const errorData: any = await res.text();
89 throw new Error(errorData);
90 }
91}