@autofleet/rabbit 1.5.3 → 1.5.5

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/example.js CHANGED
@@ -8,8 +8,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
- const index_1 = require("./index");
15
+ const index_1 = __importDefault(require("./index"));
13
16
  process.env.RABBITMQ_SERVICE_HOST = '34.76.123.137:5672';
14
17
  const init = () => __awaiter(void 0, void 0, void 0, function* () {
15
18
  const rabbit = new index_1.default();
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
@@ -1,4 +1,23 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
2
21
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
22
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
23
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -8,23 +27,24 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
27
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
28
  });
10
29
  };
30
+ var __importDefault = (this && this.__importDefault) || function (mod) {
31
+ return (mod && mod.__esModule) ? mod : { "default": mod };
32
+ };
11
33
  Object.defineProperty(exports, "__esModule", { value: true });
12
34
  /* eslint-disable @typescript-eslint/ban-ts-comment,@typescript-eslint/ban-types,@typescript-eslint/no-unused-vars,consistent-return,no-async-promise-executor,no-param-reassign,no-empty */
13
35
  // eslint-disable-next-line max-classes-per-file
14
- const bluebird = require("bluebird");
36
+ const bluebird = __importStar(require("bluebird"));
15
37
  const amqp_connection_manager_1 = require("amqp-connection-manager");
16
38
  const events_1 = require("events");
17
- const mockImpl_1 = require("./mockImpl");
18
- const rabbitError_1 = require("./rabbitError");
39
+ const outbreak_1 = require("@autofleet/outbreak");
40
+ const rabbitError_1 = __importDefault(require("./rabbitError"));
19
41
  const assertExchangeFanout = (c, exchangeName) => c.assertExchange(exchangeName, 'fanout');
20
42
  const connectionCreatedConst = 'connectionCreated';
