2021-04-22 05:15:57 +12:00
|
|
|
const { generateTemplateID, getTemplateParams, StaticDatabases } = require("@budibase/auth").db
|
|
|
|
const { CouchDB } = require("../../../db")
|
|
|
|
const { TemplatePurposePretty } = require("../../../constants")
|
2021-04-22 03:42:44 +12:00
|
|
|
|
2021-04-22 05:15:57 +12:00
|
|
|
const GLOBAL_DB = StaticDatabases.GLOBAL.name
|
|
|
|
const GLOBAL_OWNER = "global"
|
|
|
|
|
|
|
|
async function getTemplates({ ownerId, type, id } = {}) {
|
|
|
|
const db = new CouchDB(GLOBAL_DB)
|
|
|
|
const response = await db.allDocs(
|
|
|
|
getTemplateParams(ownerId, id, {
|
|
|
|
include_docs: true,
|
|
|
|
})
|
|
|
|
)
|
|
|
|
let templates = response.rows.map(row => row.doc)
|
|
|
|
if (type) {
|
|
|
|
templates = templates.filter(template => template.type === type)
|
|
|
|
}
|
|
|
|
return templates
|
|
|
|
}
|
2021-04-22 03:42:44 +12:00
|
|
|
|
2021-04-22 03:46:51 +12:00
|
|
|
exports.save = async ctx => {
|
2021-04-22 05:15:57 +12:00
|
|
|
const db = new CouchDB(GLOBAL_DB)
|
|
|
|
const type = ctx.params.type
|
|
|
|
let template = ctx.request.body
|
|
|
|
if (!template.ownerId) {
|
|
|
|
template.ownerId = GLOBAL_OWNER
|
|
|
|
}
|
|
|
|
if (!template._id) {
|
|
|
|
template._id = generateTemplateID(template.ownerId)
|
|
|
|
}
|
|
|
|
|
|
|
|
const response = await db.put({
|
|
|
|
...template,
|
|
|
|
type,
|
|
|
|
})
|
|
|
|
ctx.body = {
|
|
|
|
...template,
|
|
|
|
_rev: response.rev,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.definitions = async ctx => {
|
|
|
|
ctx.body = {
|
|
|
|
purpose: TemplatePurposePretty
|
|
|
|
}
|
2021-04-22 03:42:44 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
exports.fetch = async ctx => {
|
2021-04-22 05:15:57 +12:00
|
|
|
ctx.body = await getTemplates()
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.fetchByType = async ctx => {
|
|
|
|
ctx.body = await getTemplates({
|
|
|
|
type: ctx.params.type,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
exports.fetchByOwner = async ctx => {
|
|
|
|
ctx.body = await getTemplates({
|
|
|
|
ownerId: ctx.params.ownerId,
|
|
|
|
})
|
2021-04-22 03:42:44 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
exports.find = async ctx => {
|
2021-04-22 05:15:57 +12:00
|
|
|
ctx.body = await getTemplates({
|
|
|
|
id: ctx.params.id,
|
|
|
|
})
|
2021-04-22 03:42:44 +12:00
|
|
|
}
|
|
|
|
|
|
|
|
exports.destroy = async ctx => {
|
2021-04-22 05:15:57 +12:00
|
|
|
// TODO
|
|
|
|
const db = new CouchDB(GLOBAL_DB)
|
2021-04-22 03:46:51 +12:00
|
|
|
ctx.body = {}
|
2021-04-22 03:42:44 +12:00
|
|
|
}
|