ensl_gathers/lib/gather/gather_singleton.js

72 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-09-14 16:50:00 +00:00
"use strict"
let Gather = require("./gather");
let gatherCallbacks = {};
2015-09-27 11:55:00 +00:00
let archiveUpdatedCallback = () => {};
2015-09-26 16:03:01 +00:00
let winston = require("winston");
let mongoose = require("mongoose");
let ArchivedGather = mongoose.model("ArchivedGather");
2015-09-14 16:50:00 +00:00
// Register initial callback to reset gather when state is `done`
gatherCallbacks['onDone'] = [function () {
rotateGather();
}];
let newGather = () => {
return SingletonClass.current = Gather({
onEvent: function () {
2015-10-02 14:53:11 +00:00
gatherCallbacks['onEvent'].forEach(cb => {
cb.apply(this, [].slice.call(arguments))
});
2015-09-14 16:50:00 +00:00
},
onDone: function () {
2015-10-02 14:53:11 +00:00
gatherCallbacks['onDone'].forEach(cb => {
cb.apply(this, [].slice.call(arguments))
});
2015-09-14 16:50:00 +00:00
}
});
};
2015-09-26 16:03:01 +00:00
let archiveGather = gather => {
ArchivedGather.archive(gather, (error, result) => {
2015-09-27 11:55:00 +00:00
if (error) return winston.error(error);
if (archiveUpdatedCallback
&& typeof archiveUpdatedCallback === 'function') {
archiveUpdatedCallback();
}
2015-09-26 16:03:01 +00:00
});
};
2015-09-14 16:50:00 +00:00
let rotateGather = () => {
2015-09-26 16:03:01 +00:00
if (SingletonClass.current) {
SingletonClass.previous = SingletonClass.current;
archiveGather(SingletonClass.previous);
}
2015-09-14 16:50:00 +00:00
return newGather();
}
let SingletonClass = {
registerCallback: function (type, method) {
if (gatherCallbacks[type]) {
gatherCallbacks[type].push(method);
} else {
gatherCallbacks[type] = [method];
}
},
2015-09-27 11:55:00 +00:00
onArchiveUpdate: function (callback) {
archiveUpdatedCallback = callback;
},
2015-09-14 16:50:00 +00:00
restart: function () {
this.previousGather = undefined;
this.current = undefined;
return newGather();
},
reset: function () {
return newGather();
},
current: Gather(),
previous: undefined
};
module.exports = SingletonClass;