PGlite Postgres 同步插件
A 类 同步插件 页:1 PGlite 读取 使用 电器。完整的文件可在 pglite.dev/docs/ sync (英语)。 。 。 .
要安装 :
npm install @electric-sql/pglite-sync
并创建所需的本地表格:
import { electricSync } from '@electric-sql/pglite-sync'
const pg = await PGlite.create({
extensions: {
electric: electricSync(),
},
})
await pg.exec(`
CREATE TABLE IF NOT EXISTS todo (
id SERIAL PRIMARY KEY,
task TEXT,
done BOOLEAN
);
`)
您可以使用单个表格或多表 API 同步来自 Electric 的数据 :
单表同步
使用 syncShapeToTable 以同步单个表格 :
const shape = await pg.electric.syncShapeToTable({
shape: { url: 'http://localhost:3000/v1/shape', table: 'todo' },
shapeKey: 'todo', // or null if the shape state does not need to be persisted
table: 'todo',
primaryKey: ['id'],
onError: (error) => {
console.error('Shape sync error', error)
}
})
多表同步
多表 API 当您需要同步相关表格时是有用的, 通过同步 PGLite 中作为单项交易在 Postgres 中发生的更新来保证多个表格的一致性 .
使用 syncShapesToTables 以同步多个表格:
const sync = await pg.electric.syncShapesToTables({
shapes: {
todos: {
shape: { url: 'http://localhost:3000/v1/shape', table: 'todo' },
table: 'todo',
primaryKey: ['id'],
},
users: {
shape: { url: 'http://localhost:3000/v1/shape', table: 'users' },
table: 'users',
primaryKey: ['id'],
}
},
key: 'my-sync', // or null if the sync state does not need to be persisted
onInitialSync: () => {
console.log('Initial sync complete')
},
onError: (error) => {
console.error('Sync error', error)
}
})
// Unsubscribe when done
sync.unsubscribe()