UNPKG

@betit/orion

Version:

Pluggable microservice framework

68 lines (67 loc) 2.05 kB
"use strict"; const client_1 = require('../client'); 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 extends client_1.default { /** * Create new service. */ constructor(name, options = {}) { super(options); this.name = name; this.options = options; this.id = utils_1.generateId(); } /** * 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); } /** * Service name and id. */ toString() { return `${this.name}-${this.id}`; } } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Service;