1
0
Fork 0
mirror of synced 2024-06-29 11:31:06 +12:00
budibase/packages/backend-core/src/db/Replication.js

64 lines
1.6 KiB
JavaScript
Raw Normal View History

const { dangerousGetDB } = require(".")
2021-05-13 22:06:08 +12:00
class Replication {
/**
*
* @param {String} source - the DB you want to replicate or rollback to
* @param {String} target - the DB you want to replicate to, or rollback from
*/
constructor({ source, target }) {
this.source = dangerousGetDB(source)
this.target = dangerousGetDB(target)
2021-05-13 22:06:08 +12:00
}
promisify(operation, opts = {}) {
return new Promise(resolve => {
operation(this.target, opts)
2021-05-13 22:06:08 +12:00
.on("denied", function (err) {
// a document failed to replicate (e.g. due to permissions)
throw new Error(`Denied: Document failed to replicate ${err}`)
})
.on("complete", function (info) {
return resolve(info)
})
.on("error", function (err) {
throw new Error(`Replication Error: ${err}`)
})
})
}
/**
* Two way replication operation, intended to be promise based.
* @param {Object} opts - PouchDB replication options
*/
2021-05-17 08:25:37 +12:00
sync(opts = {}) {
this.replication = this.promisify(this.source.sync, opts)
return this.replication
}
/**
* One way replication operation, intended to be promise based.
* @param {Object} opts - PouchDB replication options
*/
2021-05-17 08:25:37 +12:00
replicate(opts = {}) {
this.replication = this.promisify(this.source.replicate.to, opts)
return this.replication
}
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 = dangerousGetDB(this.target.name)
2021-05-13 22:06:08 +12:00
await this.replicate()
}
cancel() {
this.replication.cancel()
}
}
module.exports = Replication