({
transaction,
idempotencyKey,
}: {
transaction: { mutations: Array<PendingMutation> }
idempotencyKey: string
})
| 151 | |
| 152 | // Sync function to push mutations to the backend |
| 153 | async 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', |
nothing calls this directly
no test coverage detected