budibase/packages/server/src/events/AutomationEmitter.ts

94 lines
2.0 KiB
TypeScript
Raw Normal View History

import { rowEmission, tableEmission } from "./utils"
import mainEmitter from "./index"
import env from "../environment"
2024-10-24 13:51:44 +02:00
import {
Table,
Row,
DocumentType,
App,
ContextEmitter,
EventType,
UserBindings,
} from "@budibase/types"
import { context } from "@budibase/backend-core"
2024-01-23 11:10:38 +01:00
const MAX_AUTOMATIONS_ALLOWED = 5
2024-10-24 13:07:13 +02:00
class AutomationEmitter implements ContextEmitter {
chainCount: number
metadata: { automationChainCount: number }
constructor(chainCount: number) {
this.chainCount = chainCount
this.metadata = {
automationChainCount: chainCount,
}
}
async getMaxAutomationChain() {
const db = context.getAppDB()
const appMetadata = await db.get<App>(DocumentType.APP_METADATA)
let chainAutomations = appMetadata?.automations?.chainAutomations
if (chainAutomations === true) {
2024-01-23 11:10:38 +01:00
return MAX_AUTOMATIONS_ALLOWED
} else if (chainAutomations === undefined && env.SELF_HOSTED) {
2024-01-23 11:10:38 +01:00
return MAX_AUTOMATIONS_ALLOWED
} else {
return 0
}
}
2024-10-22 15:36:15 +02:00
async emitRow({
eventName,
appId,
row,
table,
2024-10-24 13:51:44 +02:00
oldRow,
user,
2024-10-22 15:36:15 +02:00
}: {
2024-10-24 13:51:44 +02:00
eventName: EventType.ROW_SAVE | EventType.ROW_DELETE | EventType.ROW_UPDATE
2024-10-22 15:36:15 +02:00
appId: string
row: Row
table?: Table
2024-10-24 13:51:44 +02:00
oldRow?: Row
user: UserBindings
2024-10-22 15:36:15 +02:00
}) {
let MAX_AUTOMATION_CHAIN = await this.getMaxAutomationChain()
// don't emit even if we've reached max automation chain
if (this.chainCount >= MAX_AUTOMATION_CHAIN) {
return
}
rowEmission({
emitter: mainEmitter,
eventName,
appId,
row,
table,
2024-10-24 13:51:44 +02:00
oldRow,
metadata: this.metadata,
2024-10-24 13:51:44 +02:00
user,
})
}
async emitTable(eventName: string, appId: string, table?: Table) {
let MAX_AUTOMATION_CHAIN = await this.getMaxAutomationChain()
// don't emit even if we've reached max automation chain
if (this.chainCount >= MAX_AUTOMATION_CHAIN) {
return
}
tableEmission({
emitter: mainEmitter,
eventName,
appId,
table,
metadata: this.metadata,
})
}
}
export default AutomationEmitter