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 { TodoItemRecord } from "@/db/schema";
5import * as TanstackQuery from "@/integrations/tanstack-query/root-provider";
6import type { TodoItemCreateDataType } from "@/local-api/api.todo-items";
7
8async function getTodoItems() {
9 const res = await fetch("/api/todo-items", { method: "GET" });
10
11 const todoItems: TodoItemRecord[] = await res.json();
12
13 return todoItems;
14}
15
16async function updateTodoItem({
17 data,
18}: {
19 data: Partial<TodoItemRecord> & { id: string };
20}) {
21 const res = await fetch("/api/todo-items", {
22 method: "PATCH",
23 headers: {
24 "Content-Type": "application/json",
25 },
26 body: JSON.stringify(data),
27 });
28
29 if (!res.ok) {
30 throw new Error("Failed to update todo item");
31 }
32
33 const updatedItem: TodoItemRecord = await res.json();
34
35 return updatedItem;
36}
37
38export async function batchUpdateTodoItem({
39 data,
40}: {
41 data: (Partial<TodoItemRecord> & { id: string })[];
42}) {
43 const res = await fetch("/api/batch/todo-items", {
44 method: "PATCH",
45 headers: {
46 "Content-Type": "application/json",
47 },
48 body: JSON.stringify(data),
49 });
50
51 if (!res.ok) {
52 throw new Error("Failed to batch update todo items");
53 }
54
55 await res.json();
56}
57
58async function insertTodoItem({ data }: { data: TodoItemCreateDataType }) {
59 const res = await fetch("/api/todo-items", {
60 method: "POST",
61 headers: {
62 "Content-Type": "application/json",
63 },
64 body: JSON.stringify(data),
65 });
66
67 if (!res.ok) {
68 throw new Error("Failed to insert todo item");
69 }
70
71 const response: TodoItemRecord = await res.json();
72
73 return response;
74}
75
76export const todoItemsCollection = createCollection(
77 queryCollectionOptions({
78 queryKey: ["todo-items"],
79 queryFn: getTodoItems,
80 queryClient: TanstackQuery.getContext().queryClient,
81 onInsert: async ({ transaction }) => {
82 const { modified: newTodoItem } = transaction.mutations[0];
83
84 try {
85 await insertTodoItem({
86 data: newTodoItem,
87 });
88 } catch (error) {
89 // TODO: handle error
90 toast.error(`Failed to insert todo item "${newTodoItem.title}"`);
91 console.error("Failed to insert todo item:", error);
92 }
93 },
94 onUpdate: async ({ transaction }) => {
95 const { original, changes } = transaction.mutations[0];
96
97 try {
98 await updateTodoItem({
99 data: {
100 id: original.id,
101 ...changes,
102 },
103 });
104 } catch (error) {
105 // TODO: handle error
106 console.error("Failed to update todo item:", error);
107 }
108 },
109 getKey: (item) => item.id,
110 }),
111);