|
| 1 | +/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ |
| 2 | + |
| 3 | +import Promise from 'bluebird'; |
| 4 | + |
| 5 | +import { ApiGatewayManagementApiClient, PostToConnectionCommand } from '@aws-sdk/client-apigatewaymanagementapi'; |
| 6 | +import { NodeHttpHandler } from '@smithy/node-http-handler'; |
| 7 | +import { ConfiguredRetryStrategy } from '@smithy/util-retry'; |
| 8 | +import { omit, pick } from 'lodash'; |
| 9 | +import { defaultBackoffDelay } from '../utils/retry'; |
| 10 | +import { defaultDebugLogger } from '../utils/log'; |
| 11 | + |
| 12 | +class Connector { |
| 13 | + constructor({ |
| 14 | + debug, |
| 15 | + pipelineId, |
| 16 | + endpoint = process.env.WEBSOCKET_ENDPOINT, |
| 17 | + timeout = Number(process.env.WS_TIMEOUT) || Number(process.env.TIMEOUT) || 1000, |
| 18 | + additionalClientOpts = {}, |
| 19 | + ...opt |
| 20 | + }) { |
| 21 | + this.debug = (msg) => debug('%j', msg); |
| 22 | + this.endpoint = endpoint || 'undefined'; |
| 23 | + this.client = Connector.getClient(pipelineId, debug, timeout, endpoint, additionalClientOpts); |
| 24 | + this.opt = opt; |
| 25 | + } |
| 26 | + |
| 27 | + static clients = {}; |
| 28 | + |
| 29 | + static getClient(pipelineId, debug, timeout, endpoint, additionalClientOpts) { |
| 30 | + const addlRequestHandlerOpts = pick(additionalClientOpts, ['requestHandler']); |
| 31 | + const addlClientOpts = omit(additionalClientOpts, ['requestHandler']); |
| 32 | + |
| 33 | + if (!this.clients[pipelineId]) { |
| 34 | + this.clients[pipelineId] = new ApiGatewayManagementApiClient({ |
| 35 | + endpoint, |
| 36 | + requestHandler: new NodeHttpHandler({ |
| 37 | + requestTimeout: timeout, |
| 38 | + connectionTimeout: timeout, |
| 39 | + ...addlRequestHandlerOpts, |
| 40 | + }), |
| 41 | + retryStrategy: new ConfiguredRetryStrategy(11, defaultBackoffDelay), |
| 42 | + logger: defaultDebugLogger(debug), |
| 43 | + ...addlClientOpts, |
| 44 | + }); |
| 45 | + } |
| 46 | + return this.clients[pipelineId]; |
| 47 | + } |
| 48 | + |
| 49 | + postToConnection(connectionId, data, ctx) { |
| 50 | + const params = { |
| 51 | + ConnectionId: connectionId, |
| 52 | + Data: typeof data === 'string' ? data : JSON.stringify(data), |
| 53 | + }; |
| 54 | + |
| 55 | + return this._sendCommand(new PostToConnectionCommand(params), ctx); |
| 56 | + } |
| 57 | + |
| 58 | + _sendCommand(command, ctx) { |
| 59 | + this.opt.metrics?.capture(this.client, command, 'ws', this.opt, ctx); |
| 60 | + return Promise.resolve(this.client.send(command)) |
| 61 | + .tap(this.debug) |
| 62 | + .tapCatch(this.debug); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +export default Connector; |
0 commit comments