1
0
Fork 0
mirror of synced 2024-10-01 09:38:55 +13:00
budibase/packages/server/src/api/controllers/instance.js

64 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-05-07 21:53:34 +12:00
const CouchDB = require("../../db")
exports.create = async function(ctx) {
2020-05-07 21:53:34 +12:00
const instanceName = ctx.request.body.name
2020-05-07 21:53:34 +12:00
const { clientId, applicationId } = ctx.params
const db = new CouchDB(instanceName)
await db.put({
_id: "_design/database",
metadata: {
clientId,
2020-05-07 21:53:34 +12:00
applicationId,
},
2020-05-07 21:53:34 +12:00
views: {
by_username: {
map: function(doc) {
if (doc.type === "user") {
2020-05-07 21:53:34 +12:00
emit([doc.username], doc._id)
}
2020-05-07 21:53:34 +12:00
}.toString(),
},
2020-05-07 21:53:34 +12:00
by_type: {
map: function(doc) {
emit([doc.type], doc._id)
}.toString(),
},
},
})
// Add the new instance under the app clientDB
const clientDatabaseId = `client-${clientId}`
2020-05-07 21:53:34 +12:00
const clientDb = new CouchDB(clientDatabaseId)
const budibaseApp = await clientDb.get(applicationId)
const instance = { id: instanceName, name: instanceName }
budibaseApp.instances.push(instance)
await clientDb.put(budibaseApp)
ctx.body = {
message: `Instance Database ${instanceName} successfully provisioned.`,
status: 200,
2020-05-07 21:53:34 +12:00
instance,
}
2020-05-07 21:53:34 +12:00
}
exports.destroy = async function(ctx) {
2020-05-07 21:53:34 +12:00
const db = new CouchDB(ctx.params.instanceId)
const designDoc = await db.get("_design/database")
await db.destroy()
// remove instance from client application document
2020-05-07 21:53:34 +12:00
const { metadata } = designDoc
const clientDb = new CouchDB(metadata.clientId)
const budibaseApp = await clientDb.get(metadata.applicationId)
budibaseApp.instances = budibaseApp.instances.filter(
instance => instance !== ctx.params.instanceId
)
2020-05-08 00:52:24 +12:00
await clientDb.put(budibaseApp)
ctx.body = {
message: `Instance Database ${ctx.params.instanceId} successfully destroyed.`,
2020-05-07 21:53:34 +12:00
status: 200,
}
2020-05-07 21:53:34 +12:00
}