fastify-rabbitmq 0.0.1-alpha.2 → 1.1.0

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/README.md CHANGED
@@ -1,140 +1,88 @@
1
- # Fastify RabbitMq
1
+ # Fastify RabbitMQ
2
2
 
3
3
  A Fastify RabbitMQ Plugin Developed in Pure TypeScript.
4
- It uses the [node-amqp-connection-manager](https://github.com/jwalton/node-amqp-connection-manager) plugin as a wrapper.
4
+ It uses the [rabbitmq-client](https://github.com/cody-greene/node-rabbitmq-client/) plugin as a wrapper.
5
5
 
6
- This comes right from the README on ```node-amqp-connection-manager```:
7
-
8
- > Features
9
- > * Automatically reconnect when your amqplib broker dies in a fire.
10
- > * Round-robin connections between multiple brokers in a cluster.
11
- > * If messages are sent while the broker is unavailable, queues messages in memory until we reconnect.
12
- > * Supports both promises and callbacks (using promise-breaker)
13
- > * Very un-opinionated library—a thin wrapper around amqplib.
14
-
15
- ## Notice
16
-
17
- This NPM package is still going **active development** so things will break. Review the issues list for on going development work and if you want to help out, submit a PR.
18
-
19
- Help Wanted:
20
- * Documentation
21
- * GitHub Workflows
22
- * Unit Testing using Jest
6
+ The build exports this to valid ESM and CJS for ease of cross-compatibility.
23
7
 
24
8
  ## Table of Contents
25
9
 
26
- 1. [Notice](#notice)
27
- 2. [Install](#install)
10
+ 1. [Install](#install)
28
11
  2. [Basic Usage](#basic-usage)
29
12
  3. [Full Documentation](#full-documentation)
30
- 1. [Options](#options)
13
+ 1) [Options](#options)
31
14
  4. [Acknowledgements](#acknowledgements)
32
15
  5. [License](#license)
33
16
 
34
17
  ## Install
35
- ```
36
- npm i fastify-rabbitmq amqplib
37
- npm i --save-dev @types/amqplib
18
+
19
+ ```markdown
20
+ npm i fastify-rabbitmq
38
21
  ```
39
22
 
40
23
  ## Basic Usage
24
+
41
25
  Register this as a plugin.
42
26
  Make sure it is loaded before any ***routes*** are loaded.
43
27
 
44
28
  ### Quick Setup on the Server Side
45
29
 
46
30
  ```typescript
47
- export default fp<any>(async (fastify: FastifyInstance, options: FastifyPluginOptions) => {
48
-
49
- fastify.register(fastifyRabbit, {
50
- urLs: ['amqp://localhost']
31
+ export default fp<FastifyRabbitMQOptions>((fastify, options, done) => {
32
+
33
+ void fastify.register(fastifyRabbit, {
34
+ connection: `amqp://guest:guest@localhost`
51
35
  })
52
36
 
53
- fastify.ready().then(async () => {
54
- fastify.log.debug('[rabbitmq] Started RabbitMQ')
55
- fastify.rabbitmq.channel = fastify.rabbitmq.createChannel({
56
- json: true,
57
- setup: function (channel: ConfirmChannel) {
58
- return Promise.all([
59
- channel.assertQueue('server', {durable: true}),
60
- channel.prefetch(1),
61
- channel.consume('server', async (message) => {
62
- fastify.log.debug(JSON.stringify(data))
63
- fastify.rabbitmq.channel?.ack(message);
64
- })
65
- ]);
66
- },
67
- })
37
+ void fastify.ready().then(async () => {
38
+
39
+ const snowAssignAssetTag = fastify.rabbitmq.createConsumer({
40
+ queue: 'foo',
41
+ queueOptions: {durable: true}
42
+ }, async (msg: any) => {
43
+ console.log(msg) // ==> bar
44
+ })
45
+
68
46
  })
69
-
47
+
70
48
  });
71
49
  ```
72
-
73
- Within server instance can also call the same queue as long as it has access to the ``fastify.rabbitmq`` decorator.
74
- Traditionally, a separate app is running and is the client sending messages to the client.
75
-
76
50
  ### Quick Setup on the Client Side
77
51
 
78
- First set up your plugin to register the plugin.
79
-
80
- ```typescript
81
- import {ConfirmChannel} from "amqplib";
82
- import {
83
- FastifyInstance,
84
- FastifyPluginOptions,
85
- } from 'fastify';
86
- import fp from "fastify-plugin";
87
- import fastifyRabbit from "fastify-rabbitmq"
88
-
89
- export default fp<any>(async (fastify: FastifyInstance, options: FastifyPluginOptions) => {
90
-
91
- fastify.register(fastifyRabbit, {
92
- urLs: ['amqp://localhost']
93
- })
52
+ Within any "endpoint" function, or if you have access to ```fastify.rabbitmq``` you can then call:
94
53
 
95
- fastify.ready().then(async () => {
96
-
97
- fastify.rabbitmq.channel = fastify.rabbitmq.createChannel({
98
- json: true,
99
- setup: function (channel: ConfirmChannel) {
100
- return channel.assertQueue('client', { durable: true });
101
- }
102
- });
103
-
104
- })
54
+ ```js
55
+ fastify.get('/rabbitmq', async (request, reply) => {
56
+ let pub = request.rabbitmq.createPublisher({
57
+ confirm: true,
58
+ maxAttempts: 1
59
+ })
105
60
 
61
+ await pub.send('foo', "bar") // ==> sent to foo queue
106
62
  })
107
63
  ```
108
64
 
109
- Now in your routes or anywhere the fastify.rabbitmq can be accessed:
110
-
111
- ```typescript
112
- fastify.get('/rabbitmq', {}, async (request, reply) => {
113
- try {
114
- fastify.rabbitmq.channel?.sendToQueue('server', { foo: 'bar'})
115
- return reply.code(200).send({ result: true});
116
- } catch (error) {
117
- return reply.send(404);
118
- }
119
- });
120
- ```
65
+ Sending the string ```bar``` to the queue called ```foo```.
121
66
 
122
67
  ## Full Documentation
123
68
 
124
69
  ### Options
125
70
 
126
71
  ```typescript
127
- export interface FastifyRabbitMQOptions extends AmqpConnectionManagerOptions {
128
- logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'
72
+ export interface FastifyRabbitMQOptions {
73
+ /** Connection String or object pointing to the RabbitMQ Broker Services */
74
+ connection: string | ConnectionOptions
75
+ /** To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time. */
129
76
  namespace?: string
130
- urLs: ConnectionUrl | ConnectionUrl[] | undefined | null
131
77
  }
132
78
  ```
79
+
133
80
  #### FastifyRabbitMQOptions
134
81
 
135
- ##### `logLevel`
82
+ ##### `connection`
136
83
 
137
- Set the log level for Fastify RabbitMQ plugin. This is usefull for development work. The default value is ```silent```
84
+ Connection String or object pointing to the RabbitMQ Broker Services.
85
+ This can be an object of ```ConnectionOptions``` from the ```rabbitmq-client``` plugin options.
138
86
 
139
87
  ##### `namespace`
140
88
 
@@ -142,37 +90,13 @@ If you need more than one "connection" to a different set and/or array of Rabbit
142
90
  either on network or cloud, each registration of the plugin needs it to be in its own namespace.
143
91
  If not provided, your application will fail to load.
144
92
 
145
- ##### `urLs`
146
-
147
- This needs to be an array of the RabbitMQ host:
148
-
149
- ```typescript
150
- fastify.register(fastifyRabbit, {
151
- urLs: ['amqp://localhost']
152
- })
153
- ```
154
-
155
- This is not needed
156
- if you use AmqpConnectionManagerOptions [findServers](https://github.com/jwalton/node-amqp-connection-manager#connecturls-options)
157
- which overrides the urls value if it's set.
158
- If you need
159
- to pass in credentials to the RabbitMQ or vHost for the connection review the [connection options](#amqpconnectionmanageroptions).
160
-
161
- Please review the options [here](https://github.com/jwalton/node-amqp-connection-manager/blob/master/src/AmqpConnectionManager.ts#L26C13-L26C34).
162
- (Note:
163
- This URL might bring you to the wrong line
164
- if the file has been changed on the ```node-amqp-connection-manager``` package.)
165
-
166
- #### ```AmqpConnectionManagerOptions```
167
-
168
- See [Connection Options](https://github.com/jwalton/node-amqp-connection-manager#connecturls-options) for 'node-amqp-connection-manager' for detailed options that can be passed in.
169
93
 
170
94
  ## Acknowledgements
171
95
 
172
- - [node-amqp-connection-manager](https://github.com/jwalton/node-amqp-connection-manager)
96
+ - [rabbitmq-client](https://www.npmjs.com/package/rabbitmq-client)
173
97
  - [fastify](https://fastify.dev/)
174
- - ...and of course my Wife and Baby Girl.
98
+ - ... and my Wife and Baby Girl.
175
99
 
176
100
  ## License
177
101
 
178
- Licensed under [MIT](./LICENSE).
102
+ Licensed under [MIT](./LICENSE).
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.errors = void 0;
7
+ const error_1 = __importDefault(require("@fastify/error"));
8
+ exports.errors = {
9
+ /** Error if there is an invalid option used during registration. */
10
+ FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: (0, error_1.default)('FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS', 'Invalid options: %s'),
11
+ /** Error if there is an setup error of the plugin itself. */
12
+ FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: (0, error_1.default)('FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS', 'Setup error: %s'),
13
+ /** If an invalid usage error was done, this error would pop up. */
14
+ FASTIFY_RABBIT_MQ_ERR_USAGE: (0, error_1.default)('FASTIFY_RABBIT_MQ_ERR_USAGE', 'Usage error: %s')
15
+ };
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.decorateFastifyInstance = void 0;
21
+ const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
22
+ const rabbitmq_client_1 = require("rabbitmq-client");
23
+ const errors_js_1 = require("./errors.js");
24
+ const validation_js_1 = require("./validation.js");
25
+ __exportStar(require("./types.js"), exports);
26
+ const decorateFastifyInstance = (fastify, options, connection) => {
27
+ const { namespace = '' } = options;
28
+ if (typeof namespace !== 'undefined') {
29
+ fastify.log.debug('[fastify-rabbitmq] Namespace: %s', namespace);
30
+ }
31
+ if (typeof namespace !== 'undefined' && namespace !== '') {
32
+ if (typeof fastify.rabbitmq === 'undefined') {
33
+ fastify.decorate('rabbitmq', Object.create(null));
34
+ }
35
+ if (typeof fastify.rabbitmq[namespace] !== 'undefined') {
36
+ throw new errors_js_1.errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(`Already registered with namespace: ${namespace}`);
37
+ }
38
+ fastify.log.trace('[fastify-rabbitmq] Decorate Fastify with Namespace: %', namespace);
39
+ fastify.rabbitmq[namespace] = connection;
40
+ }
41
+ else {
42
+ if (typeof fastify.rabbitmq !== 'undefined') {
43
+ throw new errors_js_1.errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS('Already registered.');
44
+ }
45
+ }
46
+ if (typeof fastify.rabbitmq === 'undefined') {
47
+ fastify.log.trace('[fastify-rabbitmq] Decorate Fastify');
48
+ fastify.decorate('rabbitmq', connection);
49
+ }
50
+ };
51
+ exports.decorateFastifyInstance = decorateFastifyInstance;
52
+ /**
53
+ * Main Function
54
+ * @since 1.0.0
55
+ * @example
56
+ * This is the basics on how to use this plugin:
57
+ * ```js
58
+ * app.register(fastifyRabbit, {
59
+ * connection: 'amqp://guest:guest@localhost'
60
+ * })
61
+ * ```
62
+ * This will allow you to read from your Fastify "object" and
63
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
64
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
65
+ * this plugin to execute functions it provides.
66
+ *
67
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
68
+ *
69
+ */
70
+ const fastifyRabbit = (0, fastify_plugin_1.default)(async (fastify, opts, done) => {
71
+ await (0, validation_js_1.validateOpts)(opts);
72
+ const { connection } = opts;
73
+ const c = new rabbitmq_client_1.Connection(connection);
74
+ decorateFastifyInstance(fastify, opts, c);
75
+ done();
76
+ });
77
+ exports.default = fastifyRabbit;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateOpts = void 0;
4
+ const errors_js_1 = require("./errors.js");
5
+ const validateOpts = async (options) => {
6
+ // Mandatory
7
+ if (typeof options.connection === 'undefined') {
8
+ throw new errors_js_1.errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS('connection or findServers must be defined.');
9
+ }
10
+ // Mandatory
11
+ if (typeof options.connection !== 'undefined') {
12
+ if (typeof options.connection !== 'object') {
13
+ // we need to do some sort of check here to make sure RabbitMQOptions is "valid"
14
+ }
15
+ }
16
+ };
17
+ exports.validateOpts = validateOpts;
@@ -0,0 +1,13 @@
1
+ import { ConnectionOptions } from 'rabbitmq-client';
2
+ export interface FastifyRabbitMQOptions {
3
+ /**
4
+ * @since 1.0.0
5
+ * @description Connection String or object pointing to the RabbitMQ Broker Services
6
+ */
7
+ connection: string | ConnectionOptions;
8
+ /**
9
+ * @since 1.0.0
10
+ * @description To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time.
11
+ */
12
+ namespace?: string;
13
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=decorate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorate.js","sourceRoot":"","sources":["../../src/decorate.ts"],"names":[],"mappings":""}
@@ -0,0 +1,14 @@
1
+ export declare const errors: {
2
+ /** Error if there is an invalid option used during registration. */
3
+ FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: import("@fastify/error").FastifyErrorConstructor<{
4
+ code: "FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS";
5
+ }, [any?, any?, any?]>;
6
+ /** Error if there is an setup error of the plugin itself. */
7
+ FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: import("@fastify/error").FastifyErrorConstructor<{
8
+ code: "FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS";
9
+ }, [any?, any?, any?]>;
10
+ /** If an invalid usage error was done, this error would pop up. */
11
+ FASTIFY_RABBIT_MQ_ERR_USAGE: import("@fastify/error").FastifyErrorConstructor<{
12
+ code: "FASTIFY_RABBIT_MQ_ERR_USAGE";
13
+ }, [any?, any?, any?]>;
14
+ };
@@ -0,0 +1,10 @@
1
+ import createError from '@fastify/error';
2
+ export const errors = {
3
+ /** Error if there is an invalid option used during registration. */
4
+ FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: createError('FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS', 'Invalid options: %s'),
5
+ /** Error if there is an setup error of the plugin itself. */
6
+ FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: createError('FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS', 'Setup error: %s'),
7
+ /** If an invalid usage error was done, this error would pop up. */
8
+ FASTIFY_RABBIT_MQ_ERR_USAGE: createError('FASTIFY_RABBIT_MQ_ERR_USAGE', 'Usage error: %s')
9
+ };
10
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,WAAW,MAAM,gBAAgB,CAAA;AAExC,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,oEAAoE;IACpE,kCAAkC,EAAE,WAAW,CAC7C,oCAAoC,EACpC,qBAAqB,CACtB;IACD,6DAA6D;IAC7D,kCAAkC,EAAE,WAAW,CAC7C,oCAAoC,EACpC,iBAAiB,CAClB;IACD,mEAAmE;IACnE,2BAA2B,EAAE,WAAW,CACtC,6BAA6B,EAC7B,iBAAiB,CAClB;CACF,CAAA"}
@@ -0,0 +1,26 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { ConnectionOptions } from 'rabbitmq-client';
3
+ import { FastifyRabbitMQOptions } from './decorate.js';
4
+ export * from './types.js';
5
+ declare const decorateFastifyInstance: (fastify: FastifyInstance, options: FastifyRabbitMQOptions, connection: any) => void;
6
+ /**
7
+ * Main Function
8
+ * @since 1.0.0
9
+ * @example
10
+ * This is the basics on how to use this plugin:
11
+ * ```js
12
+ * app.register(fastifyRabbit, {
13
+ * connection: 'amqp://guest:guest@localhost'
14
+ * })
15
+ * ```
16
+ * This will allow you to read from your Fastify "object" and
17
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
18
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
19
+ * this plugin to execute functions it provides.
20
+ *
21
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
22
+ *
23
+ */
24
+ declare const fastifyRabbit: import("fastify").FastifyPluginCallback<FastifyRabbitMQOptions, import("fastify").RawServerDefault, import("fastify").FastifyTypeProviderDefault, import("fastify").FastifyBaseLogger>;
25
+ export default fastifyRabbit;
26
+ export { decorateFastifyInstance, FastifyRabbitMQOptions, ConnectionOptions };
@@ -0,0 +1,58 @@
1
+ import fp from 'fastify-plugin';
2
+ import { Connection as RabbitMQConnection } from 'rabbitmq-client';
3
+ import { errors } from './errors.js';
4
+ import { validateOpts } from './validation.js';
5
+ export * from './types.js';
6
+ const decorateFastifyInstance = (fastify, options, connection) => {
7
+ const { namespace = '' } = options;
8
+ if (typeof namespace !== 'undefined') {
9
+ fastify.log.debug('[fastify-rabbitmq] Namespace: %s', namespace);
10
+ }
11
+ if (typeof namespace !== 'undefined' && namespace !== '') {
12
+ if (typeof fastify.rabbitmq === 'undefined') {
13
+ fastify.decorate('rabbitmq', Object.create(null));
14
+ }
15
+ if (typeof fastify.rabbitmq[namespace] !== 'undefined') {
16
+ throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(`Already registered with namespace: ${namespace}`);
17
+ }
18
+ fastify.log.trace('[fastify-rabbitmq] Decorate Fastify with Namespace: %', namespace);
19
+ fastify.rabbitmq[namespace] = connection;
20
+ }
21
+ else {
22
+ if (typeof fastify.rabbitmq !== 'undefined') {
23
+ throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS('Already registered.');
24
+ }
25
+ }
26
+ if (typeof fastify.rabbitmq === 'undefined') {
27
+ fastify.log.trace('[fastify-rabbitmq] Decorate Fastify');
28
+ fastify.decorate('rabbitmq', connection);
29
+ }
30
+ };
31
+ /**
32
+ * Main Function
33
+ * @since 1.0.0
34
+ * @example
35
+ * This is the basics on how to use this plugin:
36
+ * ```js
37
+ * app.register(fastifyRabbit, {
38
+ * connection: 'amqp://guest:guest@localhost'
39
+ * })
40
+ * ```
41
+ * This will allow you to read from your Fastify "object" and
42
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
43
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
44
+ * this plugin to execute functions it provides.
45
+ *
46
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
47
+ *
48
+ */
49
+ const fastifyRabbit = fp(async (fastify, opts, done) => {
50
+ await validateOpts(opts);
51
+ const { connection } = opts;
52
+ const c = new RabbitMQConnection(connection);
53
+ decorateFastifyInstance(fastify, opts, c);
54
+ done();
55
+ });
56
+ export default fastifyRabbit;
57
+ export { decorateFastifyInstance };
58
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,gBAAgB,CAAA;AAC/B,OAAO,EAAoB,UAAU,IAAI,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAEpF,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAA;AAC9C,cAAc,YAAY,CAAA;AAE1B,MAAM,uBAAuB,GAAG,CAAC,OAAwB,EAAE,OAA+B,EAAE,UAAe,EAAQ,EAAE;IACnH,MAAM,EACJ,SAAS,GAAG,EAAE,EACf,GAAG,OAAO,CAAA;IAEX,IAAI,OAAO,SAAS,KAAK,WAAW,EAAE;QACpC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,kCAAkC,EAAE,SAAS,CAAC,CAAA;KACjE;IACD,IAAI,OAAO,SAAS,KAAK,WAAW,IAAI,SAAS,KAAK,EAAE,EAAE;QACxD,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,WAAW,EAAE;YAC3C,OAAO,CAAC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;SAClD;QAED,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,KAAK,WAAW,EAAE;YACtD,MAAM,IAAI,MAAM,CAAC,kCAAkC,CAAC,sCAAsC,SAAS,EAAE,CAAC,CAAA;SACvG;QAED,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,uDAAuD,EAAE,SAAS,CAAC,CAAA;QACrF,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,GAAG,UAAU,CAAA;KACzC;SAAM;QACL,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,WAAW,EAAE;YAC3C,MAAM,IAAI,MAAM,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,CAAA;SAC3E;KACF;IAED,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,WAAW,EAAE;QAC3C,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAA;QACxD,OAAO,CAAC,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC,CAAA;KACzC;AACH,CAAC,CAAA;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,aAAa,GAAG,EAAE,CAAyB,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE;IAC7E,MAAM,YAAY,CAAC,IAAI,CAAC,CAAA;IAExB,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,CAAA;IAE3B,MAAM,CAAC,GAAG,IAAI,kBAAkB,CAAC,UAAU,CAAC,CAAA;IAE5C,uBAAuB,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAA;IAEzC,IAAI,EAAE,CAAA;AACR,CAAC,CAAC,CAAA;AAEF,eAAe,aAAa,CAAA;AAE5B,OAAO,EAAE,uBAAuB,EAA6C,CAAA"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,12 @@
1
+ import { Connection as RabbitMQConnection } from 'rabbitmq-client';
2
+ declare module 'fastify' {
3
+ interface FastifyInstance {
4
+ /** Main Decorator for Fastify **/
5
+ rabbitmq: RabbitMQConnection & fastifyRabbitMQ.FastifyRabbitMQNO;
6
+ }
7
+ }
8
+ export declare namespace fastifyRabbitMQ {
9
+ interface FastifyRabbitMQNO {
10
+ [namespace: string]: RabbitMQConnection;
11
+ }
12
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ import { FastifyRabbitMQOptions } from './decorate.js';
2
+ export declare const validateOpts: (options: FastifyRabbitMQOptions) => Promise<void>;
@@ -0,0 +1,14 @@
1
+ import { errors } from './errors.js';
2
+ export const validateOpts = async (options) => {
3
+ // Mandatory
4
+ if (typeof options.connection === 'undefined') {
5
+ throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS('connection or findServers must be defined.');
6
+ }
7
+ // Mandatory
8
+ if (typeof options.connection !== 'undefined') {
9
+ if (typeof options.connection !== 'object') {
10
+ // we need to do some sort of check here to make sure RabbitMQOptions is "valid"
11
+ }
12
+ }
13
+ };
14
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../../src/validation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,EAAE,OAA+B,EAAiB,EAAE;IACnF,YAAY;IACZ,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,WAAW,EAAE;QAC7C,MAAM,IAAI,MAAM,CAAC,kCAAkC,CAAC,4CAA4C,CAAC,CAAA;KAClG;IAED,YAAY;IACZ,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,WAAW,EAAE;QAC7C,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,EAAE;YAC1C,gFAAgF;SACjF;KACF;AACH,CAAC,CAAA"}
@@ -0,0 +1,13 @@
1
+ import { ConnectionOptions } from 'rabbitmq-client';
2
+ export interface FastifyRabbitMQOptions {
3
+ /**
4
+ * @since 1.0.0
5
+ * @description Connection String or object pointing to the RabbitMQ Broker Services
6
+ */
7
+ connection: string | ConnectionOptions;
8
+ /**
9
+ * @since 1.0.0
10
+ * @description To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time.
11
+ */
12
+ namespace?: string;
13
+ }
@@ -0,0 +1,14 @@
1
+ export declare const errors: {
2
+ /** Error if there is an invalid option used during registration. */
3
+ FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: import("@fastify/error").FastifyErrorConstructor<{
4
+ code: "FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS";
5
+ }, [any?, any?, any?]>;
6
+ /** Error if there is an setup error of the plugin itself. */
7
+ FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: import("@fastify/error").FastifyErrorConstructor<{
8
+ code: "FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS";
9
+ }, [any?, any?, any?]>;
10
+ /** If an invalid usage error was done, this error would pop up. */
11
+ FASTIFY_RABBIT_MQ_ERR_USAGE: import("@fastify/error").FastifyErrorConstructor<{
12
+ code: "FASTIFY_RABBIT_MQ_ERR_USAGE";
13
+ }, [any?, any?, any?]>;
14
+ };
@@ -0,0 +1,26 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { ConnectionOptions } from 'rabbitmq-client';
3
+ import { FastifyRabbitMQOptions } from './decorate.js';
4
+ export * from './types.js';
5
+ declare const decorateFastifyInstance: (fastify: FastifyInstance, options: FastifyRabbitMQOptions, connection: any) => void;
6
+ /**
7
+ * Main Function
8
+ * @since 1.0.0
9
+ * @example
10
+ * This is the basics on how to use this plugin:
11
+ * ```js
12
+ * app.register(fastifyRabbit, {
13
+ * connection: 'amqp://guest:guest@localhost'
14
+ * })
15
+ * ```
16
+ * This will allow you to read from your Fastify "object" and
17
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
18
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
19
+ * this plugin to execute functions it provides.
20
+ *
21
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
22
+ *
23
+ */
24
+ declare const fastifyRabbit: import("fastify").FastifyPluginCallback<FastifyRabbitMQOptions, import("fastify").RawServerDefault, import("fastify").FastifyTypeProviderDefault, import("fastify").FastifyBaseLogger>;
25
+ export default fastifyRabbit;
26
+ export { decorateFastifyInstance, FastifyRabbitMQOptions, ConnectionOptions };
@@ -0,0 +1,12 @@
1
+ import { Connection as RabbitMQConnection } from 'rabbitmq-client';
2
+ declare module 'fastify' {
3
+ interface FastifyInstance {
4
+ /** Main Decorator for Fastify **/
5
+ rabbitmq: RabbitMQConnection & fastifyRabbitMQ.FastifyRabbitMQNO;
6
+ }
7
+ }
8
+ export declare namespace fastifyRabbitMQ {
9
+ interface FastifyRabbitMQNO {
10
+ [namespace: string]: RabbitMQConnection;
11
+ }
12
+ }
@@ -0,0 +1,2 @@
1
+ import { FastifyRabbitMQOptions } from './decorate.js';
2
+ export declare const validateOpts: (options: FastifyRabbitMQOptions) => Promise<void>;
package/package.json CHANGED
@@ -1,25 +1,49 @@
1
1
  {
2
2
  "name": "fastify-rabbitmq",
3
- "version": "0.0.1-alpha.2",
4
- "description": "A Fastify RabbitMQ Plugin Developed in Pure TypeScript using the AMQPLIB",
5
- "type": "module",
6
- "types": "dist/index.d.ts",
7
- "main": "dist/index.js",
3
+ "version": "1.1.0",
4
+ "description": "A Fastify RabbitMQ Plugin Developed in Pure TypeScript.",
5
+ "module": "./dist/esm/index.js",
6
+ "main": "./dist/cjs/index.js",
7
+ "types": "./dist/types/index.d.ts",
8
+ "release": {
9
+ "branches": [
10
+ "main"
11
+ ]
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/types/index.d.ts",
16
+ "import": "./dist/esm/index.js",
17
+ "require": "./dist/cjs/index.js",
18
+ "default": "./dist/cjs/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist/**/*"
23
+ ],
8
24
  "scripts": {
9
- "build": "tsc",
25
+ "clean": "rm -rf dist coverage",
26
+ "build": "tsc && tsc -p tsconfig.cjs.json && tsc -p tsconfig.types.json && ./bin/build-types.sh",
10
27
  "build:watch": "tsc -w",
11
- "lint": "ts-standard",
12
- "lint:fix": "ts-standard --fix",
28
+ "lint": "ts-standard --parser @typescript-eslint/parser | snazzy",
29
+ "lint:fix": "ts-standard --fix --parser @typescript-eslint/parser | snazzy",
30
+ "pack": "npm run clean && npm run test:ci && npm run build && npm pack",
31
+ "prepublishOnly": "npm run clean && npm run build",
13
32
  "test": "jest",
14
- "update": "npx npm-check-updates -u && npm install"
33
+ "test:ci": "jest --ci",
34
+ "test:coverage": "jest --coverage",
35
+ "typedoc": "typedoc",
36
+ "typedoc:watch": "typedoc -watch",
37
+ "semantic-release": "semantic-release",
38
+ "semantic-release:dryRun": "semantic-release --dry-run",
39
+ "update": "npx npm-check-updates -u && npm install && npm run test"
15
40
  },
16
41
  "repository": {
17
42
  "type": "git",
18
- "url": "git+https://github.com/Bugs5382/fastify-rabbitmq.git"
43
+ "url": "https://github.com/Bugs5382/fastify-rabbitmq"
19
44
  },
20
45
  "keywords": [
21
- "amqp-connection-manager",
22
- "amqplib",
46
+ "rabbitmq-client",
23
47
  "typescript",
24
48
  "rabbitmq",
25
49
  "fastify",
@@ -32,22 +56,35 @@
32
56
  },
33
57
  "homepage": "https://github.com/Bugs5382/fastify-rabbitmq#readme",
34
58
  "dependencies": {
35
- "amqp-connection-manager": "^4.1.14",
36
- "fastify-plugin": "^4.5.1"
59
+ "@fastify/error": "^3.4.1",
60
+ "@types/amqplib": "^0.10.4",
61
+ "fastify-plugin": "^4.5.1",
62
+ "promise-tools": "^2.1.0",
63
+ "rabbitmq-client": "^4.4.0",
64
+ "randomstring": "^1.3.0"
37
65
  },
38
66
  "devDependencies": {
39
- "@types/amqplib": "^0.10.1",
40
- "@types/jest": "^29.5.3",
41
- "@types/node": "^20.4.10",
42
- "fastify": "^4.21.0",
43
- "jest": "^29.6.2",
44
- "npm-check-updates": "^16.11.1",
67
+ "@semantic-release/changelog": "^6.0.3",
68
+ "@semantic-release/commit-analyzer": "^11.1.0",
69
+ "@semantic-release/git": "^10.0.1",
70
+ "@semantic-release/release-notes-generator": "^12.1.0",
71
+ "@types/jest": "^29.5.8",
72
+ "@types/node": "^20.9.0",
73
+ "@types/randomstring": "^1.1.11",
74
+ "@typescript-eslint/parser": "^6.11.0",
75
+ "fastify": "^4.24.3",
76
+ "jest": "^29.7.0",
77
+ "jest-ts-webcompat-resolver": "^1.0.0",
78
+ "npm-check-updates": "^16.14.6",
45
79
  "pre-commit": "^1.2.2",
80
+ "semantic-release": "^22.0.7",
81
+ "snazzy": "^9.0.0",
46
82
  "ts-jest": "^29.1.1",
47
83
  "ts-node": "^10.9.1",
48
84
  "ts-standard": "^12.0.2",
49
- "tsd": "^0.28.1",
50
- "typescript": "^5.1.6"
85
+ "tsd": "^0.29.0",
86
+ "typedoc": "^0.25.3",
87
+ "typescript": "^5.2.2"
51
88
  },
52
89
  "pre-commit": []
53
90
  }
package/dist/index.d.ts DELETED
@@ -1,27 +0,0 @@
1
- import { Channel, ConfirmChannel } from 'amqplib';
2
- import { ChannelWrapper } from 'amqp-connection-manager';
3
- import type { AmqpConnectionManager, AmqpConnectionManagerOptions, ConnectionUrl } from 'amqp-connection-manager';
4
- import { FastifyInstance } from 'fastify';
5
- import FastifyRabbitMQOptions = fastifyRabbitMQ.FastifyRabbitMQOptions;
6
- import FastifyRabbitMQObject = fastifyRabbitMQ.FastifyRabbitMQObject;
7
- declare module 'fastify' {
8
- interface FastifyInstance {
9
- rabbitmq: FastifyRabbitMQObject & fastifyRabbitMQ.FastifyRabbitMQNestedObject;
10
- }
11
- }
12
- declare namespace fastifyRabbitMQ {
13
- interface FastifyRabbitMQObject extends AmqpConnectionManager {
14
- channel?: ChannelWrapper;
15
- }
16
- interface FastifyRabbitMQNestedObject {
17
- [namespace: string]: FastifyRabbitMQObject;
18
- }
19
- interface FastifyRabbitMQOptions extends AmqpConnectionManagerOptions {
20
- logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error';
21
- namespace?: string;
22
- urLs: ConnectionUrl | ConnectionUrl[] | undefined | null;
23
- }
24
- }
25
- declare const fastifyRabbit: (fastify: FastifyInstance, options: FastifyRabbitMQOptions) => Promise<void>;
26
- export { Channel, ConfirmChannel };
27
- export default fastifyRabbit;
package/dist/index.js DELETED
@@ -1,67 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import amqp from 'amqp-connection-manager';
11
- import fp from 'fastify-plugin';
12
- /**
13
- * decorateFastifyInstance
14
- * @since 0.0.1
15
- * @param fastify
16
- * @param options
17
- * @param connection
18
- */
19
- const decorateFastifyInstance = (fastify, options, connection) => {
20
- const { logLevel = 'silent', namespace = '' } = options;
21
- // override log level
22
- const logger = fastify.log.child({}, { level: logLevel });
23
- if (namespace !== '') {
24
- logger.debug('[fastify-rabbitmq] Namespace: %s', namespace);
25
- }
26
- if (namespace !== '') {
27
- if (typeof fastify.rabbitmq === 'undefined') {
28
- fastify.decorate('rabbitmq', connection);
29
- }
30
- if (fastify.rabbitmq[namespace] != null) {
31
- throw Error('[fastify-rabbitmq] Connection name already registered: ' + namespace);
32
- }
33
- logger.trace('[fastify-rabbitmq] Decorate Fastify with Namespace: %', namespace);
34
- fastify.rabbitmq[namespace] = connection;
35
- }
36
- else {
37
- if (typeof fastify.rabbitmq !== 'undefined') {
38
- throw Error('[fastify-rabbitmq] Already registered');
39
- }
40
- }
41
- if (typeof fastify.rabbitmq === 'undefined') {
42
- logger.trace('[fastify-rabbitmq] Decorate Fastify');
43
- fastify.decorate('rabbitmq', connection);
44
- }
45
- };
46
- const fastifyRabbit = fp((fastify, options) => __awaiter(void 0, void 0, void 0, function* () {
47
- const { logLevel = 'silent', urLs, heartbeatIntervalInSeconds, reconnectTimeInSeconds, findServers, connectionOptions } = options;
48
- // override log level
49
- const logger = fastify.log.child({}, { level: logLevel });
50
- const connection = amqp.connect(urLs, {
51
- heartbeatIntervalInSeconds,
52
- reconnectTimeInSeconds,
53
- findServers,
54
- connectionOptions
55
- });
56
- connection.on('connect', function () {
57
- logger.debug('[fastify-rabbitmq] Connection to RabbitMQ Successful');
58
- });
59
- connection.on('disconnect', function () {
60
- logger.debug('[fastify-rabbitmq] Connection to RabbitMQ Disconnected');
61
- });
62
- /**
63
- * Decorate Fastify
64
- */
65
- decorateFastifyInstance(fastify, options, connection);
66
- }));
67
- export default fastifyRabbit;