@glandjs/core
Version:
Glands is a web framework for Node.js (@core)
66 lines (65 loc) • 2.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApplicationBinder = void 0;
class ApplicationBinder {
constructor(explorer, broker, logger) {
this.explorer = explorer;
this.broker = broker;
this.map = new Map();
this.logger = logger?.child('Binder');
}
bind() {
this.logger?.debug('Starting controller/channel binding...');
this.bindChannel();
this.bindControllers();
this.logger?.info('- Done.');
}
bindChannel() {
const channels = this.explorer.exploreChannels();
for (const channel of channels) {
const { instance, event, namespace, target } = channel;
const fullEvent = `gland:define:channel:${namespace}:${event}`;
this.broker.on(fullEvent, async (...args) => {
this.logger?.debug(`[Broker] Invoking channel handler [${namespace}:${event}]`);
return await target.apply(instance, args);
});
this.map.set(fullEvent, {
namespace,
event,
fullEvent,
});
this.logger?.info(`Channel bound: namespace="${namespace}", event="${event}"`);
}
}
bindControllers() {
const controllers = this.explorer.exploreControllers();
for (const controller of controllers) {
const { method, route, controller: ctr } = controller;
const fullPath = this.combinePaths(ctr.path, route);
this.logger?.debug(`Binding route [${method.toUpperCase()} ${fullPath}] to method "${ctr.methodName}"`);
this.broker.broadcast('gland:define:route', {
path: route,
meta: {
method: ctr.methodName,
path: fullPath,
},
method,
action: (ctx) => {
this.logger?.debug(`[Broker] Executing action for ${method.toUpperCase()} ${fullPath}`);
ctx.state = ctx._state || {};
ctx.state.brokerId = this.broker.id;
ctx.state.channel = Array.from(this.map.values());
return ctr.target(ctx);
},
});
this.logger?.info(`Controller route bound: [${method.toUpperCase()}] ${fullPath}`);
}
}
combinePaths(basePath, methodPath) {
basePath = basePath.startsWith('/') ? basePath : `/${basePath}`;
basePath = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
methodPath = methodPath.startsWith('/') ? methodPath : `/${methodPath}`;
return `${basePath}${methodPath}`;
}
}
exports.ApplicationBinder = ApplicationBinder;