I’m working on a rule engine in JavaScript that allows users to schedule when rules are checked. I’m using Agenda to the scheduling.
Ideally I want to define jobs with variable names so then whenever a rule is updated all I need is the id of the rule to see if an existing job for that rule already exsists. i.e. like “Execute Rule {id}”. But it seems like Agenda doesn’t recognize a matching job name unless it has the exact same name. How do I work around this ?
agenda.define('execute rule', async job => {
console.log("running job");
const { ruleMongObj } = job.attrs.data; // Accessing the job data attributes -- THIS IS THE FULL MONG OBJ
const engine = new Engine();
// Add the rule to the engine
engine.addRule(rule.ruleMongObj);
try {
// Fetch facts for the user (subscriberId) from the backend
const { subscriberId } = ruleMongObj;
const factsResponse = await axios.get(`${backendBaseUrl}/fact/user/${subscriberId}/facts`);
const facts = factsResponse.data;
// Run the engine with the fetched facts
const events = await engine.run(facts);
if (events.length > 0) {
events.forEach(event => {
console.log(`Event triggered: ${event.type}`, event.params);
});
} else {
console.log(`Rule ${rule._id} executed false`);
}
} catch (err) {
console.error('Error running rule engine:', err);
}
});
All I can think of right now is to create the job for the rule and then give the rule object in my backend a key to the job’s id so that every time that rule is updated we know if an existing job exists but I’d like a cleaner solution if possible.
As a note I am also not entirely sure if I can have the same job run on multiple time intervals? Any guidance on that would also help.
I tried simply passing in “execute rule {id}” which each new job but that doesn’t really work.