2020-09-26 01:47:42 +12:00
|
|
|
const fs = require("fs")
|
2020-05-07 21:53:34 +12:00
|
|
|
const CouchDB = require("../../db")
|
2020-10-10 07:10:28 +13:00
|
|
|
const { createLinkView } = require("../../db/linkedRows")
|
2020-10-09 22:00:57 +13:00
|
|
|
const { join } = require("../../utilities/centralPath")
|
2020-09-29 05:04:08 +13:00
|
|
|
const { downloadTemplate } = require("../../utilities/templates")
|
2020-10-29 09:35:06 +13:00
|
|
|
const { generateAppID } = require("../../db/utils")
|
2020-05-15 02:12:30 +12:00
|
|
|
|
2020-04-21 03:17:11 +12:00
|
|
|
exports.create = async function(ctx) {
|
2020-05-07 21:53:34 +12:00
|
|
|
const instanceName = ctx.request.body.name
|
2020-09-26 01:47:42 +12:00
|
|
|
const template = ctx.request.body.template
|
2020-10-29 09:35:06 +13:00
|
|
|
const instanceId = generateAppID()
|
2020-06-11 08:39:30 +12:00
|
|
|
|
2020-05-12 03:14:31 +12:00
|
|
|
const db = new CouchDB(instanceId)
|
2020-04-24 01:37:08 +12:00
|
|
|
await db.put({
|
|
|
|
_id: "_design/database",
|
2020-10-03 02:49:23 +13:00
|
|
|
// view collation information, read before writing any complex views:
|
|
|
|
// https://docs.couchdb.org/en/master/ddocs/views/collation.html#collation-specification
|
2020-10-03 01:04:44 +13:00
|
|
|
views: {},
|
2020-05-07 21:53:34 +12:00
|
|
|
})
|
2020-10-10 07:10:28 +13:00
|
|
|
// add view for linked rows
|
2020-09-30 04:40:59 +13:00
|
|
|
await createLinkView(instanceId)
|
2020-04-21 03:17:11 +12:00
|
|
|
|
2020-09-26 01:47:42 +12:00
|
|
|
// replicate the template data to the instance DB
|
|
|
|
if (template) {
|
2020-09-29 05:04:08 +13:00
|
|
|
const templatePath = await downloadTemplate(...template.key.split("/"))
|
2020-10-07 12:24:56 +13:00
|
|
|
const dbDumpReadStream = fs.createReadStream(
|
|
|
|
join(templatePath, "db", "dump.txt")
|
|
|
|
)
|
2020-09-26 01:47:42 +12:00
|
|
|
const { ok } = await db.load(dbDumpReadStream)
|
|
|
|
if (!ok) {
|
|
|
|
ctx.throw(500, "Error loading database dump from template.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-15 02:12:30 +12:00
|
|
|
ctx.status = 200
|
|
|
|
ctx.message = `Instance Database ${instanceName} successfully provisioned.`
|
2020-10-29 09:35:06 +13:00
|
|
|
ctx.body = { _id: instanceId, name: instanceName }
|
2020-05-07 21:53:34 +12:00
|
|
|
}
|
2020-04-21 03:17:11 +12:00
|
|
|
|
|
|
|
exports.destroy = async function(ctx) {
|
2020-05-07 21:53:34 +12:00
|
|
|
const db = new CouchDB(ctx.params.instanceId)
|
|
|
|
await db.destroy()
|
2020-04-21 03:17:11 +12:00
|
|
|
|
2020-05-15 02:12:30 +12:00
|
|
|
ctx.status = 200
|
|
|
|
ctx.message = `Instance Database ${ctx.params.instanceId} successfully destroyed.`
|
2020-05-07 21:53:34 +12:00
|
|
|
}
|