UNPKG

@betit/orion

Version:

Pluggable microservice framework

88 lines (87 loc) 2.65 kB
"use strict"; const codec_1 = require('../codec'); const transport_1 = require('../transport'); const utils_1 = require('../utils'); const debug = utils_1.debugLog('orion:client'); /** * Provides an interface to make requests to services. */ class Client { /** * Create new client. */ constructor(options) { this.options = options; this.options = Object.assign({ timeout: 3000 }, options); 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)); } /** * Call service method. * @param {Object} request * @param {Object} [params] * @param {Function} callback */ call(request, callback) { // supports method call without params if (arguments.length === 3) { request = { path: request, params: callback }; callback = arguments[2]; } else if (typeof request === 'string') { request = { path: request }; } let route = request.path; // services registered with names like `service.method` // but we support `/service/method` style calls as well // hence we need to "normalize" the route here. route = route.replace(/\//gi, '.'); if (route.startsWith('.')) { route = route.substring(1); } if (!route) { return callback(new Error('Invalid request path')); } if (this.options.service) { route = `${this.options.service}.${route}`; } debug('calling:', route); const req = this.codec.encode(request); debug('sending request:', request); this.transport.request(route, req, res => { if (res instanceof Error) { callback(res); } else { const response = this.codec.decode(res); debug('got response:', response); callback(response.err, response.res); } }, this.options.timeout); } /** * Close underlying transport connection. */ close() { debug('close'); this.transport.close(); } } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Client;