2020-05-28 21:20:03 +02:00
|
|
|
const EventEmitter = require("events").EventEmitter
|
2020-06-01 11:41:28 +02:00
|
|
|
const CouchDB = require("../db")
|
2020-06-01 22:26:32 +02:00
|
|
|
const { Orchestrator, serverStrategy } = require("./workflow")
|
2020-05-24 23:54:08 +02:00
|
|
|
|
2020-05-31 18:12:52 +02:00
|
|
|
const emitter = new EventEmitter()
|
|
|
|
|
2020-06-01 17:22:13 +02:00
|
|
|
async function executeRelevantWorkflows(event, eventType) {
|
|
|
|
const db = new CouchDB(event.instanceId)
|
2020-05-31 18:12:52 +02:00
|
|
|
const workflowsToTrigger = await db.query("database/by_workflow_trigger", {
|
2020-06-01 17:22:13 +02:00
|
|
|
key: [eventType],
|
2020-06-01 22:26:32 +02:00
|
|
|
include_docs: true,
|
2020-05-31 18:12:52 +02:00
|
|
|
})
|
|
|
|
|
2020-06-01 17:22:13 +02:00
|
|
|
const workflows = workflowsToTrigger.rows.map(wf => wf.doc)
|
2020-05-31 18:12:52 +02:00
|
|
|
|
2020-06-01 17:22:13 +02:00
|
|
|
// Create orchestrator
|
|
|
|
const workflowOrchestrator = new Orchestrator()
|
|
|
|
workflowOrchestrator.strategy = serverStrategy
|
2020-05-31 18:12:52 +02:00
|
|
|
|
2020-06-01 17:22:13 +02:00
|
|
|
for (let workflow of workflows) {
|
2020-08-05 16:18:28 +02:00
|
|
|
workflowOrchestrator.execute(workflow, event)
|
2020-05-31 18:12:52 +02:00
|
|
|
}
|
2020-06-01 17:22:13 +02:00
|
|
|
}
|
|
|
|
|
2020-06-04 14:55:52 +02:00
|
|
|
emitter.on("record:save", async function(event) {
|
2020-06-01 22:26:32 +02:00
|
|
|
await executeRelevantWorkflows(event, "record:save")
|
2020-05-31 18:12:52 +02:00
|
|
|
})
|
|
|
|
|
2020-06-01 11:41:28 +02:00
|
|
|
emitter.on("record:delete", async function(event) {
|
2020-06-01 22:26:32 +02:00
|
|
|
await executeRelevantWorkflows(event, "record:delete")
|
2020-05-31 18:12:52 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
module.exports = emitter
|