const { EventEmitter } = require('eventemitter3')
const reusify = require('reusify')
function EventDriven() {
this.reusify = reusify(EventEmitter).get()
Object.defineProperties(this.reusify, {
nextTick: {
value: process.nextTick,
writable: true,
enumerable: true
},
parse: {
value: JSON.parse,
writable: true,
enumerable: true
},
stringify: {
value: JSON.stringify,
writable: true,
enumerable: true
},
promise: {
value: Promise,
writable: true,
enumerable: true
},
eventName: {
value: undefined,
writable: true,
enumerable: true
},
data: {
value: undefined,
writable: true,
enumerable: true
},
response: {
value: undefined,
writable: true,
enumerable: true
}
})
}
EventDriven.prototype.pub = function (eventName, data) {
this.reusify.eventName = eventName
this.reusify.data = data
if (this.reusify.data !== undefined) {
this.reusify.nextTick(() => this.reusify.emit(this.reusify.eventName, this.reusify.stringify({ data: this.reusify.data })))
return Promise.resolve(this.reusify)
}
}
EventDriven.prototype.sub = function (eventName) {
let self = this
self.reusify.response = new self.reusify.promise(function (resolve, reject) {
self.reusify.eventName = eventName
self.reusify.on(self.reusify.eventName, function (data) {
self.reusify.data = data
self.reusify.response = self.reusify.parse(self.reusify.data)
resolve(self.reusify.response.data)
})
if (self.reusify.response !== (undefined && null)) {
self.reusify.nextTick(() => self.reusify.off(self.reusify.eventName))
self.reusify.nextTick(() => {
self.reusify.eventName = undefined
self.reusify.data = undefined
self.reusify.response = undefined
})
}
})
return self.reusify.response
}
exports.event = new EventDriven()