UNPKG

kitejs

Version:

the rpc framework Kite for Node.js

104 lines (103 loc) 3.59 kB
"use strict"; exports.__esModule = true; var protocol_1 = require("./protocol/protocol"); var Debug = require("debug"); var NConsul = require("consul"); var lookup_1 = require("./consul/lookup"); var util_1 = require("./util"); var debug = Debug('consul'); var Consul = /** @class */ (function () { function Consul() { this.useCheckEnv = true; } Consul.prototype.get = function (serAddress, service, callback, env, idc, action, requestOptions) { if (env === void 0) { env = 'prod'; } if (!service) { return callback(new Error('unknown service name.'), null); } if (typeof env !== 'string') { this.useCheckEnv = false; } debug("start_request host: " + serAddress.getHost + " port: " + serAddress.getPort()); this.initOptions(serAddress, service, env, idc); if (action === 'catelog') { this.requestWithCatelog(callback); } else { this.requestWithLookup(requestOptions, callback); } }; Consul.prototype.initOptions = function (serAddress, service, env, idc) { if (env === void 0) { env = 'prod'; } this.options = { address: serAddress, service: service, env: env, idc: idc }; }; Consul.prototype.requestWithCatelog = function (callback) { var consul = NConsul({ host: this.options.address.getHost(), port: this.options.address.getPort() }); var __this = this; consul.catalog.service.nodes({ service: __this.options.service }, function (err, nodes) { if (err) return callback(err); var hosts = []; nodes.forEach(function (node) { if (__this.useCheckEnv && !__this.checkEnv(node.ServiceTags, __this.options.env)) { return; } hosts.push(new protocol_1.Address(node.Address || node.ServiceAddress, node.ServicePort)); }); callback(null, hosts); }); }; Consul.prototype.requestWithLookup = function (requestOptions, callback) { var debug = this.options.env !== 'prod'; var lookup = new lookup_1.Lookup({ debug: debug }); var __this = this; lookup.request(util_1.assign({ service: this.options.service, host: this.options.address.host, port: this.options.address.port }, requestOptions || {}), function (err, nodes) { if (err) { callback(err); return; } var hosts = []; nodes.forEach(function (node) { if (__this.useCheckEnv && node.Tags && node.Tags.env) { if (node.Tags.env !== __this.options.env) { return; } } hosts.push(new protocol_1.Address(node.Host, node.Port)); }); callback(null, hosts); }); }; /** * tags maybe is null, @TODO */ Consul.prototype.checkEnv = function (tags, env) { if (Array.isArray(tags)) { for (var i = 0; i < tags.length; i++) { var tag = tags[i]; if (tag.indexOf('env:') === 0 && tag === ('env:' + env)) { return true; } } return false; } return true; }; return Consul; }()); exports.Consul = Consul; exports.consul = new Consul();