1
0
Fork 0
mirror of synced 2024-06-26 18:10:51 +12:00
budibase/packages/backend-core/src/db/Replication.ts

82 lines
2 KiB
TypeScript
Raw Normal View History

import { dangerousGetDB, closeDB } from "."
import { DocumentType } from "./constants"
2021-05-13 22:06:08 +12:00
class Replication {
source: any
target: any
replication: any
2021-05-13 22:06:08 +12:00
/**
*
* @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 }: any) {
this.source = dangerousGetDB(source)
this.target = dangerousGetDB(target)
2021-05-13 22:06:08 +12:00
}
close() {
return Promise.all([closeDB(this.source), closeDB(this.target)])
}
promisify(operation: any, opts = {}) {
return new Promise(resolve => {
operation(this.target, opts)
.on("denied", function (err: any) {
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}`)
})
.on("complete", function (info: any) {
2021-05-13 22:06:08 +12:00
return resolve(info)
})
.on("error", function (err: any) {
2021-05-13 22:06:08 +12:00
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
}
appReplicateOpts() {
return {
filter: (doc: any) => {
return doc._id !== DocumentType.APP_METADATA
},
}
}
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)
// take the opportunity to remove deleted tombstones
2021-05-13 22:06:08 +12:00
await this.replicate()
}
cancel() {
this.replication.cancel()
}
}
export default Replication