1
0
Fork 0
mirror of synced 2024-06-16 01:14:48 +12:00
budibase/packages/server/src/api/controllers/application.js

249 lines
6.8 KiB
JavaScript
Raw Normal View History

2020-05-07 21:53:34 +12:00
const CouchDB = require("../../db")
const compileStaticAssets = require("../../utilities/builder/compileStaticAssets")
2020-05-15 02:12:30 +12:00
const env = require("../../environment")
const { existsSync } = require("fs-extra")
2020-06-04 08:23:56 +12:00
const { budibaseAppsDir } = require("../../utilities/budibaseDir")
2020-06-19 03:59:31 +12:00
const setBuilderToken = require("../../utilities/builder/setBuilderToken")
const fs = require("fs-extra")
const { join, resolve } = require("../../utilities/centralPath")
const packageJson = require("../../../package.json")
const { createLinkView } = require("../../db/linkedRows")
const { createRoutingView } = require("../../utilities/routing")
const { downloadTemplate } = require("../../utilities/templates")
const {
generateAppID,
getLayoutParams,
getScreenParams,
generateScreenID,
} = require("../../db/utils")
const {
BUILTIN_ROLE_IDS,
AccessController,
} = require("../../utilities/security/roles")
2020-07-15 08:10:51 +12:00
const {
downloadExtractComponentLibraries,
} = require("../../utilities/createAppPackage")
const { BASE_LAYOUTS } = require("../../constants/layouts")
const {
createHomeScreen,
createLoginScreen,
} = require("../../constants/screens")
const { cloneDeep } = require("lodash/fp")
const { recurseMustache } = require("../../utilities/mustache")
const { getAllApps } = require("../../utilities")
2020-11-26 04:03:19 +13:00
const { USERS_TABLE_SCHEMA } = require("../../constants")
const {
getDeployedApps,
getHostingInfo,
HostingTypes,
} = require("../../utilities/builder/hosting")
2020-04-08 04:25:09 +12:00
// utility function, need to do away with this
async function getLayouts(db) {
return (
await db.allDocs(
getLayoutParams(null, {
include_docs: true,
})
)
).rows.map(row => row.doc)
}
async function getScreens(db) {
return (
await db.allDocs(
getScreenParams(null, {
include_docs: true,
})
)
).rows.map(row => row.doc)
}
function getUserRoleId(ctx) {
return !ctx.user.role || !ctx.user.role._id
? BUILTIN_ROLE_IDS.PUBLIC
: ctx.user.role._id
}
async function getAppUrlIfNotInUse(ctx) {
let url
if (ctx.request.body.url) {
url = encodeURI(ctx.request.body.url)
} else {
url = encodeURI(`${ctx.request.body.name}`)
}
url = `/${url.replace(/\/|\\/g, "")}`.toLowerCase()
const hostingInfo = await getHostingInfo()
if (hostingInfo.type === HostingTypes.CLOUD) {
return url
}
const deployedApps = await getDeployedApps()
if (
deployedApps[url] != null &&
deployedApps[url].appId !== ctx.params.appId
) {
ctx.throw(400, "App name/URL is already in use.")
}
return url
}
async function createInstance(template) {
const appId = generateAppID()
const db = new CouchDB(appId)
await db.put({
_id: "_design/database",
// view collation information, read before writing any complex views:
// https://docs.couchdb.org/en/master/ddocs/views/collation.html#collation-specification
views: {},
})
// add view for linked rows
await createLinkView(appId)
await createRoutingView(appId)
// replicate the template data to the instance DB
if (template) {
const templatePath = await downloadTemplate(...template.key.split("/"))
const dbDumpReadStream = fs.createReadStream(
join(templatePath, "db", "dump.txt")
)
const { ok } = await db.load(dbDumpReadStream)
if (!ok) {
throw "Error loading database dump from template."
}
2020-11-25 03:04:14 +13:00
} else {
// create the users table
2020-11-26 04:03:19 +13:00
await db.put(USERS_TABLE_SCHEMA)
}
return { _id: appId }
}
2020-06-30 03:49:16 +12:00
exports.fetch = async function(ctx) {
ctx.body = await getAllApps()
2020-05-07 21:53:34 +12:00
}
2020-04-08 04:25:09 +12:00
exports.fetchAppDefinition = async function(ctx) {
const db = new CouchDB(ctx.params.appId)
const layouts = await getLayouts(db)
const userRoleId = getUserRoleId(ctx)
const accessController = new AccessController(ctx.params.appId)
const screens = await accessController.checkScreensAccess(
await getScreens(db),
userRoleId
)
ctx.body = {
layouts,
screens,
libraries: ["@budibase/standard-components"],
}
}
2020-06-30 03:49:16 +12:00
exports.fetchAppPackage = async function(ctx) {
const db = new CouchDB(ctx.params.appId)
const application = await db.get(ctx.params.appId)
const [layouts, screens] = await Promise.all([getLayouts(db), getScreens(db)])
ctx.body = {
application,
screens,
layouts,
}
2020-11-03 04:46:08 +13:00
await setBuilderToken(ctx, ctx.params.appId, application.version)
}
2020-06-30 03:49:16 +12:00
exports.create = async function(ctx) {
const url = await getAppUrlIfNotInUse(ctx)
const instance = await createInstance(ctx.request.body.template)
const appId = instance._id
const version = packageJson.version
2020-05-15 02:12:30 +12:00
const newApplication = {
_id: appId,
type: "app",
version: packageJson.version,
componentLibraries: ["@budibase/standard-components"],
name: ctx.request.body.name,
url: url,
2020-09-26 01:47:42 +12:00
template: ctx.request.body.template,
instance: instance,
deployment: {
type: "cloud",
},
2020-04-10 03:53:48 +12:00
}
const instanceDb = new CouchDB(appId)
await instanceDb.put(newApplication)
2020-05-15 02:12:30 +12:00
if (env.NODE_ENV !== "jest") {
const newAppFolder = await createEmptyAppPackage(ctx, newApplication)
await downloadExtractComponentLibraries(newAppFolder)
}
await setBuilderToken(ctx, appId, version)
ctx.status = 200
2020-05-15 02:12:30 +12:00
ctx.body = newApplication
ctx.message = `Application ${ctx.request.body.name} created successfully`
2020-05-07 21:53:34 +12:00
}
2020-06-30 03:49:16 +12:00
exports.update = async function(ctx) {
const url = await getAppUrlIfNotInUse(ctx)
const db = new CouchDB(ctx.params.appId)
const application = await db.get(ctx.params.appId)
const data = ctx.request.body
const newData = { ...application, ...data, url }
const response = await db.put(newData)
data._rev = response.rev
ctx.status = 200
ctx.message = `Application ${application.name} updated successfully.`
ctx.body = response
}
exports.delete = async function(ctx) {
const db = new CouchDB(ctx.params.appId)
const app = await db.get(ctx.params.appId)
const result = await db.destroy()
// remove top level directory
await fs.rmdir(join(budibaseAppsDir(), ctx.params.appId), {
recursive: true,
})
ctx.status = 200
ctx.message = `Application ${app.name} deleted successfully.`
ctx.body = result
}
const createEmptyAppPackage = async (ctx, app) => {
2020-06-04 08:23:56 +12:00
const appsFolder = budibaseAppsDir()
const newAppFolder = resolve(appsFolder, app._id)
const db = new CouchDB(app._id)
2020-10-14 05:02:59 +13:00
if (existsSync(newAppFolder)) {
ctx.throw(400, "App folder already exists for this application")
}
2020-11-06 03:38:44 +13:00
fs.mkdirpSync(newAppFolder)
2020-11-07 02:40:00 +13:00
let screensAndLayouts = []
for (let layout of BASE_LAYOUTS) {
const cloned = cloneDeep(layout)
cloned.title = app.name
screensAndLayouts.push(recurseMustache(cloned, app))
}
2020-11-07 02:40:00 +13:00
const homeScreen = createHomeScreen(app)
homeScreen._id = generateScreenID()
screensAndLayouts.push(homeScreen)
const loginScreen = createLoginScreen(app)
loginScreen._id = generateScreenID()
screensAndLayouts.push(loginScreen)
await db.bulkDocs(screensAndLayouts)
await compileStaticAssets(app._id)
return newAppFolder
}