21
43
  class RabbitMq {
22
- constructor({ isTestEnv = false } = {}) {
44
+ constructor() {
23
45
  this.PUBLISH_TIMEOUT = Number(process.env.RABBITMQ_PUBLISH_TIMEOUT) || 60000;
24
46
  this.PUBLISH_ERROR_MSG = `rabbit: publish timeout(${this.PUBLISH_TIMEOUT}ms) has pass, exchange: `;
25
47
  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
48
  this.ack = (msg) => __awaiter(this, void 0, void 0, function* () {
29
49
  if (this.channel) {
30
50
  yield this.channel.ack(msg);
@@ -49,7 +69,6 @@ class RabbitMq {
49
69
  this.connection = null;
50
70
  this.creatingConnection = false;
51
71
  this.exchanges = {};
52
- this.isTestEnv = isTestEnv;
53
72
  }
54
73
  static parseMsg(msg) {
55
74
  let { content } = msg;
@@ -77,7 +96,7 @@ class RabbitMq {
77
96
  }
78
97
  this.creatingConnection = true;
79
98
  const host = process.env.RABBITMQ_SERVICE_HOST || '';
80
- const connection = yield this.connect([`amqp://${host}`]);
99
+ const connection = yield amqp_connection_manager_1.connect([`amqp://${host}`]);
81
100
  this.connection = connection;
82
101
  this.connection.on('disconnect', ({ err }) => console.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`));
83
102
  this.creatingConnection = false;
@@ -95,7 +114,7 @@ class RabbitMq {
95
114
  const connection = yield this.getConnection();
96
115
  try {
97
116
  if (this.channel === null) {
98
- this.channel = yield connection.createChannel({});
117
+ this.channel = connection.createChannel({});
99
118
  }
100
119
  resolve(this.channel);
101
120
  }
@@ -142,6 +161,7 @@ class RabbitMq {
142
161
  }
143
162
  consume(queue, callback, options) {
144
163
  return __awaiter(this, void 0, void 0, function* () {
164
+ outbreak_1.newTrace(outbreak_1.traceTypes.RABBIT);
145
165
  RabbitMq.validateName('queue', queue);
146
166
  const { limit } = (options && options.limit) ? options : { limit: 1 };
147
167
  const channel = yield this.assertChannel();
@@ -156,6 +176,7 @@ class RabbitMq {
156
176
  }
157
177
  consumeFromExchange(queue, exchange, callback, options) {
158
178
  return __awaiter(this, void 0, void 0, function* () {
179
+ outbreak_1.newTrace(outbreak_1.traceTypes.RABBIT);
159
180
  RabbitMq.validateName('queue', queue);
160
181
  RabbitMq.validateName('exchange', exchange);
161
182
  const { limit } = (options && options.limit) ? options : { limit: 1 };
@@ -8,9 +8,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
11
14
  Object.defineProperty(exports, "__esModule", { value: true });
12
15
  /* eslint-disable @typescript-eslint/ban-ts-comment,@typescript-eslint/no-unused-vars */
13
- const index_1 = require("./index");
16
+ const index_1 = __importDefault(require("./index"));
14
17
  jest.setTimeout(120000);
15
18
  const rabbit = new index_1.default();
16
19
  const delay = () => new Promise((resolve) => setTimeout(() => resolve(), 500));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/rabbit",
3
- "version": "1.5.3",
3
+ "version": "1.5.5",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -14,6 +14,7 @@
14
14
  "dev": "nodemon"
15
15
  },
16
16
  "dependencies": {
17
+ "@autofleet/outbreak": "0.0.6",
17
18
  "@types/amqp-connection-manager": "^2.0.10",
18
19
  "@types/amqplib": "^0.5.16",
19
20
  "@types/jest": "^22.0.0",
package/src/index.ts CHANGED
@@ -2,13 +2,9 @@
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';
7
+ import { newTrace, traceTypes } from '@autofleet/outbreak';
12
8
  import RabbitError from './rabbitError';
13
9
 
14
10
  interface ExchangesCache {
@@ -18,7 +14,7 @@ interface ExchangesCache {
18
14
  const assertExchangeFanout = (c: any, exchangeName: string) => c.assertExchange(exchangeName, 'fanout');
19
15
 
20
16
  const connectionCreatedConst = 'connectionCreated';
21
- class RabbitMq implements RabbitWrapperInterface {
17
+ class RabbitMq {
22
18
  static parseMsg(msg: any) {
23
19
  let { content } = msg;
24
20
  content = content.toString();
@@ -55,21 +51,14 @@ class RabbitMq implements RabbitWrapperInterface {
55
51
 
56
52
  exchanges: ExchangesCache;
57
53
 
58
- isTestEnv: boolean;
59
-
60
- constructor({ isTestEnv = false } = {}) {
54
+ constructor() {
61
55
  this.em = new EventEmitter();
62
56
  this.channel = null;
63
57
  this.connection = null;
64
58
  this.creatingConnection = false;
65
59
  this.exchanges = {};
66
- this.isTestEnv = isTestEnv;
67
60
  }
68
61
 
69
- private getConnectFunc = () => (this.isTestEnv ? connectMock : connectAmqp)
70
-
71
- private connect = (urls:any[] = []) => this.getConnectFunc()(urls);
72
-
73
62
  public ack = async (msg: any) => {
74
63
  if (this.channel) {
75
64
  await this.channel.ack(msg);
@@ -101,7 +90,7 @@ class RabbitMq implements RabbitWrapperInterface {
101
90
  }
102
91
  this.creatingConnection = true;
103
92
  const host: string = process.env.RABBITMQ_SERVICE_HOST || '';
104
- const connection: AmqpConnectionManager = await this.connect([`amqp://${host}`]);
93
+ const connection: AmqpConnectionManager = await connect([`amqp://${host}`]);
105
94
  this.connection = connection;
106
95
  this.connection.on('disconnect',
107
96
  ({ err }) => console.error(`${this.DISCONNECT_MSG}${err && ` - ${err}`}`));
@@ -121,7 +110,7 @@ class RabbitMq implements RabbitWrapperInterface {
121
110
 
122
111
  try {
123
112
  if (this.channel === null) {
124
- this.channel = await connection.createChannel({});
113
+ this.channel = connection.createChannel({});
125
114
  }
126
115
  resolve(this.channel);
127
116
  } catch (e) {
@@ -162,6 +151,7 @@ class RabbitMq implements RabbitWrapperInterface {
162
151
  }
163
152
 
164
153
  async consume(queue: string, callback: (msg: any, ack: Function, nack: Function) => any, options?: any) {
154
+ newTrace(traceTypes.RABBIT);
165
155
  RabbitMq.validateName('queue', queue);
166
156
  const { limit } = (options && options.limit) ? options : { limit: 1 };
167
157
  const channel: ChannelWrapper = await this.assertChannel();
@@ -175,6 +165,7 @@ class RabbitMq implements RabbitWrapperInterface {
175
165
  }
176
166
 
177
167
  async consumeFromExchange(queue: string, exchange: string, callback: (msg: any, ack: Function, nack: Function) => any, options?: any) {
168
+ newTrace(traceTypes.RABBIT);
178
169
  RabbitMq.validateName('queue', queue);
179
170
  RabbitMq.validateName('exchange', exchange);
180
171
  const { limit } = (options && options.limit) ? options : { limit: 1 };
package/tsconfig.json CHANGED
@@ -4,6 +4,7 @@
4
4
  "module": "commonjs",
5
5
  "declaration": true,
6
6
  "outDir": "./dist",
7
- "strict": true
7
+ "strict": true,
8
+ "esModuleInterop": true
8
9
  }
9
10
  }
@@ -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 };