@autofleet/rabbit 1.5.3 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  /// <reference types="node" />
2
2
  import { AmqpConnectionManager, ChannelWrapper } from 'amqp-connection-manager';
3
3
  import { EventEmitter } from 'events';
4
- import RabbitWrapperInterface from './interfaces/RabbitWrapperInterface';
5
4
  interface ExchangesCache {
6
5
  [key: string]: any;
7
6
  }
8
- declare class RabbitMq implements RabbitWrapperInterface {
7
+ declare class RabbitMq {
9
8
  static parseMsg(msg: any): any;
10
9
  static validateName(type: string, name: string): void;
11
10
  PUBLISH_TIMEOUT: number;
@@ -16,12 +15,7 @@ declare class RabbitMq implements RabbitWrapperInterface {
16
15
  em: EventEmitter;
17
16
  creatingConnection: boolean;
18
17
  exchanges: ExchangesCache;
19
- isTestEnv: boolean;
20
- constructor({ isTestEnv }?: {
21
- isTestEnv?: boolean | undefined;
22
- });
23
- private getConnectFunc;
24
- private connect;
18
+ constructor();
25
19
  ack: (msg: any) => Promise<void>;
26
20
  nack: (queue: string) => (msg: any, retries: number) => Promise<void>;
27
21
  getConnection(): Promise<AmqpConnectionManager>;
package/dist/index.js CHANGED
@@ -14,17 +14,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
14
14
  const bluebird = require("bluebird");
15
15
  const amqp_connection_manager_1 = require("amqp-connection-manager");
16
16
  const events_1 = require("events");
17
- const mockImpl_1 = require("./mockImpl");
18
17
  const rabbitError_1 = require("./rabbitError");
19
18
  const assertExchangeFanout = (c, exchangeName) => c.assertExchange(exchangeName, 'fanout');
20
19
  const connectionCreatedConst = 'connectionCreated';
21
20
  class RabbitMq {
22
- constructor({ isTestEnv = false } = {}) {
21
+ constructor() {
23
22
  this.PUBLISH_TIMEOUT = Number(process.env.RABBITMQ_PUBLISH_TIMEOUT) || 60000;
24
23
  this.PUBLISH_ERROR_MSG = `rabbit: publish timeout(${this.PUBLISH_TIMEOUT}ms) has pass, exchange: `;
25
24
  this.DISCONNECT_MSG = 'rabbit: connection disconnect';
26
- this.getConnectFunc = () => (this.isTestEnv ? mockImpl_1.connect : amqp_connection_manager_1.connect);
27
- this.connect = (urls = []) => this.getConnectFunc()(urls);
28
25
  this.ack = (msg) => __awaiter(this, void 0, void 0, function* () {
29
26
  if (this.channel) {
30
27
  yield this.channel.ack(msg);
@@ -49,7 +46,6 @@ class RabbitMq {
49
46
  this.connection = null;
50
47
  this.creatingConnection = false;
51
48
  this.exchanges = {};
52
- this.isTestEnv = isTestEnv;
53
49
  }
54
50
  static parseMsg(msg) {
55
51
  let { content } = msg;
@@ -77,7 +73,7 @@ class RabbitMq {
77
73
  }
78
74
  this.creatingConnection = true;
79
75
  const host = process.env.RABBITMQ_SERVICE_HOST || '';
80
- const connection = yield this.connect([`amqp://${host}`]);
76
+ const connection = yield amqp_connection_manager_1.connect([`amqp://${host}`]);
81
77
  this.connection = connection;
82
78
  this.connection.on('disconnect', ({ err }) => console.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`));
83
79
  this.creatingConnection = false;
@@ -95,7 +91,7 @@ class RabbitMq {
95
91
  const connection = yield this.getConnection();
96
92
  try {
97
93
  if (this.channel === null) {
98
- this.channel = yield connection.createChannel({});
94
+ this.channel = connection.createChannel({});
99
95
  }
100
96
  resolve(this.channel);
101
97
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/rabbit",
3
- "version": "1.5.3",
3
+ "version": "1.5.4",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
package/src/index.ts CHANGED
@@ -2,13 +2,8 @@
2
2
  // eslint-disable-next-line max-classes-per-file
3
3
  import * as bluebird from 'bluebird';
4
4
  import { ConfirmChannel } from 'amqplib';
5
- import {
6
- AmqpConnectionManager, ChannelWrapper,
7
- connect as connectAmqp,
8
- } from 'amqp-connection-manager';
5
+ import { AmqpConnectionManager, ChannelWrapper, connect } from 'amqp-connection-manager';
9
6
  import { EventEmitter } from 'events';
10
- import { connect as connectMock } from './mockImpl';
11
- import RabbitWrapperInterface from './interfaces/RabbitWrapperInterface';
12
7
  import RabbitError from './rabbitError';
13
8
 
14
9
  interface ExchangesCache {
@@ -18,7 +13,7 @@ interface ExchangesCache {
18
13
  const assertExchangeFanout = (c: any, exchangeName: string) => c.assertExchange(exchangeName, 'fanout');
19
14
 
20
15
  const connectionCreatedConst = 'connectionCreated';
21
- class RabbitMq implements RabbitWrapperInterface {
16
+ class RabbitMq {
22
17
  static parseMsg(msg: any) {
23
18
  let { content } = msg;
24
19
  content = content.toString();
@@ -55,21 +50,14 @@ class RabbitMq implements RabbitWrapperInterface {
55
50
 
56
51
  exchanges: ExchangesCache;
57
52
 
58
- isTestEnv: boolean;
59
-
60
- constructor({ isTestEnv = false } = {}) {
53
+ constructor() {
61
54
  this.em = new EventEmitter();
62
55
  this.channel = null;
63
56
  this.connection = null;
64
57
  this.creatingConnection = false;
65
58
  this.exchanges = {};
66
- this.isTestEnv = isTestEnv;
67
59
  }
68
60
 
69
- private getConnectFunc = () => (this.isTestEnv ? connectMock : connectAmqp)
70
-
71
- private connect = (urls:any[] = []) => this.getConnectFunc()(urls);
72
-
73
61
  public ack = async (msg: any) => {
74
62
  if (this.channel) {
75
63
  await this.channel.ack(msg);
@@ -101,7 +89,7 @@ class RabbitMq implements RabbitWrapperInterface {
101
89
  }
102
90
  this.creatingConnection = true;
103
91
  const host: string = process.env.RABBITMQ_SERVICE_HOST || '';
104
- const connection: AmqpConnectionManager = await this.connect([`amqp://${host}`]);
92
+ const connection: AmqpConnectionManager = await connect([`amqp://${host}`]);
105
93
  this.connection = connection;
106
94
  this.connection.on('disconnect',
107
95
  ({ err }) => console.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`));
@@ -121,7 +109,7 @@ class RabbitMq implements RabbitWrapperInterface {
121
109
 
122
110
  try {
123
111
  if (this.channel === null) {
124
- this.channel = await connection.createChannel({});
112
+ this.channel = connection.createChannel({});
125
113
  }
126
114
  resolve(this.channel);
127
115
  } catch (e) {
@@ -1,15 +0,0 @@
1
- interface RabbitWrapperInterface {
2
- ack: any;
3
- nack: any;
4
- getConnection: any;
5
- assertChannel: any;
6
- assertExchange: any;
7
- getQueueLength: any;
8
- bindQueue: any;
9
- assertQueue: any;
10
- consume: any;
11
- consumeFromExchange: any;
12
- publish: any;
13
- sendToQueue: any;
14
- }
15
- export default RabbitWrapperInterface;
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,25 +0,0 @@
1
- export interface channel {
2
- assertQueue: any;
3
- assertExchange: any;
4
- bindQueue: any;
5
- publish: any;
6
- consume: any;
7
- deleteQueue: any;
8
- ack: any;
9
- nack: any;
10
- prefetch: any;
11
- on: any;
12
- once: any;
13
- close: any;
14
- addSetup: any;
15
- checkQueue: any;
16
- sendToQueue: any;
17
- }
18
- export interface connection {
19
- createChannel: any;
20
- createConfirmChannel: any;
21
- on: any;
22
- once: any;
23
- close: any;
24
- }
25
- export declare const connect: () => any;
@@ -1,98 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.connect = void 0;
13
- const Bluebird = require("bluebird");
14
- let exchanges = {};
15
- let queues = {};
16
- const setIfUndef = (object, prop, value) => {
17
- if (!object[prop]) {
18
- // eslint-disable-next-line no-param-reassign
19
- object[prop] = value;
20
- }
21
- };
22
- class ChannelImpl {
23
- constructor() {
24
- this.assertQueue = (queue, qOptions) => new Bluebird((resolve) => {
25
- setIfUndef(queues, queue, { messages: [], subscribers: [], options: qOptions });
26
- return resolve();
27
- });
28
- this.assertExchange = (exchange, type, exchOptions = {}) => new Bluebird((resolve) => {
29
- setIfUndef(exchanges, exchange, { bindings: [], options: exchOptions, type });
30
- return resolve();
31
- });
32
- this.bindQueue = (queue, exchange, key) => new Bluebird((resolve, reject) => {
33
- if (!exchanges[exchange])
34
- return reject(`Bind to non-existing exchange ${exchange}`);
35
- const re = `^${key.replace('.', '\\.').replace('#', '(\\w|\\.)+').replace('*', '\\w+')}$`;
36
- exchanges[exchange].bindings.push({ regex: new RegExp(re), queueName: queue });
37
- return resolve();
38
- });
39
- this.publish = (exchange, routingKey, content, props) => new Bluebird((resolve, reject) => {
40
- if (!exchanges[exchange])
41
- return reject(`Publish to non-existing exchange ${exchange}`);
42
- const { bindings } = exchanges[exchange];
43
- const matchingBindings = bindings.filter((b) => b.regex.test(routingKey));
44
- matchingBindings.forEach((binding) => {
45
- const subscribers = queues[binding.queueName] ? queues[binding.queueName].subscribers : [];
46
- subscribers.forEach((sub) => {
47
- const message = { fields: { routingKey }, properties: props, content };
48
- sub(message);
49
- });
50
- });
51
- return resolve();
52
- });
53
- this.consume = (queue, handler) => {
54
- queues[queue].subscribers.push(handler);
55
- };
56
- this.sendToQueue = (queue, content, routingKey = '', props = {}) => {
57
- const subscribers = queues[queue] ? queues[queue].subscribers : [];
58
- subscribers.forEach((sub) => {
59
- const message = { fields: { routingKey }, properties: props, content };
60
- sub(message);
61
- });
62
- };
63
- this.deleteQueue = (queue) => {
64
- setImmediate(() => {
65
- delete queues[queue];
66
- });
67
- };
68
- this.checkQueue = () => ({ messageCount: 0 });
69
- this.ack = () => null;
70
- this.nack = () => null;
71
- this.prefetch = () => null;
72
- this.on = () => null;
73
- this.once = () => null;
74
- this.close = () => Bluebird.resolve();
75
- }
76
- addSetup(funcToRun) {
77
- return __awaiter(this, void 0, void 0, function* () {
78
- const val = yield funcToRun(this);
79
- return val;
80
- });
81
- }
82
- }
83
- const createChannel = () => new Bluebird((resolve) => resolve(new ChannelImpl()));
84
- exports.connect = () => new Bluebird((resolve) => {
85
- const connectionImpl = {
86
- createChannel,
87
- createConfirmChannel: createChannel,
88
- on: () => null,
89
- once: () => null,
90
- close: () => Bluebird.resolve(),
91
- };
92
- return resolve(connectionImpl);
93
- });
94
- const resetMock = () => {
95
- queues = {};
96
- exchanges = {};
97
- };
98
- module.exports = { connect: exports.connect, resetMock };
@@ -1 +0,0 @@
1
- export {};
@@ -1,67 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- /* eslint-disable @typescript-eslint/ban-ts-comment,@typescript-eslint/no-unused-vars */
13
- const index_1 = require("../index");
14
- jest.setTimeout(120000);
15
- const rabbit = new index_1.default({ isTestEnv: true });
16
- describe('RabbitMQ', () => {
17
- it('check exchange', () => __awaiter(void 0, void 0, void 0, function* () {
18
- const callback = (msg, ack) => {
19
- expect(msg.content).toEqual('hey');
20
- ack(msg);
21
- };
22
- const mockFn = jest.fn(callback);
23
- yield rabbit.consumeFromExchange('test-q2', 'test-e', mockFn);
24
- yield rabbit.publish('test-e', 'hey');
25
- expect(mockFn).toBeCalled();
26
- }));
27
- it('check queue', () => __awaiter(void 0, void 0, void 0, function* () {
28
- const callback = (msg, ack) => {
29
- expect(msg.content).toEqual('hey-q');
30
- ack(msg);
31
- };
32
- const mockFn = jest.fn(callback);
33
- yield rabbit.consume('test-q-2', mockFn);
34
- yield rabbit.sendToQueue('test-q-2', 'hey-q');
35
- expect(mockFn).toBeCalled();
36
- }));
37
- it('cant publish to unknown exchange', () => __awaiter(void 0, void 0, void 0, function* () {
38
- let err;
39
- try {
40
- yield rabbit.publish('', 'hey');
41
- }
42
- catch (e) {
43
- err = e;
44
- }
45
- expect(err).toBeDefined();
46
- }));
47
- it('get queue length', () => __awaiter(void 0, void 0, void 0, function* () {
48
- const queueName = 'test-queue-length';
49
- const exchangeName = 'test-e2';
50
- yield rabbit.assertQueue(queueName);
51
- yield rabbit.assertExchange(exchangeName);
52
- yield rabbit.bindQueue(queueName, exchangeName);
53
- yield rabbit.publish(exchangeName, 'hey');
54
- let messageCount;
55
- ({ messageCount } = yield rabbit.getQueueLength(queueName));
56
- expect(messageCount).toEqual(0);
57
- yield rabbit.publish(exchangeName, 'hey');
58
- ({ messageCount } = yield rabbit.getQueueLength(queueName));
59
- expect(messageCount).toEqual(0);
60
- yield rabbit.consumeFromExchange(queueName, exchangeName, (msg, ack) => __awaiter(void 0, void 0, void 0, function* () {
61
- expect(msg.content).toEqual('hey');
62
- ack(msg);
63
- }));
64
- ({ messageCount } = yield rabbit.getQueueLength(queueName));
65
- expect(messageCount).toEqual(0);
66
- }));
67
- });
@@ -1,17 +0,0 @@
1
- interface RabbitWrapperInterface {
2
- ack:any;
3
- nack: any;
4
- getConnection: any;
5
- assertChannel: any;
6
- assertExchange: any;
7
- getQueueLength: any;
8
- bindQueue: any;
9
- assertQueue: any;
10
- consume: any;
11
- consumeFromExchange: any;
12
- publish: any;
13
- sendToQueue: any;
14
-
15
- }
16
-
17
- export default RabbitWrapperInterface;
@@ -1,63 +0,0 @@
1
- /* eslint-disable @typescript-eslint/ban-ts-comment,@typescript-eslint/no-unused-vars */
2
- import RabbitMq from '../index';
3
-
4
- jest.setTimeout(120000);
5
-
6
- const rabbit = new RabbitMq({ isTestEnv: true });
7
-
8
- describe('RabbitMQ', () => {
9
- it('check exchange', async () => {
10
- const callback = (msg: any, ack: any) => {
11
- expect(msg.content).toEqual('hey');
12
- ack(msg);
13
- };
14
- const mockFn = jest.fn(callback);
15
- await rabbit.consumeFromExchange('test-q2', 'test-e', mockFn);
16
- await rabbit.publish('test-e', 'hey');
17
- expect(mockFn).toBeCalled();
18
- });
19
-
20
- it('check queue', async () => {
21
- const callback = (msg: any, ack: any) => {
22
- expect(msg.content).toEqual('hey-q');
23
- ack(msg);
24
- };
25
- const mockFn = jest.fn(callback);
26
- await rabbit.consume('test-q-2', mockFn);
27
- await rabbit.sendToQueue('test-q-2', 'hey-q');
28
- expect(mockFn).toBeCalled();
29
- });
30
-
31
- it('cant publish to unknown exchange', async () => {
32
- let err;
33
- try {
34
- await rabbit.publish('', 'hey');
35
- } catch (e) {
36
- err = e;
37
- }
38
- expect(err).toBeDefined();
39
- });
40
-
41
- it('get queue length', async () => {
42
- const queueName = 'test-queue-length';
43
- const exchangeName = 'test-e2';
44
-
45
- await rabbit.assertQueue(queueName);
46
- await rabbit.assertExchange(exchangeName);
47
- await rabbit.bindQueue(queueName, exchangeName);
48
-
49
- await rabbit.publish(exchangeName, 'hey');
50
- let messageCount: any;
51
- ({ messageCount } = await rabbit.getQueueLength(queueName));
52
- expect(messageCount).toEqual(0);
53
- await rabbit.publish(exchangeName, 'hey');
54
- ({ messageCount } = await rabbit.getQueueLength(queueName));
55
- expect(messageCount).toEqual(0);
56
- await rabbit.consumeFromExchange(queueName, exchangeName, async (msg: any, ack: any) => {
57
- expect(msg.content).toEqual('hey');
58
- ack(msg);
59
- });
60
- ({ messageCount } = await rabbit.getQueueLength(queueName));
61
- expect(messageCount).toEqual(0);
62
- });
63
- });
@@ -1,132 +0,0 @@
1
- import * as Bluebird from 'bluebird';
2
-
3
- let exchanges: any = {};
4
- let queues: any = {};
5
-
6
- export interface channel {
7
- assertQueue: any;
8
- assertExchange: any;
9
- bindQueue: any;
10
- publish: any;
11
- consume: any;
12
- deleteQueue: any;
13
- ack: any;
14
- nack: any;
15
- prefetch: any;
16
- on: any;
17
- once: any;
18
- close: any;
19
- addSetup: any;
20
- checkQueue: any;
21
- sendToQueue: any;
22
- }
23
- export interface connection {
24
- createChannel: any;
25
- createConfirmChannel: any;
26
- on: any;
27
- once: any;
28
- close: any;
29
- }
30
-
31
- const setIfUndef = (object: any, prop: any, value: any) => {
32
- if (!object[prop]) {
33
- // eslint-disable-next-line no-param-reassign
34
- object[prop] = value;
35
- }
36
- };
37
-
38
- class ChannelImpl implements channel {
39
- public assertQueue = (queue: any, qOptions: any) => new Bluebird((resolve: () => any) => {
40
- setIfUndef(queues, queue, { messages: [], subscribers: [], options: qOptions });
41
- return resolve();
42
- });
43
-
44
- public assertExchange = (exchange: any, type: any, exchOptions: any = {}) => new Bluebird((resolve: () => any) => {
45
- setIfUndef(exchanges, exchange, { bindings: [], options: exchOptions, type });
46
-
47
- return resolve();
48
- });
49
-
50
- public bindQueue = (queue: any, exchange: string, key: string) => new Bluebird((resolve: () => any, reject: (arg0: string) => any) => {
51
- if (!exchanges[exchange]) return reject(`Bind to non-existing exchange ${exchange}`);
52
-
53
- const re = `^${key.replace('.', '\\.').replace('#', '(\\w|\\.)+').replace('*', '\\w+')}$`;
54
- exchanges[exchange].bindings.push({ regex: new RegExp(re), queueName: queue });
55
-
56
- return resolve();
57
- });
58
-
59
- public publish = (exchange: string, routingKey: any, content: any, props: any) => new Bluebird((resolve: () => any, reject: (arg0: string) => any) => {
60
- if (!exchanges[exchange]) return reject(`Publish to non-existing exchange ${exchange}`);
61
-
62
- const { bindings } = exchanges[exchange];
63
- const matchingBindings = bindings.filter((b: any) => b.regex.test(routingKey));
64
-
65
- matchingBindings.forEach((binding: { queueName: string | number; }) => {
66
- const subscribers = queues[binding.queueName] ? queues[binding.queueName].subscribers : [];
67
- subscribers.forEach((sub: (arg0: { fields: { routingKey: any; }; properties: any; content: any; }) => void) => {
68
- const message = { fields: { routingKey }, properties: props, content };
69
- sub(message);
70
- });
71
- });
72
-
73
- return resolve();
74
- });
75
-
76
- public consume = (queue: string | number, handler: any) => {
77
- queues[queue].subscribers.push(handler);
78
- };
79
-
80
- public sendToQueue = (queue: string, content: any, routingKey = '', props: any = {}) => {
81
- const subscribers = queues[queue] ? queues[queue].subscribers : [];
82
- subscribers.forEach((sub: (arg0: { fields: { routingKey: any; }; properties: any; content: any; }) => void) => {
83
- const message = { fields: { routingKey }, properties: props, content };
84
- sub(message);
85
- });
86
- };
87
-
88
- public deleteQueue = (queue: string | number) => {
89
- setImmediate(() => {
90
- delete queues[queue];
91
- });
92
- };
93
-
94
- public async addSetup(funcToRun: any) {
95
- const val = await funcToRun(this);
96
- return val;
97
- }
98
-
99
- public checkQueue = () => ({ messageCount: 0 });
100
-
101
- public ack = () => null;
102
-
103
- public nack = () => null;
104
-
105
- public prefetch = () => null;
106
-
107
- public on = () => null;
108
-
109
- public once = () => null;
110
-
111
- public close = () => Bluebird.resolve();
112
- }
113
-
114
- const createChannel = () => new Bluebird((resolve: any) => resolve(new ChannelImpl()));
115
- export const connect = (): any => new Bluebird((resolve: any) => {
116
- const connectionImpl: connection = {
117
- createChannel,
118
- createConfirmChannel: createChannel,
119
- on: () => null,
120
- once: () => null,
121
- close: () => Bluebird.resolve(),
122
- };
123
-
124
- return resolve(connectionImpl);
125
- });
126
-
127
- const resetMock = () => {
128
- queues = {};
129
- exchanges = {};
130
- };
131
-
132
- module.exports = { connect, resetMock };