首页 > 解决方案 > 如何使用 watermelondb 为同步功能传递数据

问题描述

大家好,我正在使用 watermelondb,我有下面的代码,但我不知道如何实际使用它。我是 watermelondb 的新手,我不知道如何将数据作为道具传递给pullChangespushChanges对象。当我调用同步函数时,如何将必要的数据(如更改lastPulledAt)从数据库传递到同步函数中。而且我还需要对 migrationsEnabledAtVersion: 1 进行更多解释。提前感谢您的亲切回答。

import { synchronize } from '@nozbe/watermelondb/sync'

async function mySync() {
  await synchronize({
    database,
    pullChanges: async ({ lastPulledAt, schemaVersion, migration }) => {
      const urlParams = `last_pulled_at=${lastPulledAt}&schema_version=${schemaVersion}&migration=${encodeURIComponent(JSON.stringify(migration))}`
      const response = await fetch(`https://my.backend/sync?${urlParams}`)
      if (!response.ok) {
        throw new Error(await response.text())
      }

      const { changes, timestamp } = await response.json()
      return { changes, timestamp }
    },
    pushChanges: async ({ changes, lastPulledAt }) => {
      const response = await fetch(`https://my.backend/sync?last_pulled_at=${lastPulledAt}`, {
        method: 'POST',
        body: JSON.stringify(changes)
      })
      if (!response.ok) {
        throw new Error(await response.text())
      }
    },
    migrationsEnabledAtVersion: 1,
  })
}

标签: synchronizewatermelondb

解决方案


推荐阅读