decision
Version:
Decision System Based on Event System and Alleyway Grammer
81 lines (70 loc) • 2.22 kB
JavaScript
/********************************************************************
*
* Decision System Based on Event System and Alleyway Grammer
*
********************************************************************/
import decisionChain from "./decisionChain";
import Alleyway from "alleyway";
import makeDecisions from "./makeDecisions";
import Marmoset from "marmoset";
let makeAction = (name, action, marmoset) => async(...y) => {
let res = await action.apply(undefined, y);
// action done
marmoset.trigger("system", "actionDone", {
name,
res: res
});
return res;
}
let getPrintEventData = (data) => {
if (!data || typeof data !== "object") return data;
let res = "";
for (let name in data) {
res += name + ":" + data[name] + " ; ";
}
return res;
}
export default (opts) => {
let actionMap = {};
let alleyway = Alleyway(actionMap);
let marmoset = Marmoset({
logEvent: opts && opts.logEvent
});
let loadActions = (config) => {
for (let name in config) {
let action = config[name];
// wrap action
actionMap[name] = makeAction(name, action, marmoset);
// specify actionDone
// actionDone>${ name }
marmoset.createEventByRoute((m) => {
m().happen("system", "actionDone").
inCase(e => e.data.name === name).
trigger("system", name).data(e => e.data.res);
});
}
// after loading actions
alleyway = Alleyway(actionMap);
}
let loadDecisions = (decision) => {
let chain = decisionChain(marmoset, alleyway);
let factory = chain.createFactory();
decision(factory);
makeDecisions(chain.getDecisions(), marmoset, alleyway)
}
let loadEvents = (config) => {
for (let channel in config) {
let paths = config[channel];
for (let i = 0; i < paths.length; i++) {
let watch = paths[i];
watch(marmoset, channel);
}
}
}
return {
loadEvents,
loadActions,
loadDecisions,
marmoset // export event system
}
}