MCPcopy Create free account
hub / github.com/electric-sql/electric / doSyncToServer

Function doSyncToServer

examples/linearlite/src/sync.ts:167–249  ·  view source on GitHub ↗
(pg: PGliteWithExtensions)

Source from the content-addressed store, hash-verified

165
166// Call wrapped in mutex to prevent multiple syncs from happening at the same time
167async function doSyncToServer(pg: PGliteWithExtensions) {
168 let issueChanges: IssueChange[]
169 let commentChanges: CommentChange[]
170 await pg.transaction(async (tx) => {
171 const issueRes = await tx.query<IssueChange>(`
172 SELECT
173 id,
174 title,
175 description,
176 priority,
177 status,
178 modified,
179 created,
180 kanbanorder,
181 username,
182 modified_columns,
183 deleted,
184 new
185 FROM issue
186 WHERE synced = false AND sent_to_server = false
187 `)
188 const commentRes = await tx.query<CommentChange>(`
189 SELECT
190 id,
191 body,
192 username,
193 issue_id,
194 modified,
195 created,
196 modified_columns,
197 deleted,
198 new
199 FROM comment
200 WHERE synced = false AND sent_to_server = false
201 `)
202 issueChanges = issueRes.rows
203 commentChanges = commentRes.rows
204 })
205 const changeSet: ChangeSet = {
206 issues: issueChanges!,
207 comments: commentChanges!,
208 }
209 const response = await fetch(APPLY_CHANGES_URL, {
210 method: `POST`,
211 headers: {
212 'Content-Type': `application/json`,
213 },
214 body: JSON.stringify(changeSet),
215 })
216 if (!response.ok) {
217 // In a real app you would want to check which changes have failed and save that
218 // information to the database, maybe in a `sync_errors` column on the row effected.
219 throw new Error(`Failed to apply changes`)
220 }
221 await pg.transaction(async (tx) => {
222 // Mark all changes as sent to server, but check that the modified timestamp
223 // has not changed in the meantime
224

Callers 1

startWritePathFunction · 0.85

Calls 3

fetchFunction · 0.85
queryMethod · 0.80
execMethod · 0.65

Tested by

no test coverage detected