embark-area-51/lib/core/processes/eventsWrapper.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

const uuid = require('uuid/v1');
2018-07-27 21:33:50 +00:00
const constants = require('../../constants');
2018-05-15 21:08:08 +00:00
class Events {
2018-05-16 16:03:39 +00:00
/**
* Constructs an event wrapper for processes.
* Handles sending an event message to the parent process and waiting for its response
* No need to create an instance of eventsWrapper for your own process, just extend ProcessWrapper
* Then, you an use `this.events.[on|request]` with the usual parameters you would use
*/
2018-05-15 21:08:08 +00:00
constructor() {
this.subscribedEvents = {};
this.listenToParentProcess();
}
listenToParentProcess() {
process.on('message', (msg) => {
if (!msg.event || msg.event !== constants.process.events.response) {
return;
}
if (!this.subscribedEvents[msg.eventId]) {
return;
}
this.subscribedEvents[msg.eventId](msg.result);
});
}
sendEvent() {
const eventType = arguments[0];
const requestName = arguments[1];
let args = [].slice.call(arguments, 2);
const eventId = uuid();
this.subscribedEvents[eventId] = args[args.length - 1];
2018-05-15 21:08:08 +00:00
args = args.splice(0, args.length - 2);
process.send({
event: eventType,
requestName,
args,
eventId: eventId
2018-05-15 21:08:08 +00:00
});
}
on() {
this.sendEvent(constants.process.events.on, ...arguments);
}
request() {
this.sendEvent(constants.process.events.request, ...arguments);
}
}
module.exports = Events;