@betit/orion
Version:
Pluggable microservice framework
86 lines (85 loc) • 2.58 kB
JavaScript
;
const codec_1 = require('../codec');
const transport_1 = require('../transport');
const reply_1 = require('./reply');
const utils_1 = require('../utils');
const debug = utils_1.debugLog('orion:service');
/**
* Provides an interface to create your service and register request handlers.
*/
class Service {
/**
* Create new service.
*/
constructor(name, options = {}) {
this.name = name;
this.options = options;
this.id = utils_1.generateId();
this.codec = this.options.codec || new codec_1.DefaultBinaryCodec();
this.transport = this.options.transport || new transport_1.DefaultTransport();
}
/**
* Publish to a topic.
* @param {any} topic
* @param {Object} message
*/
emit(topic, message) {
debug('emit:', topic);
this.transport.publish(topic, this.codec.encode(message));
}
/**
* Subscribe to a topic.
* @param {string} topic
* @param {Function} callback
*/
on(topic, callback, disableGroup = false) {
const subject = `${this.name}:${topic}`;
debug('on:', subject);
return this.transport.subscribe(subject, disableGroup ? null : this.name, message => {
callback(this.codec.decode(message));
});
}
/**
* Register request handler method.
* @param {string} method
* @param {Function} callback
* @param {string} [prefix]
*/
handle(path, callback, prefix) {
const route = `${prefix || this.name}.${path}`;
debug('register handler:', route);
this.transport.handle(route, this.name, (data, send) => {
const req = this.codec.decode(data);
debug('incoming request:', req);
const reply = new reply_1.default(data => {
debug('sending response:', data.err, data.res);
const response = this.codec.encode(data);
send(response);
});
callback(req, reply.fn());
});
}
/**
* Start listenning on the underlying transport connection.
* @param {Function} callback
*/
listen(callback) {
debug('listen');
this.transport.listen(callback);
}
/**
* Close underlying transport connection.
*/
close() {
debug('close');
this.transport.close();
}
/**
* Service name and id.
*/
toString() {
return `${this.name}-${this.id}`;
}
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Service;