Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

todos.ts

326 lines9.1 KB

1import { createCollection } from '@tanstack/react-db'
2import { queryCollectionOptions } from '@tanstack/query-db-collection'
3import { startOfflineExecutor } from '@tanstack/offline-transactions'
4import {
5 ElectronCollectionCoordinator,
6 createElectronSQLitePersistence,
7 persistedCollectionOptions,
8} from '@tanstack/electron-db-sqlite-persistence'
9import { z } from 'zod'
10import { queryClient } from '../utils/queryClient'
11import type { StorageAdapter } from '@tanstack/offline-transactions'
12import type { Todo } from '../utils/api'
13import type { PendingMutation } from '@tanstack/db'
14​
15// Declare the electronAPI exposed via preload
16declare global {
17 interface Window {
18 electronAPI: {
19 invoke: (channel: string, ...args: Array<unknown>) => Promise<unknown>
20 resetDatabase: () => Promise<void>
21 kv: {
22 get: (key: string) => Promise<string | null>
23 set: (key: string, value: string) => Promise<void>
24 delete: (key: string) => Promise<void>
25 keys: () => Promise<Array<string>>
26 clear: () => Promise<void>
27 }
28 }
29 }
31​
32/**
33 * SQLite-backed storage adapter for the offline transactions outbox.
34 * Stores pending mutations in the main process SQLite database via IPC,
35 * so they survive app restarts (unlike IndexedDB in Electron).
36 */
37class ElectronSQLiteStorageAdapter implements StorageAdapter {
38 private prefix: string
39​
40 constructor(prefix = 'offline-tx:') {
41 this.prefix = prefix
42 }
43​
44 private prefixedKey(key: string): string {
45 return `${this.prefix}${key}`
46 }
47​
48 async get(key: string): Promise<string | null> {
49 return window.electronAPI.kv.get(this.prefixedKey(key))
50 }
51​
52 async set(key: string, value: string): Promise<void> {
53 await window.electronAPI.kv.set(this.prefixedKey(key), value)
54 }
55​
56 async delete(key: string): Promise<void> {
57 await window.electronAPI.kv.delete(this.prefixedKey(key))
58 }
59​
60 async keys(): Promise<Array<string>> {
61 const allKeys = await window.electronAPI.kv.keys()
62 return allKeys
63 .filter((k) => k.startsWith(this.prefix))
64 .map((k) => k.slice(this.prefix.length))
65 }
66​
67 async clear(): Promise<void> {
68 const keys = await this.keys()
69 for (const key of keys) {
70 await window.electronAPI.kv.delete(this.prefixedKey(key))
71 }
72 }
74​
75/**
76 * Fetch with retry and exponential backoff.
77 * Keeps retrying on network errors and non-OK responses so the app
78 * degrades gracefully when the server is temporarily unreachable.
79 */
80async function fetchWithRetry(
81 url: string,
82 options: RequestInit = {},
83 retryConfig: { retries?: number; delay?: number; backoff?: number } = {},
84): Promise<Response> {
85 const { retries = 6, delay = 1000, backoff = 2 } = retryConfig
86​
87 for (let i = 0; i <= retries; i++) {
88 try {
89 const response = await fetch(url, options)
90 if (response.ok) return response
91​
92 console.warn(
93 `Fetch attempt ${i + 1} failed with status: ${response.status}. Retrying...`,
94 )
95 } catch (error) {
96 console.error(
97 `Fetch attempt ${i + 1} failed due to a network error:`,
98 error,
99 )
100 if (i >= retries) throw error
101 }
102​
103 if (i < retries) {
104 const currentDelay = delay * Math.pow(backoff, i)
105 await new Promise((resolve) => setTimeout(resolve, currentDelay))
106 }
107 }
108​
109 throw new Error(`Failed to fetch ${url} after ${retries} retries.`)
111​
112// Schema — use ISO strings for dates (SQLite-friendly)
113const todoSchema = z.object({
114 id: z.string(),
115 text: z.string(),
116 completed: z.boolean(),
117 createdAt: z.string(),
118 updatedAt: z.string(),
119})
120​
121// Multi-window coordinator: uses BroadcastChannel + Web Locks for
122// leader election and cross-window notification (both available in Electron)
123const coordinator = new ElectronCollectionCoordinator({
124 dbName: 'electron-todos',
125})
126​
127// Create persistence via IPC bridge to the main process SQLite database
128const persistence = createElectronSQLitePersistence({
129 invoke: window.electronAPI.invoke,
130 coordinator,
131})
132​
133const BASE_URL = 'http://localhost:3001'
134​
135// Compose: query sync wrapped in persisted collection
136const queryOpts = queryCollectionOptions({
137 id: 'todos-collection',
138 queryClient,
139 queryKey: ['todos'],
140 queryFn: async (): Promise<Array<Todo>> => {
141 const response = await fetchWithRetry(`${BASE_URL}/api/todos`)
142 if (!response.ok) {
143 throw new Error(`Failed to fetch todos: ${response.status}`)
144 }
145 return response.json()
146 },
147 getKey: (item) => item.id,
148 schema: todoSchema,
149 refetchInterval: 3000,
150})
151​
152// Sync function to push mutations to the backend
153async function syncTodos({
154 transaction,
155 idempotencyKey,
156}: {
157 transaction: { mutations: Array<PendingMutation> }
158 idempotencyKey: string
159}) {
160 const mutations = transaction.mutations
161​
162 console.log(`[Sync] Processing ${mutations.length} mutations`, idempotencyKey)
163​
164 for (const mutation of mutations) {
165 try {
166 switch (mutation.type) {
167 case 'insert': {
168 const todoData = mutation.modified as Todo
169 const response = await fetchWithRetry(`${BASE_URL}/api/todos`, {
170 method: 'POST',
171 headers: {
172 'Content-Type': 'application/json',
173 'Idempotency-Key': idempotencyKey,
174 },
175 body: JSON.stringify({
176 id: todoData.id,
177 text: todoData.text,
178 completed: todoData.completed,
179 }),
180 })
181 if (!response.ok) {
182 throw new Error(`Failed to sync insert: ${response.statusText}`)
183 }
184 break
185 }
186​
187 case 'update': {
188 const todoData = mutation.modified as Partial<Todo>
189 const id = (mutation.modified as Todo).id
190 const response = await fetchWithRetry(`${BASE_URL}/api/todos/${id}`, {
191 method: 'PUT',
192 headers: {
193 'Content-Type': 'application/json',
194 'Idempotency-Key': idempotencyKey,
195 },
196 body: JSON.stringify({
197 text: todoData.text,
198 completed: todoData.completed,
199 }),
200 })
201 if (!response.ok) {
202 throw new Error(`Failed to sync update: ${response.statusText}`)
203 }
204 break
205 }
206​
207 case 'delete': {
208 const id = (mutation.original as Todo).id
209 const response = await fetchWithRetry(`${BASE_URL}/api/todos/${id}`, {
210 method: 'DELETE',
211 headers: {
212 'Idempotency-Key': idempotencyKey,
213 },
214 })
215 if (!response.ok) {
216 throw new Error(`Failed to sync delete: ${response.statusText}`)
217 }
218 break
219 }
220 }
221 } catch (error) {
222 console.error('[Sync] Error syncing mutation:', mutation, error)
223 throw error
224 }
225 }
226​
227 // Refresh the collection after sync
228 await collection.utils.refetch()
230​
231// Create the persisted collection
232const collection = createCollection(
233 persistedCollectionOptions({
234 ...queryOpts,
235 persistence,
236 schemaVersion: 1,
237 }),
239​
240// Create todos setup: collection + offline executor
241export function createTodos() {
242 const executor = startOfflineExecutor({
243 collections: { todos: collection },
244 storage: new ElectronSQLiteStorageAdapter('offline-tx:'),
245 mutationFns: {
246 syncTodos,
247 },
248 onLeadershipChange: (isLeader) => {
249 console.log('[Offline] Leadership changed:', isLeader)
250 },
251 onStorageFailure: (diagnostic) => {
252 console.warn('[Offline] Storage failure:', diagnostic)
253 },
254 })
255​
256 console.log('[Offline] Executor mode:', executor.mode)
257​
258 // Log when initialization completes and pending transactions are loaded
259 executor
260 .waitForInit()
261 .then(() => {
262 console.log(
263 '[Offline] Init complete. isOfflineEnabled:',
264 executor.isOfflineEnabled,
265 )
266 console.log('[Offline] Pending count:', executor.getPendingCount())
267 })
268 .catch((err) => {
269 console.error('[Offline] Init failed:', err)
270 })
271​
272 return {
273 collection,
274 executor,
275 close: () => {
276 executor.dispose()
277 },
278 }
280​
281// Helper to create offline actions
282export function createTodoActions(
283 offline: ReturnType<typeof createTodos>['executor'],
284) {
285 const addTodo = offline.createOfflineAction({
286 mutationFnName: 'syncTodos',
287 onMutate: (text: string) => {
288 const now = new Date().toISOString()
289 const newTodo: Todo = {
290 id: crypto.randomUUID(),
291 text: text.trim(),
292 completed: false,
293 createdAt: now,
294 updatedAt: now,
295 }
296 collection.insert(newTodo)
297 return newTodo
298 },
299 })
300​
301 const toggleTodo = offline.createOfflineAction({
302 mutationFnName: 'syncTodos',
303 onMutate: (id: string) => {
304 const todo = collection.get(id)
305 if (!todo) return
306 collection.update(id, (draft) => {
307 draft.completed = !draft.completed
308 draft.updatedAt = new Date().toISOString()
309 })
310 return todo
311 },
312 })
313​
314 const deleteTodo = offline.createOfflineAction({
315 mutationFnName: 'syncTodos',
316 onMutate: (id: string) => {
317 const todo = collection.get(id)
318 if (todo) {
319 collection.delete(id)
320 }
321 return todo
322 },
323 })
324​
325 return { addTodo, toggleTodo, deleteTodo }