amqp-extension 3.3.0 → 4.0.0-beta.1

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/.eslintrc CHANGED
@@ -5,7 +5,7 @@
5
5
  "parserOptions": {
6
6
  "project": "./tsconfig.eslint.json"
7
7
  },
8
- "ignorePatterns": ["**/dist/*", "**/*.d.ts", "**/test/*"],
8
+ "ignorePatterns": ["**/dist/*", "**/*.d.ts"],
9
9
  "globals": {
10
10
  "NodeJS": true
11
11
  },
package/CHANGELOG.md CHANGED
@@ -1,3 +1,23 @@
1
+ # [4.0.0-beta.1](https://github.com/Tada5hi/amqp-extension/compare/v3.3.0...v4.0.0-beta.1) (2024-06-06)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **deps:** bump amqplib from 0.10.3 to 0.10.4 ([#368](https://github.com/Tada5hi/amqp-extension/issues/368)) ([dae6c84](https://github.com/Tada5hi/amqp-extension/commit/dae6c840ad69e74a6c5dc37ea7f0fbb6c8ea1bae))
7
+ * **deps:** bump smob from 1.4.1 to 1.5.0 ([#334](https://github.com/Tada5hi/amqp-extension/issues/334)) ([0b2935a](https://github.com/Tada5hi/amqp-extension/commit/0b2935af145d4844510c19b6d3f9d23ac0e3386a))
8
+
9
+
10
+ ### Features
11
+
12
+ * adjusted test suite ([a5cc771](https://github.com/Tada5hi/amqp-extension/commit/a5cc7714a141d671d1e97ed67216df0ffc53af49))
13
+ * change publish/consume signature ([ff316ec](https://github.com/Tada5hi/amqp-extension/commit/ff316ec27ac1077c7a6949ea5e5adf6ad1e5e5f5))
14
+ * initial refactoring of config, consume- &p publish-behaviour ([1102aa8](https://github.com/Tada5hi/amqp-extension/commit/1102aa8a8b000336312d89c92434d8c77e7a0424))
15
+
16
+
17
+ ### BREAKING CHANGES
18
+
19
+ * public api changed
20
+
1
21
  # [3.3.0](https://github.com/Tada5hi/amqp-extension/compare/v3.2.0...v3.3.0) (2024-03-20)
2
22
 
3
23
 
package/README.MD CHANGED
@@ -12,13 +12,8 @@ This is a library on top of the [amqplib](https://www.npmjs.com/package/amqplib)
12
12
 
13
13
  - [Installation](#installation)
14
14
  - [Usage](#usage)
15
- - [Publish](#publish-to-queue)
16
- - [Consume](#consume-queue)
17
- - [Functions](#functions)
18
- - [publish](#publish)
19
- - [consume](#consume)
20
- - [Types](#types)
21
- - [Config](#config-types)
15
+ - [Publish](#publish)
16
+ - [Consume](#consume)
22
17
  - [License](#license)
23
18
 
24
19
 
@@ -30,16 +25,15 @@ npm install amqp-extension --save
30
25
 
31
26
  ## Usage
32
27
 
33
- ### Publish to Queue
28
+ ### Publish
34
29
 
35
30
  The `publish` method allows you to send messages quickly.
36
- Existing options can be added or overwritten
37
31
 
38
32
  ```typescript
39
33
  import { Client } from "amqp-extension";
40
34
 
41
35
  const client = new Client({
42
- connection: 'amqp://<user>:<password>@<host>',
36
+ connectionOptions: 'amqp://<user>:<password>@<host>',
43
37
  exchange: {
44
38
  name: '<name>',
45
39
  type: 'topic'
@@ -47,20 +41,15 @@ const client = new Client({
47
41
  });
48
42
 
49
43
  (async () => {
50
- await client.publish({
51
- content: {
52
- type: 'resourceCreated',
53
- name: 'foo'
54
- }
44
+ await client.publish('<routing-key>', {
45
+ foo: 'bar'
55
46
  });
56
47
  })();
57
48
  ```
58
49
 
59
- ### Consume Queue
60
-
61
- To consume a queue use the `consume` function. As first argument it accepts a configuration object
62
- and as second argument and object to specify an async callback function handler for a specific message `type`.
50
+ ### Consume
63
51
 
52
+ To consume a queue use the `consume` function.
64
53
  ```typescript
65
54
  import {
66
55
  Client,
@@ -69,22 +58,16 @@ import {
69
58
  } from "amqp-extension";
70
59
 
71
60
  const client = new Client({
72
- connection: 'amqp://<user>:<password>@<host>',
61
+ connectionOptions: 'amqp://<user>:<password>@<host>',
73
62
  exchange: {
74
63
  name: '<name>',
75
64
  type: 'topic'
76
65
  }
77
66
  });
78
67
 
79
- const options: ConsumeOptions = {
80
- exchange: {
81
- routingKey: '<routing-key>'
82
- }
83
- }
84
-
85
68
  (async () => {
86
- await client.consume(options, {
87
- resourceCreated: async (message: ConsumeMessage) => {
69
+ await client.consume('<routing-key>', {
70
+ $any: async (message: ConsumeMessage) => {
88
71
  const content = message.content.toString('utf-8');
89
72
  const payload = JSON.parse(content);
90
73
  console.log(payload);
@@ -94,125 +77,6 @@ const options: ConsumeOptions = {
94
77
  })();
95
78
  ```
96
79
 
97
- ## Functions
98
-
99
- ### publish
100
-
101
- ▸ `function` **publish**(`message: Message`, `options?: PublishOptions`): `Promise<void>`
102
-
103
- Send the constructed queue message to the message broker.
104
- As second parameter a registered config can be used by specifying the alias or provide the full config object.
105
- #### Example
106
- **`Simple`**
107
-
108
- ```typescript
109
- import { Client } from "amqp-extension";
110
-
111
- const client = new Client({
112
- // ...
113
- });
114
-
115
- (async () => {
116
- await client.publish({
117
- content: {
118
- type: 'resourceCreated'
119
- }
120
- });
121
- })();
122
- ```
123
-
124
- #### Type parameters
125
-
126
- | Name | Description |
127
- |:------|:------------|
128
-
129
- #### Parameters
130
-
131
- | Name | Type | Description |
132
- |:----------|:-----------------|:----------------------------|
133
- | `message` | `Message` | Constructed message object. |
134
- | `options` | `PublishOptions` | Publish options. |
135
-
136
- #### Returns
137
-
138
- `Promise<void>`
139
-
140
- The function does not return a value.
141
-
142
- ### consume
143
-
144
- ▸ `function` **consume**(`options: ConsumeOptions`, `cb: ConsumeHandlers`): `Promise<void>`
145
-
146
- Send the constructed queue message to the message broker.
147
- As second parameter a registered config can be used by specifying the alias or provide the full config object.
148
- #### Example
149
- **`Simple`**
150
-
151
- ```typescript
152
- import {
153
- Client,
154
- ConsumeOptions,
155
- ConsumeMessage,
156
- } from "amqp-extension";
157
-
158
- const client = new Client({
159
- // ...
160
- });
161
-
162
- const options: ConsumeOptions = {
163
- routingKey: '<routing-key>'
164
- }
165
-
166
- (async () => {
167
- await client.consume(options, {
168
- '<type>': async (message: ConsumeMessage) => {
169
- // do some async action :)
170
- }
171
- });
172
- })();
173
-
174
- ```
175
-
176
- #### Type parameters
177
-
178
- | Name | Description |
179
- |:-------|:------------|
180
-
181
-
182
-
183
- #### Parameters
184
-
185
- | Name | Type | Description |
186
- |:-----------|:------------------|:-------------------|
187
- | `options` | `ConsumeOptions` | Consume options. ) |
188
- | `handlers` | `ConsumeHandlers` | Handlers object. |
189
-
190
- #### Returns
191
-
192
- `Promise<void>`
193
-
194
- The function does not return a value.
195
-
196
- ## Types
197
-
198
- ### Config Types
199
-
200
- ```typescript
201
- import { Options } from 'amqplib';
202
- import { ExchangeOptions } from '../exchange';
203
- import { ConsumeOptions, PublishOptions } from '../type';
204
-
205
- export type Config = {
206
- connection: Options.Connect | string,
207
- exchange: ExchangeOptions,
208
- publish: PublishOptions,
209
- consume: ConsumeOptions
210
- };
211
-
212
- export type ConfigInput = Partial<Exclude<Config, 'connection'>> &
213
- Pick<Config, 'connection'>;
214
- ```
215
-
216
80
  ## License
217
81
 
218
82
  Made with 💚
@@ -17,7 +17,7 @@ function buildConfig(input) {
17
17
  consume: input.consume || {},
18
18
  exchange: input.exchange || {
19
19
  name: '',
20
- type: exchange_1.ExchangeType.DEFAULT,
20
+ type: exchange_1.ExchangeType.DIRECT,
21
21
  },
22
22
  };
23
23
  }
@@ -1,11 +1,12 @@
1
1
  import type { Options } from 'amqplib';
2
- import type { ExchangeOptions } from '../exchange';
3
- import type { ConsumeOptions, PublishOptions } from '../type';
2
+ import type { ConsumeOptions } from '../consume';
3
+ import type { Exchange } from '../exchange';
4
+ import type { PublishOptions } from '../publish';
4
5
  export type Config = {
5
6
  reconnectAttempts: number;
6
7
  reconnectTimeout: number;
7
8
  connection: Options.Connect | string;
8
- exchange: ExchangeOptions;
9
+ exchange: Exchange;
9
10
  publish: PublishOptions;
10
11
  consume: ConsumeOptions;
11
12
  };
@@ -1,3 +1,3 @@
1
- export * from './static';
1
+ export * from './constants';
2
2
  export * from './type';
3
3
  export * from './utils';
@@ -20,6 +20,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
20
20
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
- __exportStar(require("./static"), exports);
23
+ __exportStar(require("./constants"), exports);
24
24
  __exportStar(require("./type"), exports);
25
25
  __exportStar(require("./utils"), exports);
@@ -1,11 +1,25 @@
1
1
  import type { ChannelWrapper } from 'amqp-connection-manager';
2
- import type { ConsumeMessage } from 'amqplib';
3
- import type { ConsumeHandlerAnyKey } from './static';
2
+ import type { ConsumeMessage, Options } from 'amqplib';
3
+ import type { ConsumeHandlerAnyKey } from './constants';
4
4
  export { ConsumeMessage, };
5
5
  export type ConsumeMessageHandler = (message: ConsumeMessage, channel: ChannelWrapper) => Promise<void> | void;
6
- export type ConsumeHandlerAnyKeyType = typeof ConsumeHandlerAnyKey;
7
6
  export type ConsumeHandlers = {
8
7
  [ConsumeHandlerAnyKey]?: ConsumeMessageHandler;
9
8
  } & {
10
9
  [key: string]: ConsumeMessageHandler;
11
10
  };
11
+ export type ConsumeOptions = Options.Consume & {
12
+ /**
13
+ * Default: false
14
+ */
15
+ requeueOnFailure?: boolean;
16
+ /**
17
+ * Default: undefined
18
+ */
19
+ prefetchCount?: number;
20
+ };
21
+ export type ConsumeContext = {
22
+ from: string;
23
+ options?: ConsumeOptions;
24
+ handlers: ConsumeHandlers;
25
+ };
@@ -1,3 +1,2 @@
1
- import type { Options } from 'amqplib';
2
- import type { ConsumeOptions } from '../type';
3
- export declare function buildDriverConsumeOptions(options: ConsumeOptions): Options.Consume;
1
+ import type { ConsumeHandlers } from './type';
2
+ export declare function isConsumeHandlers(input: unknown): input is ConsumeHandlers;
@@ -1,13 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildDriverConsumeOptions = void 0;
4
- const utils_1 = require("../utils");
5
- function buildDriverConsumeOptions(options) {
6
- return (0, utils_1.removeKeysFromOptions)({ ...options }, [
7
- 'exchange',
8
- 'queueName',
9
- 'requeueOnFailure',
10
- 'prefetchCount',
11
- ]);
3
+ exports.isConsumeHandlers = void 0;
4
+ const smob_1 = require("smob");
5
+ function isConsumeHandlers(input) {
6
+ if (!(0, smob_1.isObject)(input)) {
7
+ return false;
8
+ }
9
+ const keys = Object.keys(input);
10
+ for (let i = 0; i < keys.length; i++) {
11
+ if (typeof input[keys[i]] !== 'function') {
12
+ return false;
13
+ }
14
+ }
15
+ return true;
12
16
  }
13
- exports.buildDriverConsumeOptions = buildDriverConsumeOptions;
17
+ exports.isConsumeHandlers = isConsumeHandlers;
@@ -1,5 +1,4 @@
1
1
  export declare enum ExchangeType {
2
- DEFAULT = "default",
3
2
  FANOUT = "fanout",
4
3
  DIRECT = "direct",
5
4
  TOPIC = "topic",
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ExchangeType = void 0;
4
4
  var ExchangeType;
5
5
  (function (ExchangeType) {
6
- ExchangeType["DEFAULT"] = "default";
7
6
  ExchangeType["FANOUT"] = "fanout";
8
7
  ExchangeType["DIRECT"] = "direct";
9
8
  ExchangeType["TOPIC"] = "topic";
@@ -1,7 +1,8 @@
1
1
  import type { Options } from 'amqplib';
2
2
  import type { ExchangeType } from './constants';
3
- export type ExchangeOptions = {
4
- name: string;
3
+ export type ExchangeOptions = Options.AssertExchange;
4
+ export type Exchange = {
5
5
  type: `${ExchangeType}`;
6
- routingKey?: string;
7
- } & Options.AssertExchange;
6
+ name?: string;
7
+ options?: ExchangeOptions;
8
+ };
@@ -1,5 +1,4 @@
1
- import type { Options } from 'amqplib';
2
1
  import { ExchangeType } from './constants';
3
- import type { ExchangeOptions } from './type';
4
- export declare function isDefaultExchange(exchange?: `${ExchangeType}`): boolean;
5
- export declare function buildDriverExchangeOptions(options: ExchangeOptions): Options.AssertExchange;
2
+ import type { Exchange } from './type';
3
+ export declare function isDefaultExchange(input?: `${ExchangeType}`): input is ExchangeType.DIRECT;
4
+ export declare function isExchange(input: unknown): input is Exchange;
@@ -1,17 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildDriverExchangeOptions = exports.isDefaultExchange = void 0;
4
- const utils_1 = require("../utils");
3
+ exports.isExchange = exports.isDefaultExchange = void 0;
4
+ const smob_1 = require("smob");
5
5
  const constants_1 = require("./constants");
6
- function isDefaultExchange(exchange) {
7
- return typeof exchange === 'undefined' || exchange === constants_1.ExchangeType.DEFAULT;
6
+ function isDefaultExchange(input) {
7
+ return typeof input === 'undefined' || input === constants_1.ExchangeType.DIRECT;
8
8
  }
9
9
  exports.isDefaultExchange = isDefaultExchange;
10
- function buildDriverExchangeOptions(options) {
11
- return (0, utils_1.removeKeysFromOptions)({ ...options }, [
12
- 'name',
13
- 'type',
14
- 'routingKey',
15
- ]);
10
+ function isExchange(input) {
11
+ return (0, smob_1.isObject)(input) &&
12
+ typeof input.type === 'string';
16
13
  }
17
- exports.buildDriverExchangeOptions = buildDriverExchangeOptions;
14
+ exports.isExchange = isExchange;
package/dist/module.d.ts CHANGED
@@ -1,12 +1,18 @@
1
- import type { Config, ConfigInput } from './config';
2
- import type { ConsumeHandlers } from './consume';
3
- import type { PublishOptionsExtended } from './publish';
4
- import type { Connection, ConsumeOptions } from './type';
1
+ import type { PublishContext, PublishOptions } from './publish';
2
+ import type { ClientContext, Connection } from './type';
3
+ import type { ConsumeContext, ConsumeHandlers, ConsumeOptions } from './consume';
4
+ import type { Exchange } from './exchange';
5
5
  export declare class Client {
6
- protected connection: Connection | undefined;
7
- protected config: Config;
8
- constructor(options: ConfigInput);
9
- useConnection(): Connection;
10
- consume(options: ConsumeOptions, handlers: ConsumeHandlers): Promise<void>;
11
- publish(options: PublishOptionsExtended): Promise<boolean>;
6
+ readonly connection: Connection;
7
+ protected publishOptions: PublishOptions;
8
+ protected consumeOptions: ConsumeOptions;
9
+ protected exchange: Exchange;
10
+ constructor(ctx: ClientContext);
11
+ of(exchange: Exchange): Client;
12
+ consume(ctx: ConsumeContext): Promise<void>;
13
+ consume(from: string, handlers: ConsumeHandlers): Promise<void>;
14
+ consume(from: string, options: ConsumeOptions, handlers: ConsumeHandlers): Promise<void>;
15
+ publish(ctx: PublishContext): Promise<boolean>;
16
+ publish(to: string, data: any): Promise<boolean>;
17
+ publish(to: string, data: any, options: PublishOptions): Promise<boolean>;
12
18
  }
package/dist/module.js CHANGED
@@ -12,35 +12,65 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.Client = void 0;
13
13
  const amqp_connection_manager_1 = require("amqp-connection-manager");
14
14
  const node_process_1 = __importDefault(require("node:process"));
15
- const smob_1 = require("smob");
16
- const uuid_1 = require("uuid");
17
- const config_1 = require("./config");
18
15
  const consume_1 = require("./consume");
19
16
  const exchange_1 = require("./exchange");
20
- const publish_1 = require("./publish");
17
+ const utils_1 = require("./utils");
21
18
  class Client {
22
- constructor(options) {
23
- this.config = (0, config_1.buildConfig)(options);
24
- node_process_1.default.once('SIGINT', async () => {
25
- if (this.connection) {
26
- await this.connection.close();
27
- }
28
- });
29
- }
30
- useConnection() {
31
- if (typeof this.connection !== 'undefined') {
32
- return this.connection;
19
+ constructor(ctx) {
20
+ if (ctx.connection) {
21
+ this.connection = ctx.connection;
22
+ }
23
+ else {
24
+ this.connection = (0, amqp_connection_manager_1.connect)(ctx.connectionOptions, {
25
+ reconnectTimeInSeconds: 60,
26
+ });
27
+ node_process_1.default.once('SIGINT', async () => {
28
+ if (this.connection) {
29
+ await this.connection.close();
30
+ }
31
+ });
33
32
  }
34
- this.connection = (0, amqp_connection_manager_1.connect)(this.config.connection, {
35
- reconnectTimeInSeconds: this.config.reconnectTimeout,
33
+ this.publishOptions = ctx.publishOptions || {};
34
+ this.consumeOptions = ctx.consumeOptions || {};
35
+ this.exchange = ctx.exchange || {
36
+ type: exchange_1.ExchangeType.DIRECT,
37
+ name: '',
38
+ };
39
+ }
40
+ of(exchange) {
41
+ return new Client({
42
+ connection: this.connection,
43
+ publishOptions: this.publishOptions,
44
+ consumeOptions: this.consumeOptions,
45
+ exchange,
36
46
  });
37
- return this.connection;
38
47
  }
39
- async consume(options, handlers) {
40
- options = (0, smob_1.merge)(options, this.config.consume);
41
- const exchangeOptions = (0, smob_1.merge)(options.exchange || {}, this.config.exchange);
42
- let queueName = options.queueName || this.config.publish.queueName || '';
43
- const requeueOnFailure = this.config.consume.requeueOnFailure ?? false;
48
+ async consume(_ctxOrFrom, _optionsOrHandlers, _handlers) {
49
+ let from;
50
+ let handlers;
51
+ let options;
52
+ if (typeof _ctxOrFrom === 'string') {
53
+ from = _ctxOrFrom;
54
+ if ((0, consume_1.isConsumeHandlers)(_optionsOrHandlers)) {
55
+ handlers = _optionsOrHandlers;
56
+ options = this.consumeOptions;
57
+ }
58
+ else {
59
+ handlers = _handlers;
60
+ options = (0, utils_1.mergeOptions)(_optionsOrHandlers, this.consumeOptions);
61
+ }
62
+ }
63
+ else {
64
+ from = _ctxOrFrom.from;
65
+ handlers = _ctxOrFrom.handlers;
66
+ if (_ctxOrFrom.options) {
67
+ options = (0, utils_1.mergeOptions)(_ctxOrFrom.options, this.consumeOptions);
68
+ }
69
+ else {
70
+ options = this.consumeOptions;
71
+ }
72
+ }
73
+ const requeueOnFailure = options.requeueOnFailure ?? false;
44
74
  const handleMessage = async (message) => {
45
75
  if (!message) {
46
76
  return;
@@ -56,99 +86,94 @@ class Client {
56
86
  channel.ack(message);
57
87
  }
58
88
  catch (e) {
59
- channel.nack(message);
89
+ channel.nack(message, undefined, requeueOnFailure);
60
90
  }
61
91
  };
62
- const connection = this.useConnection();
63
- const channel = connection.createChannel({
92
+ const channel = this.connection.createChannel({
64
93
  setup: async (channel) => {
65
- if ((0, exchange_1.isDefaultExchange)(exchangeOptions.type)) {
94
+ let queueName = from;
95
+ if ((0, exchange_1.isDefaultExchange)(this.exchange.type)) {
66
96
  if (queueName === '') {
67
- throw new Error('The queue name can not be empty if a non default exchange is selected.');
97
+ throw new Error('The queue name can not be empty if the default exchange is selected.');
68
98
  }
69
99
  await channel.assertQueue(queueName, {
70
100
  durable: true,
71
101
  });
72
102
  }
73
103
  else {
74
- await channel.assertExchange(exchangeOptions.name, exchangeOptions.type, (0, exchange_1.buildDriverExchangeOptions)({
75
- durable: true,
76
- ...exchangeOptions,
77
- }));
104
+ await channel.assertExchange(this.exchange.name || '', this.exchange.type, this.exchange.options);
78
105
  const assertionQueue = await channel.assertQueue('', {
79
106
  durable: false,
80
107
  autoDelete: true,
81
108
  exclusive: true,
82
109
  });
83
- if (typeof exchangeOptions.routingKey === 'undefined') {
84
- throw new Error('The routingKey can not be empty if a non default exchange is selected.');
85
- }
86
- await channel.bindQueue(assertionQueue.queue, this.config.exchange.name, exchangeOptions.routingKey);
110
+ await channel.bindQueue(assertionQueue.queue, this.exchange.name || '', from || '');
87
111
  queueName = assertionQueue.queue;
88
112
  }
89
- if (typeof options.prefetchCount !== 'undefined') {
113
+ if (typeof options.prefetchCount === 'number') {
90
114
  await channel.prefetch(options.prefetchCount);
91
115
  }
92
- await channel.consume(queueName, (message) => handleMessage(message), (0, consume_1.buildDriverConsumeOptions)(options));
116
+ await channel.consume(queueName, (message) => handleMessage(message), options);
93
117
  },
94
118
  });
95
119
  return channel.waitForConnect();
96
120
  }
97
- async publish(options) {
121
+ async publish(_toOrCtx, _data, _options) {
98
122
  let buffer;
99
- if (Buffer.isBuffer(options.content)) {
100
- buffer = options.content;
101
- }
102
- else if (typeof options.content === 'string') {
103
- buffer = Buffer.from(options.content, 'utf-8');
123
+ let to;
124
+ let data;
125
+ let options;
126
+ if (typeof _toOrCtx === 'string') {
127
+ to = _toOrCtx;
128
+ data = _data;
129
+ if (_options) {
130
+ options = (0, utils_1.mergeOptions)(_options, this.publishOptions);
131
+ }
132
+ else {
133
+ options = this.publishOptions;
134
+ }
104
135
  }
105
136
  else {
106
- buffer = Buffer.from(JSON.stringify(options.content), 'utf-8');
137
+ to = _toOrCtx.to;
138
+ data = _toOrCtx.data;
139
+ if (_toOrCtx.options) {
140
+ options = (0, utils_1.mergeOptions)(_toOrCtx.options, this.publishOptions);
141
+ }
142
+ else {
143
+ options = this.publishOptions;
144
+ }
107
145
  }
108
- options = (0, smob_1.merge)(options, this.config.publish || {});
109
- if (typeof options.messageId === 'undefined') {
110
- options.messageId = options.id || (0, uuid_1.v4)();
146
+ if (Buffer.isBuffer(data)) {
147
+ buffer = data;
111
148
  }
112
- const exchangeOptions = (0, smob_1.merge)({}, options.exchange || {}, this.config.exchange);
113
- // publish to default exchange
114
- const queueName = options.queueName ||
115
- this.config.publish.queueName;
116
- const connection = this.useConnection();
149
+ else if (typeof data === 'string') {
150
+ buffer = Buffer.from(data, 'utf-8');
151
+ }
152
+ else {
153
+ buffer = Buffer.from(JSON.stringify(data), 'utf-8');
154
+ }
155
+ const { connection } = this;
117
156
  const channel = connection.createChannel({
118
157
  setup: async (channel) => {
119
- if (!(0, exchange_1.isDefaultExchange)(exchangeOptions.type)) {
120
- await channel.assertExchange(exchangeOptions.name, exchangeOptions.type, (0, exchange_1.buildDriverExchangeOptions)({
158
+ if ((0, exchange_1.isDefaultExchange)(this.exchange.type)) {
159
+ if (!to) {
160
+ throw new Error('The queue name can not be empty if the default exchange is selected.');
161
+ }
162
+ await channel.assertQueue(to, {
121
163
  durable: true,
122
- ...exchangeOptions,
123
- }));
164
+ });
124
165
  return;
125
166
  }
126
- if (typeof queueName === 'undefined' || queueName === '') {
127
- throw new Error('The queue name can not be empty if a non default exchange is selected.');
167
+ if (!this.exchange.name) {
168
+ throw new SyntaxError('A non default exchange requires a name.');
128
169
  }
129
- await channel.assertQueue(queueName, {
130
- durable: true,
131
- });
170
+ await channel.assertExchange(this.exchange.name, this.exchange.type, this.exchange.options);
132
171
  },
133
172
  });
134
- if (!(0, exchange_1.isDefaultExchange)(exchangeOptions.type)) {
135
- if (typeof exchangeOptions.routingKey === 'undefined') {
136
- throw new Error('The routingKey can not be empty if a non default exchange is selected.');
137
- }
138
- const published = await channel.publish(this.config.exchange.name, exchangeOptions.routingKey, buffer, (0, publish_1.buildDriverPublishOptions)({
139
- persistent: true,
140
- ...options,
141
- }));
142
- await channel.close();
143
- return published;
144
- }
145
- if (typeof queueName === 'undefined' || queueName === '') {
146
- throw new Error('The queue name can not be empty if a non default exchange is selected.');
173
+ if (!to) {
174
+ throw new SyntaxError('The publish operation requires a destination.');
147
175
  }
148
- const published = await channel.sendToQueue(queueName, buffer, (0, publish_1.buildDriverPublishOptions)({
149
- persistent: true,
150
- ...options,
151
- }));
176
+ const published = await channel.publish(this.exchange.name || '', to, buffer, options);
152
177
  await channel.close();
153
178
  return published;
154
179
  }
@@ -1,2 +1 @@
1
1
  export * from './type';
2
- export * from './utils';
@@ -21,4 +21,3 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
23
  __exportStar(require("./type"), exports);
24
- __exportStar(require("./utils"), exports);
@@ -1,13 +1,7 @@
1
- import type { PublishOptions } from '../type';
2
- export type PublishOptionsExtended<T = any> = {
3
- /**
4
- * Alias for: messageId
5
- *
6
- * Default: <generated uuid>
7
- */
8
- id?: string;
9
- /**
10
- * The message data.
11
- */
12
- content: T;
13
- } & PublishOptions;
1
+ import type { Options } from 'amqplib';
2
+ export type PublishOptions = Options.Publish;
3
+ export type PublishContext = {
4
+ to: string;
5
+ data: any;
6
+ options?: PublishOptions;
7
+ };
package/dist/type.d.ts CHANGED
@@ -1,30 +1,14 @@
1
1
  import type { connect } from 'amqp-connection-manager';
2
2
  import type { Options } from 'amqplib';
3
- import type { ExchangeOptions } from './exchange';
3
+ import type { ConsumeOptions } from './consume';
4
+ import type { Exchange } from './exchange';
5
+ import type { PublishOptions } from './publish';
4
6
  export type Connection = ReturnType<typeof connect>;
5
- type CommonOptions = {
6
- /**
7
- * Exchange
8
- *
9
- * default: undefined
10
- */
11
- exchange?: Partial<ExchangeOptions>;
12
- /**
13
- * Queue name.
14
- *
15
- * default: ''
16
- */
17
- queueName?: string;
7
+ export type ConnectionOptions = Options.Connect | string;
8
+ export type ClientContext = {
9
+ connection?: Connection;
10
+ connectionOptions?: ConnectionOptions;
11
+ exchange?: Exchange;
12
+ publishOptions?: PublishOptions;
13
+ consumeOptions?: ConsumeOptions;
18
14
  };
19
- export type PublishOptions = CommonOptions & Options.Publish;
20
- export type ConsumeOptions = CommonOptions & Options.Consume & {
21
- /**
22
- * Default: false
23
- */
24
- requeueOnFailure?: boolean;
25
- /**
26
- * Default: undefined
27
- */
28
- prefetchCount?: number;
29
- };
30
- export {};
package/dist/utils.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare function removeKeysFromOptions<T extends Record<string, any>, K extends (keyof T)[]>(options: T, keys: K): Omit<T, K[number]>;
2
- export declare function wait(ms: number): Promise<void>;
1
+ declare const mergeOptions: import("smob").Merger;
2
+ export { mergeOptions, };
package/dist/utils.js CHANGED
@@ -1,21 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.wait = exports.removeKeysFromOptions = void 0;
3
+ exports.mergeOptions = void 0;
4
4
  const smob_1 = require("smob");
5
- function removeKeysFromOptions(options, keys) {
6
- for (let i = 0; i < keys.length; i++) {
7
- if ((0, smob_1.hasOwnProperty)(options, keys[i])) {
8
- delete options[keys[i]];
5
+ const exchange_1 = require("./exchange");
6
+ const mergeOptions = (0, smob_1.createMerger)({
7
+ priority: 'left',
8
+ inPlace: false,
9
+ clone: true,
10
+ array: true,
11
+ arrayDistinct: true,
12
+ strategy(target, key, value) {
13
+ if (key !== 'exchange') {
14
+ return undefined;
9
15
  }
10
- }
11
- return options;
12
- }
13
- exports.removeKeysFromOptions = removeKeysFromOptions;
14
- async function wait(ms) {
15
- return new Promise((resolve) => {
16
- setTimeout(() => {
17
- resolve();
18
- }, ms);
19
- });
20
- }
21
- exports.wait = wait;
16
+ if (!(0, exchange_1.isExchange)(target[key]) ||
17
+ !(0, exchange_1.isExchange)(value)) {
18
+ return undefined;
19
+ }
20
+ return target;
21
+ },
22
+ });
23
+ exports.mergeOptions = mergeOptions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "amqp-extension",
3
- "version": "3.3.0",
3
+ "version": "4.0.0-beta.1",
4
4
  "description": "An amqp extension with functions and utility functions to consume and publish queue messages.",
5
5
  "main": "./dist/index.js",
6
6
  "typings": "dist/index.d.ts",
@@ -37,17 +37,17 @@
37
37
  "dependencies": {
38
38
  "@types/amqplib": "^0.10.5",
39
39
  "amqp-connection-manager": "^4.1.14",
40
- "amqplib": "^0.10.3",
41
- "smob": "^1.4.1",
40
+ "amqplib": "^0.10.4",
41
+ "smob": "^1.5.0",
42
42
  "uuid": "^9.0.1"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@tada5hi/commitlint-config": "^1.1.7",
46
- "@tada5hi/eslint-config-typescript": "^1.2.6",
46
+ "@tada5hi/eslint-config-typescript": "^1.2.10",
47
47
  "@tada5hi/semantic-release": "^0.3.1",
48
- "@tada5hi/tsconfig": "^0.5.0",
48
+ "@tada5hi/tsconfig": "^0.5.1",
49
49
  "@types/jest": "^29.5.12",
50
- "@types/node": "^20.11.30",
50
+ "@types/node": "^20.14.2",
51
51
  "@types/uuid": "^9.0.8",
52
52
  "cross-env": "^7.0.3",
53
53
  "envix": "^1.5.0",
@@ -55,8 +55,8 @@
55
55
  "husky": "^8.0.3",
56
56
  "jest": "^29.7.0",
57
57
  "semantic-release": "^22.0.7",
58
- "testcontainers": "^10.7.2",
59
- "ts-jest": "^29.1.2",
58
+ "testcontainers": "^10.9.0",
59
+ "ts-jest": "^29.1.4",
60
60
  "typescript": "^5.4.2"
61
61
  }
62
62
  }
@@ -1,3 +0,0 @@
1
- import type { Options } from 'amqplib';
2
- import type { PublishOptionsExtended } from './type';
3
- export declare function buildDriverPublishOptions(options: PublishOptionsExtended): Options.Publish;
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildDriverPublishOptions = void 0;
4
- const utils_1 = require("../utils");
5
- function buildDriverPublishOptions(options) {
6
- return (0, utils_1.removeKeysFromOptions)({ ...options }, [
7
- 'exchange',
8
- 'queueName',
9
- 'content',
10
- 'id',
11
- ]);
12
- }
13
- exports.buildDriverPublishOptions = buildDriverPublishOptions;
File without changes
File without changes