UNPKG

@betit/orion

Version:

Pluggable microservice framework

83 lines (82 loc) 2.31 kB
"use strict"; const nats = require('nats'); const utils_1 = require('../utils'); const debug = utils_1.debugLog('orion:transport:nats'); /** * NATS transport. */ class NatsTransport { /** * Create new NATS transport. */ constructor(options) { this.options = options; this.options = Object.assign({ url: process.env.NATS || 'nats://localhost:4222', encoding: 'binary' }, options); this.client = nats.connect(this.options); } /** * Transport listen. */ listen(callback) { this.client.flush(callback); } /** * Publish to a topic. */ publish(topic, message) { this.client.publish(topic, message); } /** * Subscribe to a topic. */ subscribe(topic, group, callback) { return this.client.subscribe(topic, { queue: group }, callback); } /** * Unsubscribe from a topic. */ unsubscribe(sid, max) { this.client.unsubscribe(sid, max); } /** * Transport handle. */ handle(route, group, callback) { debug('register handler:', route); this.client.subscribe(route, { queue: group }, (req, replyTo) => { debug('incoming request:', req, replyTo); callback(req, res => { debug('sending response:', replyTo, res); this.client.publish(replyTo, res); }); }); } /** * Client request. * Nats client implements this pattern out of the box. * Publish a request with an implicit inbox listener as the response. * This should be treated as a subscription. */ request(route, payload, callback, timeout = 1000) { debug('sending request:', route); const sid = this.client.request(route, payload, { max: 1 }, response => { debug('got response:', response); callback(response); }); this.client.timeout(sid, timeout, 1, () => { debug('request timeout:', route); callback(new Error(`Transport timeout: ${route}`)); }); } /** * Close connection. */ close() { this.client.close(); } } Object.defineProperty(exports, "__esModule", { value: true }); exports.default = NatsTransport;