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

todoItems.ts

343 lines8.7 KB

1import { createCollection, parseLoadSubsetOptions } 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";
7import {
8 TODO_ITEMS_SYNC_STATE_ID,
9 todoItemsSyncCollection,
10} from "./todoItemsSync";
11​
12type TodoItemSyncPayload = Pick<
13 TodoItemRecord,
14 "id" | "boardId" | "priority" | "title" | "description" | "position"
15>;
16​
17const UNSYNCED_TOAST_ID = "todo-items-unsynced";
18​
19const desiredPayloadById = new Map<string, TodoItemSyncPayload>();
20const inFlightItemIds = new Set<string>();
21const lastSyncedSignatureById = new Map<string, string>();
22const retryAttemptById = new Map<string, number>();
23const retryTimeoutById = new Map<string, ReturnType<typeof setTimeout>>();
24const unsyncedItemIds = new Set<string>();
25const failedItemIds = new Set<string>();
26​
27function syncStateCollection() {
28 todoItemsSyncCollection.update(TODO_ITEMS_SYNC_STATE_ID, (draft) => {
29 draft.unsyncedItemIds = [...unsyncedItemIds].sort();
30 draft.inFlightItemIds = [...inFlightItemIds].sort();
31 draft.failedItemIds = [...failedItemIds].sort();
32 });
34​
35function updateUnsyncedToast() {
36 const failedCount = failedItemIds.size;
37​
38 if (failedCount === 0) {
39 toast.dismiss(UNSYNCED_TOAST_ID);
40 return;
41 }
42​
43 toast.error(
44 failedCount === 1
45 ? "1 todo change failed to sync. Local state is preserved."
46 : `${failedCount} todo changes failed to sync. Local state is preserved.`,
47 {
48 id: UNSYNCED_TOAST_ID,
49 action: {
50 label: "Retry now",
51 onClick: () => {
52 void retryUnsyncedTodoItemsSync();
53 },
54 },
55 },
56 );
58​
59function syncUiIndicators() {
60 syncStateCollection();
61 updateUnsyncedToast();
63​
64function buildPayload(item: TodoItemRecord): TodoItemSyncPayload {
65 return {
66 id: item.id,
67 boardId: item.boardId,
68 priority: item.priority,
69 title: item.title,
70 description: item.description,
71 position: item.position,
72 };
74​
75function payloadSignature(payload: TodoItemSyncPayload): string {
76 return JSON.stringify(payload);
78​
79function clearRetryTimeout(itemId: string) {
80 const timeoutId = retryTimeoutById.get(itemId);
81 if (timeoutId) {
82 clearTimeout(timeoutId);
83 retryTimeoutById.delete(itemId);
84 }
86​
87function getRetryDelayMs(attempt: number): number {
88 return Math.min(30_000, 1_000 * 2 ** Math.max(0, attempt - 1));
90​
91function getTodoItem(itemId: string): TodoItemRecord | undefined {
92 return todoItemsCollection.get(itemId);
94​
95function syncTodoItemsQueryCache(modified: TodoItemRecord) {
96 const queryClient = TanstackQuery.getContext().queryClient;
97 queryClient.setQueriesData<TodoItemRecord[]>(
98 { queryKey: todoItemsQueryKey },
99 (oldData) => {
100 if (!oldData) {
101 return oldData;
102 }
103​
104 return oldData.map((item) => (item.id === modified.id ? modified : item));
105 },
106 );
108​
109function markUnsynced(itemId: string) {
110 unsyncedItemIds.add(itemId);
111 syncUiIndicators();
113​
114function markSynced(itemId: string) {
115 unsyncedItemIds.delete(itemId);
116 failedItemIds.delete(itemId);
117 syncUiIndicators();
119​
120function clearSyncStateForItem(itemId: string) {
121 clearRetryTimeout(itemId);
122 desiredPayloadById.delete(itemId);
123 inFlightItemIds.delete(itemId);
124 lastSyncedSignatureById.delete(itemId);
125 retryAttemptById.delete(itemId);
126 unsyncedItemIds.delete(itemId);
127 failedItemIds.delete(itemId);
128 syncUiIndicators();
130​
131async function flushItemSync(itemId: string) {
132 if (inFlightItemIds.has(itemId)) {
133 return;
134 }
135​
136 const desiredPayload = desiredPayloadById.get(itemId);
137​
138 if (!desiredPayload) {
139 clearSyncStateForItem(itemId);
140 return;
141 }
142​
143 const desiredSignature = payloadSignature(desiredPayload);
144​
145 if (lastSyncedSignatureById.get(itemId) === desiredSignature) {
146 markSynced(itemId);
147 return;
148 }
149​
150 inFlightItemIds.add(itemId);
151 syncUiIndicators();
152​
153 try {
154 await updateTodoItem({ data: desiredPayload });
155 lastSyncedSignatureById.set(itemId, desiredSignature);
156 retryAttemptById.set(itemId, 0);
157 } catch (error) {
158 const nextAttempt = (retryAttemptById.get(itemId) ?? 0) + 1;
159 retryAttemptById.set(itemId, nextAttempt);
160 unsyncedItemIds.add(itemId);
161 failedItemIds.add(itemId);
162 syncUiIndicators();
163​
164 const delay = getRetryDelayMs(nextAttempt);
165 const timeoutId = setTimeout(() => {
166 retryTimeoutById.delete(itemId);
167 void flushItemSync(itemId);
168 }, delay);
169​
170 retryTimeoutById.set(itemId, timeoutId);
171​
172 console.error(`Failed to sync todo item ${itemId}:`, error);
173 return;
174 } finally {
175 inFlightItemIds.delete(itemId);
176 syncUiIndicators();
177 }
178​
179 const latestLocalItem = getTodoItem(itemId);
180​
181 if (!latestLocalItem) {
182 clearSyncStateForItem(itemId);
183 return;
184 }
185​
186 const latestPayload = buildPayload(latestLocalItem);
187 const latestSignature = payloadSignature(latestPayload);
188​
189 desiredPayloadById.set(itemId, latestPayload);
190​
191 if (lastSyncedSignatureById.get(itemId) !== latestSignature) {
192 markUnsynced(itemId);
193 void flushItemSync(itemId);
194 return;
195 }
196​
197 markSynced(itemId);
199​
200function queueLatestSync(itemId: string) {
201 const todoItem = getTodoItem(itemId);
202​
203 if (!todoItem) {
204 clearSyncStateForItem(itemId);
205 return;
206 }
207​
208 clearRetryTimeout(itemId);
209​
210 const nextPayload = buildPayload(todoItem);
211 desiredPayloadById.set(itemId, nextPayload);
212​
213 const nextSignature = payloadSignature(nextPayload);
214 const lastSyncedSignature = lastSyncedSignatureById.get(itemId);
215​
216 if (lastSyncedSignature !== nextSignature) {
217 markUnsynced(itemId);
218 }
219​
220 void flushItemSync(itemId);
222​
223export async function retryUnsyncedTodoItemsSync() {
224 const idsToRetry = [...failedItemIds];
225​
226 idsToRetry.forEach((itemId) => {
227 failedItemIds.delete(itemId);
228 clearRetryTimeout(itemId);
229 retryAttemptById.set(itemId, 0);
230 void flushItemSync(itemId);
231 });
232​
233 syncUiIndicators();
234​
235 return idsToRetry.length;
237​
238async function updateTodoItem({
239 data,
240}: {
241 data: Partial<TodoItemRecord> & { id: string };
242}) {
243 const res = await fetch("/api/todo-items", {
244 method: "PATCH",
245 headers: {
246 "Content-Type": "application/json",
247 },
248 body: JSON.stringify(data),
249 });
250​
251 if (!res.ok) {
252 throw new Error("Failed to update todo item");
253 }
254​
255 const updatedItem: TodoItemRecord = await res.json();
256​
257 return updatedItem;
259​
260async function insertTodoItem({ data }: { data: TodoItemCreateDataType }) {
261 const res = await fetch("/api/todo-items", {
262 method: "POST",
263 headers: {
264 "Content-Type": "application/json",
265 },
266 body: JSON.stringify(data),
267 });
268​
269 if (!res.ok) {
270 throw new Error("Failed to insert todo item");
271 }
272​
273 const response: TodoItemRecord = await res.json();
274​
275 return response;
277​
278const todoItemsQueryKey = ["todo-items"];
279​
280export const todoItemsCollection = createCollection<TodoItemRecord>(
281 queryCollectionOptions({
282 queryKey: todoItemsQueryKey,
283 queryFn: async ({ meta }) => {
284 const params = new URLSearchParams();
285​
286 if (meta) {
287 const { where } = meta.loadSubsetOptions;
288​
289 // Parse the expressions into simple format
290 const parsed = parseLoadSubsetOptions({ where });
291​
292 // Build query parameters from parsed filters
293​
294 // Add filters
295 parsed.filters.forEach(({ field, operator, value }) => {
296 const fieldName = field.join(".");
297​
298 // Currently only the "eq" operator is supported by our API
299 if (operator === "eq") {
300 params.set(fieldName, String(value));
301 }
302 });
303 }
304​
305 const res = await fetch(`/api/todo-items?${params}`, { method: "GET" });
306​
307 const todoItems: TodoItemRecord[] = await res.json();
308​
309 return todoItems;
310 },
311 queryClient: TanstackQuery.getContext().queryClient,
312 syncMode: "on-demand",
313 onInsert: async ({ transaction }) => {
314 const { modified: newTodoItem } = transaction.mutations[0];
315​
316 try {
317 await insertTodoItem({
318 data: newTodoItem,
319 });
320 } catch (error) {
321 toast.error(`Failed to insert todo item "${newTodoItem.title}"`);
322 console.error("Failed to insert todo item:", error);
323 throw error;
324 }
325 },
326 onUpdate: async ({ transaction }) => {
327 const { modified } = transaction.mutations[0];
328​
329 // Keep TanStack Query cache aligned with local optimistic state
330 // so switching projects still shows the latest local edits.
331 syncTodoItemsQueryCache(modified);
332​
333 // Local-first, latest-wins sync queue per item.
334 // We never throw here, so local optimistic state is never rolled back.
335 queueLatestSync(modified.id);
336​
337 return {
338 refetch: false,
339 };
340 },
341 getKey: (item) => item.id,
342 }),
343);