MCPcopy Create free account
hub / github.com/TanStack/db / syncTodos

Function syncTodos

examples/electron/offline-first/src/db/todos.ts:153–229  ·  view source on GitHub ↗
({
  transaction,
  idempotencyKey,
}: {
  transaction: { mutations: Array<PendingMutation> }
  idempotencyKey: string
})

Source from the content-addressed store, hash-verified

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',

Callers

nothing calls this directly

Calls 1

fetchWithRetryFunction · 0.70

Tested by

no test coverage detected