2020-02-03 10:24:25 +01:00
|
|
|
import { join } from "lodash"
|
|
|
|
import { map } from "lodash/fp"
|
|
|
|
import { appDefinitionFile } from "../common"
|
|
|
|
import { validateTriggers, validateActions } from "./validate"
|
|
|
|
import { apiWrapper } from "../common/apiWrapper"
|
|
|
|
import { events } from "../common/events"
|
|
|
|
import { permission } from "../authApi/permissions"
|
|
|
|
import { BadRequestError } from "../common/errors"
|
2019-07-15 08:12:52 +02:00
|
|
|
|
2020-02-03 10:24:25 +01:00
|
|
|
export const saveActionsAndTriggers = app => async (actions, triggers) =>
|
|
|
|
apiWrapper(
|
|
|
|
app,
|
|
|
|
events.templateApi.saveActionsAndTriggers,
|
|
|
|
permission.writeTemplates.isAuthorized,
|
|
|
|
{ actions, triggers },
|
|
|
|
_saveActionsAndTriggers,
|
|
|
|
app.datastore,
|
|
|
|
actions,
|
|
|
|
triggers
|
|
|
|
)
|
2019-07-15 08:12:52 +02:00
|
|
|
|
|
|
|
export const _saveActionsAndTriggers = async (datastore, actions, triggers) => {
|
|
|
|
if (await datastore.exists(appDefinitionFile)) {
|
2020-02-03 10:24:25 +01:00
|
|
|
const appDefinition = await datastore.loadJson(appDefinitionFile)
|
|
|
|
appDefinition.actions = actions
|
|
|
|
appDefinition.triggers = triggers
|
2019-07-15 08:12:52 +02:00
|
|
|
|
2020-02-03 10:24:25 +01:00
|
|
|
const actionValidErrs = map(e => e.error)(validateActions(actions))
|
2019-07-15 08:12:52 +02:00
|
|
|
|
|
|
|
if (actionValidErrs.length > 0) {
|
2020-02-03 10:24:25 +01:00
|
|
|
throw new BadRequestError(
|
|
|
|
`Actions are invalid: ${join(actionValidErrs, ", ")}`
|
|
|
|
)
|
2019-07-15 08:12:52 +02:00
|
|
|
}
|
|
|
|
|
2020-02-03 10:24:25 +01:00
|
|
|
const triggerValidErrs = map(e => e.error)(
|
|
|
|
validateTriggers(triggers, actions)
|
|
|
|
)
|
2019-07-15 08:12:52 +02:00
|
|
|
|
|
|
|
if (triggerValidErrs.length > 0) {
|
2020-02-03 10:24:25 +01:00
|
|
|
throw new BadRequestError(
|
|
|
|
`Triggers are invalid: ${join(triggerValidErrs, ", ")}`
|
|
|
|
)
|
2019-07-15 08:12:52 +02:00
|
|
|
}
|
|
|
|
|
2020-02-03 10:24:25 +01:00
|
|
|
await datastore.updateJson(appDefinitionFile, appDefinition)
|
2019-07-15 08:12:52 +02:00
|
|
|
} else {
|
2020-02-03 10:24:25 +01:00
|
|
|
throw new BadRequestError(
|
|
|
|
"Cannot save actions: Application definition does not exist"
|
|
|
|
)
|
2019-07-15 08:12:52 +02:00
|
|
|
}
|
2020-02-03 10:24:25 +01:00
|
|
|
}
|