@glandjs/core
Version:
Glands is a web framework for Node.js (@core)
58 lines (57 loc) • 1.83 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Context = void 0;
class Context {
constructor(broker) {
this.broker = broker;
this._state = {};
}
get state() {
return this._state;
}
set state(data) {
this._state = Object.assign(this._state, data);
}
emit(event, payload, options) {
const channels = this.state?.channel || [{}];
const brokerId = this.state?.brokerId;
const listener = event?.includes(':') ? event?.split(/:(.+)/) : event;
for (const channel of channels) {
if (channel.event === listener[1]) {
this.broker.emitTo(brokerId, channel.fullEvent, payload, options);
return this;
}
}
return this;
}
on(event, listener, options) {
const result = this.broker.on(event, listener, options);
if (result instanceof Promise) {
return result;
}
return this;
}
off(event, listener) {
this.broker.off(event, listener);
return this;
}
once(event, listener, options) {
const result = this.broker.once(event, listener, options);
if (result instanceof Promise) {
return result;
}
return this;
}
call(event, data, strategy) {
const channels = this.state?.channel || [{}];
const brokerId = this.state?.brokerId;
const listener = event?.includes(':') ? event?.split(/:(.+)/) : event;
for (const channel of channels) {
if (channel.event === listener[1]) {
return this.broker.callTo(brokerId, channel.fullEvent, data, strategy);
}
}
return strategy === 'all' ? [] : undefined;
}
}
exports.Context = Context;