fastify-rabbitmq 0.0.1-alpha.2 → 1.0.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,89 @@
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/jwalton/node-amqp-connection-manager) 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
50
 
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
- ### Quick Setup on the Client Side
77
-
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
- })
51
+ Within any "endpoint" function, or if you have access to ```fastify.rabbitmq``` you can then call:
94
52
 
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
- })
53
+ ```js
54
+ fastify.get('/rabbitmq', async (request, reply) => {
55
+ let pub = request.rabbitmq.createPublisher({
56
+ confirm: true,
57
+ maxAttempts: 1
58
+ })
105
59
 
60
+ await pub.send('foo', "bar") // ==> sent to foo queue
106
61
  })
107
62
  ```
108
63
 
109
- Now in your routes or anywhere the fastify.rabbitmq can be accessed:
64
+ Sending the string ```bar``` to the queue called ```foo```.
110
65
 
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
- ```
66
+ ### Quick Setup on the Client Side
121
67
 
122
68
  ## Full Documentation
123
69
 
124
70
  ### Options
125
71
 
126
72
  ```typescript
127
- export interface FastifyRabbitMQOptions extends AmqpConnectionManagerOptions {
128
- logLevel?: 'trace' | 'debug' | 'info' | 'warn' | 'error'
73
+ export interface FastifyRabbitMQOptions {
74
+ /** Connection String or object pointing to the RabbitMQ Broker Services */
75
+ connection: string | ConnectionOptions
76
+ /** To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time. */
129
77
  namespace?: string
130
- urLs: ConnectionUrl | ConnectionUrl[] | undefined | null
131
78
  }
132
79
  ```
80
+
133
81
  #### FastifyRabbitMQOptions
134
82
 
135
- ##### `logLevel`
83
+ ##### `connection`
136
84
 
137
- Set the log level for Fastify RabbitMQ plugin. This is usefull for development work. The default value is ```silent```
85
+ Connection String or object pointing to the RabbitMQ Broker Services.
86
+ This can be an object of ```ConnectionOptions``` from the ```rabbitmq-client``` plugin options.
138
87
 
139
88
  ##### `namespace`
140
89
 
@@ -142,36 +91,12 @@ If you need more than one "connection" to a different set and/or array of Rabbit
142
91
  either on network or cloud, each registration of the plugin needs it to be in its own namespace.
143
92
  If not provided, your application will fail to load.
144
93
 
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
94
 
170
95
  ## Acknowledgements
171
96
 
172
- - [node-amqp-connection-manager](https://github.com/jwalton/node-amqp-connection-manager)
97
+ - [rabbitmq-client](https://www.npmjs.com/package/rabbitmq-client)
173
98
  - [fastify](https://fastify.dev/)
174
- - ...and of course my Wife and Baby Girl.
99
+ - ... and my Wife and Baby Girl.
175
100
 
176
101
  ## License
177
102
 
@@ -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,75 @@
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
+ const fastify_plugin_1 = __importDefault(require("fastify-plugin"));
21
+ const rabbitmq_client_1 = require("rabbitmq-client");
22
+ const errors_js_1 = require("./errors.js");
23
+ const validation_js_1 = require("./validation.js");
24
+ __exportStar(require("./types.js"), exports);
25
+ const decorateFastifyInstance = (fastify, options, connection) => {
26
+ const { namespace = '' } = options;
27
+ if (typeof namespace !== 'undefined') {
28
+ fastify.log.debug('[fastify-rabbitmq] Namespace: %s', namespace);
29
+ }
30
+ if (typeof namespace !== 'undefined' && namespace !== '') {
31
+ if (typeof fastify.rabbitmq === 'undefined') {
32
+ fastify.decorate('rabbitmq', Object.create(null));
33
+ }
34
+ if (typeof fastify.rabbitmq[namespace] !== 'undefined') {
35
+ throw new errors_js_1.errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(`Already registered with namespace: ${namespace}`);
36
+ }
37
+ fastify.log.trace('[fastify-rabbitmq] Decorate Fastify with Namespace: %', namespace);
38
+ fastify.rabbitmq[namespace] = connection;
39
+ }
40
+ else {
41
+ if (typeof fastify.rabbitmq !== 'undefined') {
42
+ throw new errors_js_1.errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS('Already registered.');
43
+ }
44
+ }
45
+ if (typeof fastify.rabbitmq === 'undefined') {
46
+ fastify.log.trace('[fastify-rabbitmq] Decorate Fastify');
47
+ fastify.decorate('rabbitmq', connection);
48
+ }
49
+ };
50
+ /**
51
+ * Main Function
52
+ * @since 1.0.0
53
+ * @example
54
+ * This is the basics on how to use this plugin:
55
+ * ```js
56
+ * app.register(fastifyRabbit, {
57
+ * connection: 'amqp://guest:guest@localhost'
58
+ * })
59
+ * ```
60
+ * This will allow you to read from your Fastify "object" and
61
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
62
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
63
+ * this plugin to execute functions it provides.
64
+ *
65
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
66
+ *
67
+ */
68
+ const fastifyRabbit = (0, fastify_plugin_1.default)(async (fastify, opts, done) => {
69
+ await (0, validation_js_1.validateOpts)(opts);
70
+ const { connection } = opts;
71
+ const c = new rabbitmq_client_1.Connection(connection);
72
+ decorateFastifyInstance(fastify, opts, c);
73
+ done();
74
+ });
75
+ 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,22 @@
1
+ import { FastifyRabbitMQOptions } from './decorate.js';
2
+ export * from './types.js';
3
+ /**
4
+ * Main Function
5
+ * @since 1.0.0
6
+ * @example
7
+ * This is the basics on how to use this plugin:
8
+ * ```js
9
+ * app.register(fastifyRabbit, {
10
+ * connection: 'amqp://guest:guest@localhost'
11
+ * })
12
+ * ```
13
+ * This will allow you to read from your Fastify "object" and
14
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
15
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
16
+ * this plugin to execute functions it provides.
17
+ *
18
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
19
+ *
20
+ */
21
+ declare const fastifyRabbit: import("fastify").FastifyPluginCallback<FastifyRabbitMQOptions, import("fastify").RawServerDefault, import("fastify").FastifyTypeProviderDefault, import("fastify").FastifyBaseLogger>;
22
+ export default fastifyRabbit;
@@ -0,0 +1,57 @@
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
+ //# 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,EAAE,UAAU,IAAI,kBAAkB,EAAE,MAAM,iBAAiB,CAAA;AAElE,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"}
@@ -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,22 @@
1
+ import { FastifyRabbitMQOptions } from './decorate.js';
2
+ export * from './types.js';
3
+ /**
4
+ * Main Function
5
+ * @since 1.0.0
6
+ * @example
7
+ * This is the basics on how to use this plugin:
8
+ * ```js
9
+ * app.register(fastifyRabbit, {
10
+ * connection: 'amqp://guest:guest@localhost'
11
+ * })
12
+ * ```
13
+ * This will allow you to read from your Fastify "object" and
14
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
15
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
16
+ * this plugin to execute functions it provides.
17
+ *
18
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
19
+ *
20
+ */
21
+ declare const fastifyRabbit: import("fastify").FastifyPluginCallback<FastifyRabbitMQOptions, import("fastify").RawServerDefault, import("fastify").FastifyTypeProviderDefault, import("fastify").FastifyBaseLogger>;
22
+ export default fastifyRabbit;
@@ -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,44 @@
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.0.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
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/types/index.d.ts",
11
+ "import": "./dist/esm/index.js",
12
+ "require": "./dist/cjs/index.js",
13
+ "default": "./dist/cjs/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist/**/*"
18
+ ],
8
19
  "scripts": {
9
- "build": "tsc",
20
+ "clean": "rm -rf dist coverage",
21
+ "build": "tsc && tsc -p tsconfig.cjs.json && tsc -p tsconfig.types.json && ./bin/build-types.sh",
10
22
  "build:watch": "tsc -w",
11
- "lint": "ts-standard",
12
- "lint:fix": "ts-standard --fix",
23
+ "lint": "ts-standard --parser @typescript-eslint/parser | snazzy",
24
+ "lint:fix": "ts-standard --fix --parser @typescript-eslint/parser | snazzy",
25
+ "pack": "npm run clean && npm run test:ci && npm run build && npm pack",
26
+ "prepublishOnly": "npm run clean && npm run build",
13
27
  "test": "jest",
14
- "update": "npx npm-check-updates -u && npm install"
28
+ "test:ci": "jest --ci",
29
+ "test:coverage": "jest --coverage",
30
+ "typedoc": "typedoc",
31
+ "typedoc:watch": "typedoc -watch",
32
+ "semantic-release": "semantic-release",
33
+ "semantic-release:dryRun": "semantic-release --dry-run",
34
+ "update": "npx npm-check-updates -u && npm install && npm run test"
15
35
  },
16
36
  "repository": {
17
37
  "type": "git",
18
- "url": "git+https://github.com/Bugs5382/fastify-rabbitmq.git"
38
+ "url": "https://github.com/Bugs5382/fastify-rabbitmq"
19
39
  },
20
40
  "keywords": [
21
- "amqp-connection-manager",
22
- "amqplib",
41
+ "rabbitmq-client",
23
42
  "typescript",
24
43
  "rabbitmq",
25
44
  "fastify",
@@ -32,22 +51,35 @@
32
51
  },
33
52
  "homepage": "https://github.com/Bugs5382/fastify-rabbitmq#readme",
34
53
  "dependencies": {
35
- "amqp-connection-manager": "^4.1.14",
36
- "fastify-plugin": "^4.5.1"
54
+ "@fastify/error": "^3.4.1",
55
+ "@types/amqplib": "^0.10.4",
56
+ "fastify-plugin": "^4.5.1",
57
+ "promise-tools": "^2.1.0",
58
+ "rabbitmq-client": "^4.4.0",
59
+ "randomstring": "^1.3.0"
37
60
  },
38
61
  "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",
62
+ "@semantic-release/changelog": "^6.0.3",
63
+ "@semantic-release/commit-analyzer": "^11.1.0",
64
+ "@semantic-release/git": "^10.0.1",
65
+ "@semantic-release/release-notes-generator": "^12.1.0",
66
+ "@types/jest": "^29.5.8",
67
+ "@types/node": "^20.9.0",
68
+ "@types/randomstring": "^1.1.11",
69
+ "@typescript-eslint/parser": "^6.11.0",
70
+ "fastify": "^4.24.3",
71
+ "jest": "^29.7.0",
72
+ "jest-ts-webcompat-resolver": "^1.0.0",
73
+ "npm-check-updates": "^16.14.6",
45
74
  "pre-commit": "^1.2.2",
75
+ "semantic-release": "^22.0.7",
76
+ "snazzy": "^9.0.0",
46
77
  "ts-jest": "^29.1.1",
47
78
  "ts-node": "^10.9.1",
48
79
  "ts-standard": "^12.0.2",
49
- "tsd": "^0.28.1",
50
- "typescript": "^5.1.6"
80
+ "tsd": "^0.29.0",
81
+ "typedoc": "^0.25.3",
82
+ "typescript": "^5.2.2"
51
83
  },
52
84
  "pre-commit": []
53
85
  }
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;