UNPKG

@creditkarma/thrift-client

Version:

Thrift client library for NodeJS written in TypeScript.

95 lines 3.78 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TcpConnection = void 0; const thrift_server_core_1 = require("@creditkarma/thrift-server-core"); const pool_1 = require("./pool"); const logger_1 = require("../logger"); const utils_1 = require("./utils"); class TcpConnection extends thrift_server_core_1.ThriftConnection { constructor({ hostName, port, timeout = 5000, transport = 'buffered', protocol = 'binary', logger = logger_1.defaultLogger, pool, }) { super((0, thrift_server_core_1.getTransport)(transport), (0, thrift_server_core_1.getProtocol)(protocol)); this.hostName = hostName; this.port = port; this.filters = []; this.logger = logger; this.pool = (0, pool_1.createPool)({ port, hostName, timeout, }, this.logger, pool || {}); } register(...filters) { filters.forEach((next) => { this.filters.push({ methods: next.methods || [], handler: next.handler, }); }); } send(dataToSend, context = {}) { const requestMethod = (0, thrift_server_core_1.readThriftMethod)(dataToSend, this.Transport, this.Protocol); const handlers = this.handlersForMethod(requestMethod); const thriftRequest = { data: dataToSend, methodName: requestMethod, uri: `${this.hostName}:${this.port}`, context, }; const applyHandlers = (currentRequest, [head, ...tail]) => { if (head === undefined) { return this.write(currentRequest.data, currentRequest.context).catch((err) => { return Promise.reject(err); }); } else { return head(currentRequest, (nextData, nextContext) => { return applyHandlers({ data: nextData || currentRequest.data, methodName: currentRequest.methodName, uri: currentRequest.uri, context: nextContext || currentRequest.context, }, tail).catch((err) => { return Promise.reject(err); }); }); } }; return applyHandlers(thriftRequest, handlers).then((res) => { return res.body; }); } destory() { this.logger(['warn', 'TcpConnection'], 'Destroying TCP connection'); return this.pool.drain().then(() => { return this.pool.clear(); }); } write(dataToWrite, options) { return this.pool.acquire().then((connection) => { return connection .send(dataToWrite, this.Transport, this.Protocol) .then((response) => { this.pool.release(connection); return { statusCode: 200, headers: {}, body: response, }; }, (err) => { this.logger(['error', 'TcpConnection'], `Error sending Thrift request: ${err.message}`); this.pool.release(connection); return Promise.reject(err); }); }, (err) => { this.logger(['error', 'TcpConnection'], `Unable to acquire connection for client: ${err.message}`); throw new Error(`Unable to acquire connection for thrift client`); }); } handlersForMethod(name) { return this.filters .filter((0, utils_1.filterByMethod)(name)) .map((filter) => filter.handler); } } exports.TcpConnection = TcpConnection; //# sourceMappingURL=TcpConnection.js.map