1
0
Fork 0
mirror of synced 2024-09-20 03:08:18 +12:00
budibase/packages/backend-core/src/db/Replication.ts

72 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-03-06 06:35:04 +13:00
import PouchDB from "pouchdb"
import { getPouchDB, closePouchDB } from "./couch"
import { DocumentType } from "../constants"
2021-05-13 22:06:08 +12:00
class Replication {
2024-03-06 06:35:04 +13:00
source: PouchDB.Database
target: PouchDB.Database
2024-03-06 06:35:04 +13:00
constructor({ source, target }: { source: string; target: string }) {
this.source = getPouchDB(source)
this.target = getPouchDB(target)
2021-05-13 22:06:08 +12:00
}
2024-03-06 23:00:02 +13:00
async close() {
await Promise.all([closePouchDB(this.source), closePouchDB(this.target)])
}
2024-03-06 23:00:02 +13:00
replicate(opts: PouchDB.Replication.ReplicateOptions = {}) {
return new Promise<PouchDB.Replication.ReplicationResult<{}>>(resolve => {
this.source.replicate
.to(this.target, opts)
.on("denied", function (err) {
2021-05-13 22:06:08 +12:00
// a document failed to replicate (e.g. due to permissions)
throw new Error(`Denied: Document failed to replicate ${err}`)
})
2024-03-06 23:00:02 +13:00
.on("complete", function (info) {
2021-05-13 22:06:08 +12:00
return resolve(info)
})
2024-03-06 23:00:02 +13:00
.on("error", function (err) {
2021-05-13 22:06:08 +12:00
throw new Error(`Replication Error: ${err}`)
})
})
}
2024-03-06 06:35:04 +13:00
appReplicateOpts(
opts: PouchDB.Replication.ReplicateOptions = {}
): PouchDB.Replication.ReplicateOptions {
if (typeof opts.filter === "string") {
return opts
}
const filter = opts.filter
delete opts.filter
return {
2024-03-06 06:35:04 +13:00
...opts,
filter: (doc: any, params: any) => {
if (doc._id && doc._id.startsWith(DocumentType.AUTOMATION_LOG)) {
return false
}
2024-03-06 06:35:04 +13:00
if (doc._id === DocumentType.APP_METADATA) {
return false
}
return filter ? filter(doc, params) : true
},
}
}
2021-05-17 08:25:37 +12:00
/**
* Rollback the target DB back to the state of the source DB
*/
2021-05-13 22:06:08 +12:00
async rollback() {
await this.target.destroy()
2021-05-17 08:25:37 +12:00
// Recreate the DB again
this.target = getPouchDB(this.target.name)
// take the opportunity to remove deleted tombstones
2021-05-13 22:06:08 +12:00
await this.replicate()
}
}
export default Replication