fastify-rabbitmq 3.3.0 → 3.4.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/CHANGELOG.md ADDED
@@ -0,0 +1,71 @@
1
+ # Fastify RabbitMQ
2
+
3
+ ## v3.4.0 - 2026-06-09
4
+
5
+ ### What Changed 👀
6
+
7
+ #### 🚀 Features
8
+
9
+ - feat: re-export the rabbitmq-client types from fastify-rabbitmq @Bugs5382 (#135)
10
+ - build: migrate to tsdown and the shared eslint-config @Bugs5382 (#119)
11
+
12
+ #### 🐛 Bug Fixes
13
+
14
+ - fix: validate connection shape and reject invalid registration options @Bugs5382 (#125)
15
+
16
+ #### 📄 Documentation
17
+
18
+ - docs: point consumers at the re-exported client types @Bugs5382 (#137)
19
+ - docs: show how to encapsulate messaging in a Fastify plugin @Bugs5382 (#131)
20
+ - docs: rewrite README to standard, add AGENTS.md, fix typedoc parent-export @Bugs5382 (#124)
21
+
22
+ #### 🧩 Dependency Updates
23
+
24
+ - build(deps): bump the production-dependencies group across 1 directory with 3 updates @[dependabot[bot]](https://github.com/apps/dependabot) (#121)
25
+ - build: migrate to tsdown and the shared eslint-config @Bugs5382 (#119)
26
+
27
+ ### Extra
28
+
29
+ **Full Changelog**: https://github.com/Bugs5382/fastify-rabbitmq/compare/v3.3.0...v3.4.0
30
+
31
+ ## v3.3.0 - 2025-05-31
32
+
33
+ #### What Changed 👀
34
+
35
+ #### 🚀 Features
36
+
37
+ - feat: remove old build method @Bugs5382 (#108)
38
+
39
+ #### 🧩 Dependency Updates
40
+
41
+ - feat: remove old build method @Bugs5382 (#108)
42
+
43
+ ### Extra
44
+
45
+ **Full Changelog**: https://github.com/Bugs5382/fastify-rabbitmq/compare/v3.2.0...v3.3.0
46
+
47
+ ## v3.2.0 - 2025-03-25
48
+
49
+ #### What Changed 👀
50
+
51
+ #### 🧩 Dependency Updates
52
+
53
+ - feat: updated dependencies @Bugs5382 (#106)
54
+
55
+ ### Extra
56
+
57
+ **Full Changelog**: https://github.com/Bugs5382/fastify-rabbitmq/compare/v3.1.0...v3.2.0
58
+
59
+ ## v3.1.0 - 2024-11-17
60
+
61
+ #### What Changed 👀
62
+
63
+ - ci: update workflows @Bugs5382 (#103)
64
+
65
+ #### 🧩 Dependency Updates
66
+
67
+ - feat: updated packages @Bugs5382 (#105)
68
+
69
+ ### Extra
70
+
71
+ **Full Changelog**: https://github.com/Bugs5382/fastify-rabbitmq/compare/v3.0.0...v3.1.0
package/README.md CHANGED
@@ -1,104 +1,291 @@
1
- # Fastify RabbitMQ
1
+ # 🐰 Fastify RabbitMQ
2
2
 
3
- A Fastify RabbitMQ Plugin Developed in Pure TypeScript.
4
- It uses the [node-rabbitmq-client](https://github.com/cody-greene/node-rabbitmq-client/) plugin as a wrapper.
3
+ A Fastify RabbitMQ plugin developed in pure TypeScript.
4
+ It wraps the [`rabbitmq-client`](https://www.npmjs.com/package/rabbitmq-client) package so a Fastify
5
+ app can publish, consume, and RPC over RabbitMQ (AMQP 0-9-1).
5
6
 
6
- The build exports this to valid ESM and CJS for ease of cross-compatibility.
7
+ The build exports valid ESM and CJS for cross-compatibility.
7
8
 
8
- If you are using this NPM package, please consider giving it a :star: star.
9
- This will increase its visibility and solicit more contribution from the outside.
9
+ If you use this package, please consider giving it a ⭐ — it raises visibility and brings in more
10
+ contribution from the outside.
11
+
12
+ > This documentation covers **how to use the plugin**. The decorator `app.rabbitmq` is a live
13
+ > `rabbitmq-client` `Connection`, so its full API is available — for publisher/consumer/RPC option
14
+ > details, see [External Libraries](#-external-libraries).
15
+
16
+ > 🟢 **Requires Node.js ≥ 20.15.**
10
17
 
11
18
  ## Table of Contents
12
19
 
13
- 1. [Install](#install)
14
- 2. [Basic Usage](#basic-usage)
15
- 3. [Full Documentation](#full-documentation)
16
- 1. [Options](#options)
17
- 4. [Acknowledgements](#acknowledgements)
18
- 5. [License](#license)
20
+ 1. [Install](#-install)
21
+ 2. [Basic Usage](#-basic-usage)
22
+ 3. [Recipes](#-recipes)
23
+ 1. [Publish a message](#1-publish-a-message)
24
+ 2. [Consume a queue](#2-consume-a-queue)
25
+ 3. [RPC (request/response)](#3-rpc-requestresponse)
26
+ 4. [Declare exchanges, queues, and bindings](#4-declare-exchanges-queues-and-bindings)
27
+ 5. [Multiple connections with namespaces](#5-multiple-connections-with-namespaces)
28
+ 6. [Encapsulate messaging in your own plugin](#6-encapsulate-messaging-in-your-own-plugin)
29
+ 4. [API Reference](#-api-reference-fastifyrabbitmq)
30
+ 5. [Plugin Options](#-plugin-options)
31
+ 6. [External Libraries](#-external-libraries)
32
+ 7. [Acknowledgements](#-acknowledgements)
33
+ 8. [License](#-license)
19
34
 
20
- ## Install
35
+ ## 📦 Install
21
36
 
22
- ```
37
+ ```shell
23
38
  npm install fastify-rabbitmq
24
39
  ```
25
40
 
26
- ## Basic Usage
41
+ Requires Node.js ≥ 20.15.
42
+
43
+ ## 🚀 Basic Usage
44
+
45
+ Register the plugin (before any routes that use it):
46
+
47
+ ```ts
48
+ import fastify from "fastify";
49
+ import fastifyRabbitMQ from "fastify-rabbitmq";
50
+
51
+ const app = fastify();
52
+
53
+ await app.register(fastifyRabbitMQ, {
54
+ connection: "amqp://guest:guest@localhost",
55
+ });
56
+ ```
57
+
58
+ Registering decorates the Fastify instance with `app.rabbitmq` — a live `rabbitmq-client`
59
+ `Connection`. Use it to create publishers, consumers, and RPC clients, or to declare topology.
60
+
61
+ ## 🧩 Recipes
62
+
63
+ ### 1. Publish a message
64
+
65
+ ```ts
66
+ const publisher = app.rabbitmq.createPublisher({
67
+ confirm: true,
68
+ maxAttempts: 1,
69
+ });
70
+
71
+ await publisher.send("foo", "bar"); // routing key "foo", body "bar"
72
+ ```
73
+
74
+ In a route, reach the instance via `request.server`:
75
+
76
+ ```ts
77
+ app.get("/publish", async (request, reply) => {
78
+ const publisher = request.server.rabbitmq.createPublisher({ confirm: true });
79
+ await publisher.send("foo", "bar");
80
+ return { sent: true };
81
+ });
82
+ ```
83
+
84
+ ### 2. Consume a queue
85
+
86
+ ```ts
87
+ const consumer = app.rabbitmq.createConsumer(
88
+ {
89
+ queue: "foo",
90
+ queueOptions: { durable: true },
91
+ },
92
+ async (msg) => {
93
+ app.log.info({ body: msg.body }, "received");
94
+ // ...handle the message...
95
+ },
96
+ );
97
+ ```
98
+
99
+ ### 3. RPC (request/response)
100
+
101
+ ```ts
102
+ const rpc = app.rabbitmq.createRPCClient({ confirm: true });
103
+ const response = await rpc.send("my-rpc-queue", "ping");
104
+ app.log.info({ response: response.body }, "rpc reply");
105
+ ```
106
+
107
+ ### 4. Declare exchanges, queues, and bindings
27
108
 
28
- Register this as a plugin.
29
- Make sure it is loaded before any **_routes_** are loaded.
109
+ ```ts
110
+ await app.rabbitmq.queueDeclare({ queue: "foo", durable: true });
111
+ await app.rabbitmq.exchangeDeclare({ exchange: "my-exchange", type: "topic" });
112
+ await app.rabbitmq.queueBind({
113
+ queue: "foo",
114
+ exchange: "my-exchange",
115
+ routingKey: "foo.#",
116
+ });
117
+ ```
118
+
119
+ ### 5. Multiple connections with namespaces
120
+
121
+ To talk to more than one broker (or keep separate connections), register the plugin once per
122
+ `namespace`; each is reachable at `app.rabbitmq.<namespace>`:
123
+
124
+ ```ts
125
+ await app.register(fastifyRabbitMQ, {
126
+ connection: "amqp://guest:guest@broker-a",
127
+ namespace: "a",
128
+ });
129
+ await app.register(fastifyRabbitMQ, {
130
+ connection: "amqp://guest:guest@broker-b",
131
+ namespace: "b",
132
+ });
133
+
134
+ const pubA = app.rabbitmq.a.createPublisher();
135
+ const pubB = app.rabbitmq.b.createPublisher();
136
+ ```
137
+
138
+ Registering the same namespace twice throws `FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS`.
139
+
140
+ ### 6. Encapsulate messaging in your own plugin
141
+
142
+ This is the pattern the plugin is built for, and the reason it is a plugin at all.
143
+ Fastify's encapsulation lets you keep every messaging concern — the connection, the
144
+ topology, the publishers, the consumers, and their shutdown — in **one plugin**, and
145
+ expose just a small, intent-named surface (a decorator like `app.events`) to the rest
146
+ of the app. Your routes publish business events; they never see exchanges, routing
147
+ keys, or the AMQP client.
148
+
149
+ Wrap it with [`fastify-plugin`](https://github.com/fastify/fastify-plugin) so the
150
+ decorator is visible to sibling plugins and routes (without `fp`, the decorator would
151
+ be trapped inside this plugin's encapsulation context):
152
+
153
+ ```ts
154
+ // plugins/messaging.ts
155
+ import fp from "fastify-plugin";
156
+ import fastifyRabbitMQ, { type Publisher } from "fastify-rabbitmq";
30
157
 
31
- ### Quick Setup on the Server Side
158
+ declare module "fastify" {
159
+ interface FastifyInstance {
160
+ events: Publisher;
161
+ }
162
+ }
163
+
164
+ export default fp(
165
+ async (app) => {
166
+ // 1. Open the connection.
167
+ await app.register(fastifyRabbitMQ, {
168
+ connection: process.env.RABBITMQ_URL ?? "amqp://guest:guest@localhost",
169
+ });
32
170
 
33
- ```typescript
34
- export default fp<FastifyRabbitMQOptions>((fastify, options, done) => {
35
- void fastify.register(fastifyRabbit, {
36
- connection: `amqp://guest:guest@localhost`,
37
- });
171
+ // 2. Declare the topology and a publisher once, at startup. The publisher
172
+ // re-declares these on every reconnect, so the exchange always exists
173
+ // before the first send.
174
+ const publisher = app.rabbitmq.createPublisher({
175
+ confirm: true,
176
+ maxAttempts: 2,
177
+ exchanges: [{ exchange: "events", type: "topic" }],
178
+ });
38
179
 
39
- void fastify.ready().then(async () => {
40
- const consumer = fastify.rabbitmq.createConsumer(
180
+ // 3. Expose one intent-named sender. Routes call app.events.send(...) and
181
+ // stay ignorant of AMQP.
182
+ app.decorate("events", publisher);
183
+
184
+ // 4. Run consumers as part of the app lifecycle. The consumer manages its
185
+ // own channel and re-subscribes across reconnects.
186
+ const consumer = app.rabbitmq.createConsumer(
41
187
  {
42
- queue: "foo",
188
+ queue: "user-events",
43
189
  queueOptions: { durable: true },
190
+ queueBindings: [{ exchange: "events", routingKey: "user.#" }],
44
191
  },
45
- async (msg: any) => {
46
- console.log(msg); // ==> bar
192
+ async (msg) => {
193
+ app.log.info({ body: msg.body }, "user event");
194
+ // ...handle the message; throw to nack/retry...
47
195
  },
48
196
  );
49
- });
50
- });
197
+
198
+ // 5. Tear everything down with the app, so a restart or test closes
199
+ // cleanly instead of leaking connections.
200
+ app.addHook("onClose", async () => {
201
+ await consumer.close();
202
+ await publisher.close();
203
+ });
204
+ },
205
+ { name: "messaging" },
206
+ );
51
207
  ```
52
208
 
53
- ### Quick Setup on the Client Side
209
+ Register it once, then publish from anywhere:
54
210
 
55
- Within any "endpoint" function, or if you have access to `fastify.rabbitmq` you can then call:
211
+ ```ts
212
+ import messaging from "./plugins/messaging";
56
213
 
57
- ```js
58
- fastify.get("/rabbitmq", async (request, reply) => {
59
- let pub = request.rabbitmq.createPublisher({
60
- confirm: true,
61
- maxAttempts: 1,
62
- });
214
+ await app.register(messaging);
63
215
 
64
- await pub.send("foo", "bar"); // ==> sent to foo queue
216
+ app.post("/signup", async (request, reply) => {
217
+ await app.events.send(
218
+ { exchange: "events", routingKey: "user.created" },
219
+ request.body,
220
+ );
221
+ return { accepted: true };
65
222
  });
66
223
  ```
67
224
 
68
- Sending the string `bar` to the queue called `foo`.
225
+ Why this shape works well:
69
226
 
70
- ## Full Documentation
227
+ - **One place owns messaging.** Connection, topology, publishers, consumers, and
228
+ shutdown live together; the rest of the app depends only on `app.events`.
229
+ - **Startup declares, routes send.** Topology is declared once at boot, so the first
230
+ request never races a missing exchange.
231
+ - **Lifecycle is handled.** The `onClose` hook closes the consumer and publisher with
232
+ the app — important for graceful shutdown and for tests that start and stop Fastify
233
+ repeatedly.
234
+ - **Swappable.** Because routes only know `app.events`, you can change brokers, add a
235
+ [namespace](#5-multiple-connections-with-namespaces), or stub the decorator in a test
236
+ without touching route code.
71
237
 
72
- ### Options
238
+ > The types you need — `Publisher`, `Consumer`, `RPCClient`, `Connection`, `ConnectionOptions`,
239
+ > `Envelope`, the message types, and the AMQP error classes — are re-exported from
240
+ > `fastify-rabbitmq`. Import them from here, not from `rabbitmq-client`.
73
241
 
74
- ```typescript
75
- export interface FastifyRabbitMQOptions {
76
- /** Connection String or object pointing to the RabbitMQ Broker Services */
77
- connection: string | ConnectionOptions;
78
- /** To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time. */
79
- namespace?: string;
80
- }
81
- ```
242
+ ## 📖 API Reference (`fastify.rabbitmq`)
243
+
244
+ `app.rabbitmq` is a `rabbitmq-client` `Connection` (and, with namespaces, an index of them). The
245
+ methods you will use most:
246
+
247
+ | Method | Description |
248
+ |---|---|
249
+ | `createPublisher(options?)` | Create a `Publisher` (`.send(routingKey, body)`). |
250
+ | `createConsumer(options, handler)` | Create a `Consumer` bound to a queue; `handler(msg)` runs per message. |
251
+ | `createRPCClient(options?)` | Create an RPC client (`.send(queue, body)` returns the reply). |
252
+ | `exchangeDeclare(params)` | Declare an exchange. |
253
+ | `queueDeclare(params)` | Declare a queue. |
254
+ | `queueBind(params)` | Bind a queue to an exchange. |
255
+ | `acquire()` | Acquire a raw channel. |
256
+ | `ready()` | Resolve once the connection is established. |
257
+ | `close()` | Close the connection. |
258
+
259
+ The full option shapes for each come from `rabbitmq-client` — see [External Libraries](#-external-libraries).
260
+
261
+ ## ⚙️ Plugin Options
262
+
263
+ Pass these to `app.register(fastifyRabbitMQ, options)`:
264
+
265
+ ### `connection`
266
+
267
+ A connection string (e.g. `"amqp://guest:guest@localhost"`) or a `ConnectionOptions` object from
268
+ `rabbitmq-client` pointing at the broker. **Required.**
82
269
 
83
- #### FastifyRabbitMQOptions
270
+ ### `namespace`
84
271
 
85
- ##### `connection`
272
+ `string` — register the plugin more than once by giving each instance a unique namespace; the
273
+ connection is then exposed at `app.rabbitmq.<namespace>`. Re-using a namespace fails to load.
86
274
 
87
- Connection String or object pointing to the RabbitMQ Broker Services.
88
- This can be an object of `ConnectionOptions` from the `node-rabbitmq-client` plugin options.
275
+ ## 🔌 External Libraries
89
276
 
90
- ##### `namespace`
277
+ This plugin documents only its own surface. For publisher/consumer/RPC options, connection options
278
+ (`ConnectionOptions`), TLS, and reconnect behavior, see the package it wraps:
91
279
 
92
- If you need more than one "connection" to a different set and/or array of RabbitMQ servers,
93
- either on network or cloud, each registration of the plugin needs it to be in its own namespace.
94
- If the name space is duplicated, it will fail to load.
280
+ - [`rabbitmq-client`](https://www.npmjs.com/package/rabbitmq-client) — the underlying AMQP client
281
+ (repo: [cody-greene/node-rabbitmq-client](https://github.com/cody-greene/node-rabbitmq-client)).
95
282
 
96
- ## Acknowledgements
283
+ ## 🙏 Acknowledgements
97
284
 
98
- - [node-rabbitmq-client](https://www.npmjs.com/package/rabbitmq-client)
99
- - [fastify](https://fastify.dev/)
100
- - ... and my Wife and Baby Girl.
285
+ - [`rabbitmq-client`](https://www.npmjs.com/package/rabbitmq-client)
286
+ - [Fastify](https://fastify.dev/)
287
+ - ...and my Wife and Baby Girl.
101
288
 
102
- ## License
289
+ ## 📄 License
103
290
 
104
291
  Licensed under [MIT](./LICENSE).
@@ -0,0 +1,14 @@
1
+ import { ConnectionOptions } from "rabbitmq-client";
2
+ export interface FastifyRabbitMQOptions {
3
+ /**
4
+ * @since 1.0.0
5
+ * @remarks Connection String or object pointing to the RabbitMQ Broker Services
6
+ */
7
+ connection: ConnectionOptions | string;
8
+ /**
9
+ * @since 1.0.0
10
+ * @remarks To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time.
11
+ */
12
+ namespace?: string;
13
+ }
14
+ //# sourceMappingURL=decorate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorate.d.ts","sourceRoot":"","sources":["../src/decorate.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,WAAW,sBAAsB;IACrC;;;OAGG;IACH,UAAU,EAAE,iBAAiB,GAAG,MAAM,CAAC;IACvC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB"}
@@ -0,0 +1,15 @@
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
+ };
15
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAwBA,eAAO,MAAM,MAAM;IACjB,oEAAoE;;;;IAKpE,6DAA6D;;;;IAK7D,mEAAmE;;;;CAKpE,CAAC"}
package/dist/index.cjs ADDED
@@ -0,0 +1,139 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ let fastify_plugin = require("fastify-plugin");
28
+ fastify_plugin = __toESM(fastify_plugin);
29
+ let rabbitmq_client = require("rabbitmq-client");
30
+ let _fastify_error = require("@fastify/error");
31
+ _fastify_error = __toESM(_fastify_error);
32
+ //#region src/errors.ts
33
+ const errors = {
34
+ /** Error if there is an invalid option used during registration. */
35
+ FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: (0, _fastify_error.default)("FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS", "Invalid options: %s"),
36
+ /** Error if there is an setup error of the plugin itself. */
37
+ FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: (0, _fastify_error.default)("FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS", "Setup error: %s"),
38
+ /** If an invalid usage error was done, this error would pop up. */
39
+ FASTIFY_RABBIT_MQ_ERR_USAGE: (0, _fastify_error.default)("FASTIFY_RABBIT_MQ_ERR_USAGE", "Usage error: %s")
40
+ };
41
+ //#endregion
42
+ //#region src/validation.ts
43
+ /**
44
+ * Validate Options
45
+ *
46
+ * The plugin validates only the *shape* of `connection` -- that it is a
47
+ * non-empty connection string or a `ConnectionOptions` object. Parsing the URL
48
+ * and validating the broker options (hosts, TLS, reconnect, etc.) is delegated
49
+ * to `rabbitmq-client`. The shape guard exists because `new Connection(...)`
50
+ * accepts garbage (a number, an array, `null`, `{}`) without throwing and then
51
+ * silently fails to connect at runtime; rejecting it here surfaces a clear
52
+ * registration-time error instead.
53
+ * @since 1.0.0
54
+ * @param options
55
+ */
56
+ const validateOpts = async (options) => {
57
+ const { connection } = options;
58
+ if (connection === void 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS("connection must be defined.");
59
+ if (typeof connection === "string") {
60
+ if (connection.length === 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS("connection string must not be empty.");
61
+ return;
62
+ }
63
+ if (!(typeof connection === "object" && connection !== null && !Array.isArray(connection))) throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS("connection must be a connection string or a ConnectionOptions object.");
64
+ };
65
+ //#endregion
66
+ //#region src/index.ts
67
+ /**
68
+ * How we talk with Fastify
69
+ * @since 1.0.0
70
+ * @param fastify
71
+ * @param options
72
+ * @param connection
73
+ */
74
+ const decorateFastifyInstance = (fastify, options, connection) => {
75
+ const { namespace = "" } = options;
76
+ if (namespace !== void 0 && namespace !== "") fastify.log.debug("[fastify-rabbitmq] Namespace Attempt: %s", namespace);
77
+ if (namespace !== void 0 && namespace !== "") {
78
+ if (fastify.rabbitmq === void 0) fastify.decorate("rabbitmq", Object.create(null));
79
+ if (fastify.rabbitmq[namespace] !== void 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(`Already registered with namespace: ${namespace}`);
80
+ fastify.log.trace(`[fastify-rabbitmq] Decorate Fastify with Namespace: ${namespace}`);
81
+ fastify.rabbitmq[namespace] = connection;
82
+ } else if (fastify.rabbitmq !== void 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS("Already registered.");
83
+ if (fastify.rabbitmq === void 0) {
84
+ fastify.log.trace("[fastify-rabbitmq] Decorate Fastify");
85
+ fastify.decorate("rabbitmq", connection);
86
+ }
87
+ };
88
+ /**
89
+ * Main Function
90
+ * @since 1.0.0
91
+ * @example
92
+ * This is the basics on how to use this plugin:
93
+ * ```js
94
+ * app.register(fastifyRabbit, {
95
+ * connection: 'amqp://guest:guest@localhost'
96
+ * })
97
+ * ```
98
+ * This will allow you to read from your Fastify "object" and
99
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
100
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
101
+ * this plugin to execute functions it provides.
102
+ *
103
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
104
+ *
105
+ */
106
+ const fastifyRabbit = (0, fastify_plugin.default)(async (fastify, opts) => {
107
+ await validateOpts(opts);
108
+ const { connection } = opts;
109
+ decorateFastifyInstance(fastify, opts, new rabbitmq_client.Connection(connection));
110
+ });
111
+ //#endregion
112
+ Object.defineProperty(exports, "AMQPChannelError", {
113
+ enumerable: true,
114
+ get: function() {
115
+ return rabbitmq_client.AMQPChannelError;
116
+ }
117
+ });
118
+ Object.defineProperty(exports, "AMQPConnectionError", {
119
+ enumerable: true,
120
+ get: function() {
121
+ return rabbitmq_client.AMQPConnectionError;
122
+ }
123
+ });
124
+ Object.defineProperty(exports, "AMQPError", {
125
+ enumerable: true,
126
+ get: function() {
127
+ return rabbitmq_client.AMQPError;
128
+ }
129
+ });
130
+ Object.defineProperty(exports, "ConsumerStatus", {
131
+ enumerable: true,
132
+ get: function() {
133
+ return rabbitmq_client.ConsumerStatus;
134
+ }
135
+ });
136
+ exports.decorateFastifyInstance = decorateFastifyInstance;
137
+ exports.default = fastifyRabbit;
138
+
139
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["RabbitMQConnection"],"sources":["../src/errors.ts","../src/validation.ts","../src/index.ts"],"sourcesContent":["/*\nMIT License\n\nCopyright (c) 2026 Shane Froebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\nimport createError from \"@fastify/error\";\n\nexport const errors = {\n /** Error if there is an invalid option used during registration. */\n FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: createError(\n \"FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS\",\n \"Invalid options: %s\",\n ),\n /** Error if there is an setup error of the plugin itself. */\n FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: createError(\n \"FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS\",\n \"Setup error: %s\",\n ),\n /** If an invalid usage error was done, this error would pop up. */\n FASTIFY_RABBIT_MQ_ERR_USAGE: createError(\n \"FASTIFY_RABBIT_MQ_ERR_USAGE\",\n \"Usage error: %s\",\n ),\n};\n","/*\nMIT License\n\nCopyright (c) 2026 Shane Froebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\nimport { FastifyRabbitMQOptions } from \"./decorate\";\nimport { errors } from \"./errors\";\n\n/**\n * Validate Options\n *\n * The plugin validates only the *shape* of `connection` -- that it is a\n * non-empty connection string or a `ConnectionOptions` object. Parsing the URL\n * and validating the broker options (hosts, TLS, reconnect, etc.) is delegated\n * to `rabbitmq-client`. The shape guard exists because `new Connection(...)`\n * accepts garbage (a number, an array, `null`, `{}`) without throwing and then\n * silently fails to connect at runtime; rejecting it here surfaces a clear\n * registration-time error instead.\n * @since 1.0.0\n * @param options\n */\nexport const validateOpts = async (\n options: FastifyRabbitMQOptions,\n): Promise<void> => {\n const { connection } = options;\n\n // Mandatory\n if (connection === undefined) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(\n \"connection must be defined.\",\n );\n }\n\n if (typeof connection === \"string\") {\n if (connection.length === 0) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(\n \"connection string must not be empty.\",\n );\n }\n return;\n }\n\n const isConnectionOptions =\n typeof connection === \"object\" &&\n connection !== null &&\n !Array.isArray(connection);\n\n if (!isConnectionOptions) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(\n \"connection must be a connection string or a ConnectionOptions object.\",\n );\n }\n};\n","/*\nMIT License\n\nCopyright (c) 2026 Shane Froebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\nimport { FastifyInstance } from \"fastify\";\nimport fp from \"fastify-plugin\";\nimport { Connection as RabbitMQConnection } from \"rabbitmq-client\";\n\nimport { FastifyRabbitMQOptions } from \"./decorate\";\nimport { errors } from \"./errors\";\nimport { validateOpts } from \"./validation\";\nexport { type FastifyRabbitMQOptions } from \"./decorate\";\n\n/**\n * How we talk with Fastify\n * @since 1.0.0\n * @param fastify\n * @param options\n * @param connection\n */\nconst decorateFastifyInstance = (\n fastify: FastifyInstance,\n options: FastifyRabbitMQOptions,\n connection: any,\n): void => {\n const { namespace = \"\" } = options;\n\n if (namespace !== undefined && namespace !== \"\") {\n fastify.log.debug(\"[fastify-rabbitmq] Namespace Attempt: %s\", namespace);\n }\n if (namespace !== undefined && namespace !== \"\") {\n if (fastify.rabbitmq === undefined) {\n fastify.decorate(\"rabbitmq\", Object.create(null));\n }\n\n if (fastify.rabbitmq[namespace] !== undefined) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(\n `Already registered with namespace: ${namespace}`,\n );\n }\n\n fastify.log.trace(\n `[fastify-rabbitmq] Decorate Fastify with Namespace: ${namespace}`,\n );\n fastify.rabbitmq[namespace] = connection;\n } else {\n if (fastify.rabbitmq !== undefined) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(\n \"Already registered.\",\n );\n }\n }\n\n if (fastify.rabbitmq === undefined) {\n fastify.log.trace(\"[fastify-rabbitmq] Decorate Fastify\");\n fastify.decorate(\"rabbitmq\", connection);\n }\n};\n\n/**\n * Main Function\n * @since 1.0.0\n * @example\n * This is the basics on how to use this plugin:\n * ```js\n * app.register(fastifyRabbit, {\n * connection: 'amqp://guest:guest@localhost'\n * })\n * ```\n * This will allow you to read from your Fastify \"object\" and\n * use this plugin at the \"rabbitmq\" level. From there you can execute and maintain\n * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around\n * this plugin to execute functions it provides.\n *\n * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)\n *\n */\nconst fastifyRabbit = fp<FastifyRabbitMQOptions>(async (fastify, opts) => {\n await validateOpts(opts);\n\n const { connection } = opts;\n\n const c = new RabbitMQConnection(connection);\n\n decorateFastifyInstance(fastify, opts, c);\n});\n\nexport default fastifyRabbit;\n\nexport { decorateFastifyInstance };\n\nexport * from \"./types\";\n\n// Re-export the rabbitmq-client surface so consumers import from this package\n// instead of reaching for the wrapped client. These are the exact types the\n// app.rabbitmq decorator hands back, so they stay correct without owning a\n// parallel definition.\nexport type {\n AsyncMessage,\n Channel,\n Connection,\n ConnectionOptions,\n Consumer,\n ConsumerHandler,\n ConsumerProps,\n Envelope,\n HeaderFields,\n MessageBody,\n Publisher,\n PublisherProps,\n ReturnedMessage,\n RPCClient,\n RPCProps,\n SyncMessage,\n} from \"rabbitmq-client\";\nexport {\n AMQPChannelError,\n AMQPConnectionError,\n AMQPError,\n ConsumerStatus,\n} from \"rabbitmq-client\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,SAAS;;CAEpB,qCAAA,GAAA,eAAA,QAAA,CACE,sCACA,qBACF;;CAEA,qCAAA,GAAA,eAAA,QAAA,CACE,sCACA,iBACF;;CAEA,8BAAA,GAAA,eAAA,QAAA,CACE,+BACA,iBACF;AACF;;;;;;;;;;;;;;;;ACFA,MAAa,eAAe,OAC1B,YACkB;CAClB,MAAM,EAAE,eAAe;CAGvB,IAAI,eAAe,KAAA,GACjB,MAAM,IAAI,OAAO,mCACf,6BACF;CAGF,IAAI,OAAO,eAAe,UAAU;EAClC,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,OAAO,mCACf,sCACF;EAEF;CACF;CAOA,IAAI,EAJF,OAAO,eAAe,YACtB,eAAe,QACf,CAAC,MAAM,QAAQ,UAAU,IAGzB,MAAM,IAAI,OAAO,mCACf,uEACF;AAEJ;;;;;;;;;;AC/BA,MAAM,2BACJ,SACA,SACA,eACS;CACT,MAAM,EAAE,YAAY,OAAO;CAE3B,IAAI,cAAc,KAAA,KAAa,cAAc,IAC3C,QAAQ,IAAI,MAAM,4CAA4C,SAAS;CAEzE,IAAI,cAAc,KAAA,KAAa,cAAc,IAAI;EAC/C,IAAI,QAAQ,aAAa,KAAA,GACvB,QAAQ,SAAS,YAAY,OAAO,OAAO,IAAI,CAAC;EAGlD,IAAI,QAAQ,SAAS,eAAe,KAAA,GAClC,MAAM,IAAI,OAAO,mCACf,sCAAsC,WACxC;EAGF,QAAQ,IAAI,MACV,uDAAuD,WACzD;EACA,QAAQ,SAAS,aAAa;CAChC,OACE,IAAI,QAAQ,aAAa,KAAA,GACvB,MAAM,IAAI,OAAO,mCACf,qBACF;CAIJ,IAAI,QAAQ,aAAa,KAAA,GAAW;EAClC,QAAQ,IAAI,MAAM,qCAAqC;EACvD,QAAQ,SAAS,YAAY,UAAU;CACzC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,iBAAA,GAAA,eAAA,QAAA,CAA2C,OAAO,SAAS,SAAS;CACxE,MAAM,aAAa,IAAI;CAEvB,MAAM,EAAE,eAAe;CAIvB,wBAAwB,SAAS,MAAM,IAFzBA,gBAAAA,WAAmB,UAEM,CAAC;AAC1C,CAAC"}
@@ -0,0 +1,36 @@
1
+ import { FastifyInstance } from "fastify";
2
+ import { FastifyRabbitMQOptions } from "./decorate";
3
+ export { type FastifyRabbitMQOptions } from "./decorate";
4
+ /**
5
+ * How we talk with Fastify
6
+ * @since 1.0.0
7
+ * @param fastify
8
+ * @param options
9
+ * @param connection
10
+ */
11
+ declare const decorateFastifyInstance: (fastify: FastifyInstance, options: FastifyRabbitMQOptions, connection: any) => void;
12
+ /**
13
+ * Main Function
14
+ * @since 1.0.0
15
+ * @example
16
+ * This is the basics on how to use this plugin:
17
+ * ```js
18
+ * app.register(fastifyRabbit, {
19
+ * connection: 'amqp://guest:guest@localhost'
20
+ * })
21
+ * ```
22
+ * This will allow you to read from your Fastify "object" and
23
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
24
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
25
+ * this plugin to execute functions it provides.
26
+ *
27
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
28
+ *
29
+ */
30
+ declare const fastifyRabbit: import("fastify").FastifyPluginCallback<FastifyRabbitMQOptions, import("fastify").RawServerDefault, import("fastify").FastifyTypeProviderDefault, import("fastify").FastifyBaseLogger>;
31
+ export default fastifyRabbit;
32
+ export { decorateFastifyInstance };
33
+ export * from "./types";
34
+ export type { AsyncMessage, Channel, Connection, ConnectionOptions, Consumer, ConsumerHandler, ConsumerProps, Envelope, HeaderFields, MessageBody, Publisher, PublisherProps, ReturnedMessage, RPCClient, RPCProps, SyncMessage, } from "rabbitmq-client";
35
+ export { AMQPChannelError, AMQPConnectionError, AMQPError, ConsumerStatus, } from "rabbitmq-client";
36
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAI1C,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAGpD,OAAO,EAAE,KAAK,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAEzD;;;;;;GAMG;AACH,QAAA,MAAM,uBAAuB,GAC3B,SAAS,eAAe,EACxB,SAAS,sBAAsB,EAC/B,YAAY,GAAG,KACd,IAiCF,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,QAAA,MAAM,aAAa,wLAQjB,CAAC;AAEH,eAAe,aAAa,CAAC;AAE7B,OAAO,EAAE,uBAAuB,EAAE,CAAC;AAEnC,cAAc,SAAS,CAAC;AAMxB,YAAY,EACV,YAAY,EACZ,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,QAAQ,EACR,eAAe,EACf,aAAa,EACb,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,SAAS,EACT,cAAc,EACd,eAAe,EACf,SAAS,EACT,QAAQ,EACR,WAAW,GACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,gBAAgB,EAChB,mBAAmB,EACnB,SAAS,EACT,cAAc,GACf,MAAM,iBAAiB,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,86 @@
1
+ import fp from "fastify-plugin";
2
+ import { AMQPChannelError, AMQPConnectionError, AMQPError, Connection, ConsumerStatus } from "rabbitmq-client";
3
+ import createError from "@fastify/error";
4
+ //#region src/errors.ts
5
+ const errors = {
6
+ /** Error if there is an invalid option used during registration. */
7
+ FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: createError("FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS", "Invalid options: %s"),
8
+ /** Error if there is an setup error of the plugin itself. */
9
+ FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: createError("FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS", "Setup error: %s"),
10
+ /** If an invalid usage error was done, this error would pop up. */
11
+ FASTIFY_RABBIT_MQ_ERR_USAGE: createError("FASTIFY_RABBIT_MQ_ERR_USAGE", "Usage error: %s")
12
+ };
13
+ //#endregion
14
+ //#region src/validation.ts
15
+ /**
16
+ * Validate Options
17
+ *
18
+ * The plugin validates only the *shape* of `connection` -- that it is a
19
+ * non-empty connection string or a `ConnectionOptions` object. Parsing the URL
20
+ * and validating the broker options (hosts, TLS, reconnect, etc.) is delegated
21
+ * to `rabbitmq-client`. The shape guard exists because `new Connection(...)`
22
+ * accepts garbage (a number, an array, `null`, `{}`) without throwing and then
23
+ * silently fails to connect at runtime; rejecting it here surfaces a clear
24
+ * registration-time error instead.
25
+ * @since 1.0.0
26
+ * @param options
27
+ */
28
+ const validateOpts = async (options) => {
29
+ const { connection } = options;
30
+ if (connection === void 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS("connection must be defined.");
31
+ if (typeof connection === "string") {
32
+ if (connection.length === 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS("connection string must not be empty.");
33
+ return;
34
+ }
35
+ if (!(typeof connection === "object" && connection !== null && !Array.isArray(connection))) throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS("connection must be a connection string or a ConnectionOptions object.");
36
+ };
37
+ //#endregion
38
+ //#region src/index.ts
39
+ /**
40
+ * How we talk with Fastify
41
+ * @since 1.0.0
42
+ * @param fastify
43
+ * @param options
44
+ * @param connection
45
+ */
46
+ const decorateFastifyInstance = (fastify, options, connection) => {
47
+ const { namespace = "" } = options;
48
+ if (namespace !== void 0 && namespace !== "") fastify.log.debug("[fastify-rabbitmq] Namespace Attempt: %s", namespace);
49
+ if (namespace !== void 0 && namespace !== "") {
50
+ if (fastify.rabbitmq === void 0) fastify.decorate("rabbitmq", Object.create(null));
51
+ if (fastify.rabbitmq[namespace] !== void 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(`Already registered with namespace: ${namespace}`);
52
+ fastify.log.trace(`[fastify-rabbitmq] Decorate Fastify with Namespace: ${namespace}`);
53
+ fastify.rabbitmq[namespace] = connection;
54
+ } else if (fastify.rabbitmq !== void 0) throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS("Already registered.");
55
+ if (fastify.rabbitmq === void 0) {
56
+ fastify.log.trace("[fastify-rabbitmq] Decorate Fastify");
57
+ fastify.decorate("rabbitmq", connection);
58
+ }
59
+ };
60
+ /**
61
+ * Main Function
62
+ * @since 1.0.0
63
+ * @example
64
+ * This is the basics on how to use this plugin:
65
+ * ```js
66
+ * app.register(fastifyRabbit, {
67
+ * connection: 'amqp://guest:guest@localhost'
68
+ * })
69
+ * ```
70
+ * This will allow you to read from your Fastify "object" and
71
+ * use this plugin at the "rabbitmq" level. From there you can execute and maintain
72
+ * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
73
+ * this plugin to execute functions it provides.
74
+ *
75
+ * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
76
+ *
77
+ */
78
+ const fastifyRabbit = fp(async (fastify, opts) => {
79
+ await validateOpts(opts);
80
+ const { connection } = opts;
81
+ decorateFastifyInstance(fastify, opts, new Connection(connection));
82
+ });
83
+ //#endregion
84
+ export { AMQPChannelError, AMQPConnectionError, AMQPError, ConsumerStatus, decorateFastifyInstance, fastifyRabbit as default };
85
+
86
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["RabbitMQConnection"],"sources":["../src/errors.ts","../src/validation.ts","../src/index.ts"],"sourcesContent":["/*\nMIT License\n\nCopyright (c) 2026 Shane Froebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\nimport createError from \"@fastify/error\";\n\nexport const errors = {\n /** Error if there is an invalid option used during registration. */\n FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: createError(\n \"FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS\",\n \"Invalid options: %s\",\n ),\n /** Error if there is an setup error of the plugin itself. */\n FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: createError(\n \"FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS\",\n \"Setup error: %s\",\n ),\n /** If an invalid usage error was done, this error would pop up. */\n FASTIFY_RABBIT_MQ_ERR_USAGE: createError(\n \"FASTIFY_RABBIT_MQ_ERR_USAGE\",\n \"Usage error: %s\",\n ),\n};\n","/*\nMIT License\n\nCopyright (c) 2026 Shane Froebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\nimport { FastifyRabbitMQOptions } from \"./decorate\";\nimport { errors } from \"./errors\";\n\n/**\n * Validate Options\n *\n * The plugin validates only the *shape* of `connection` -- that it is a\n * non-empty connection string or a `ConnectionOptions` object. Parsing the URL\n * and validating the broker options (hosts, TLS, reconnect, etc.) is delegated\n * to `rabbitmq-client`. The shape guard exists because `new Connection(...)`\n * accepts garbage (a number, an array, `null`, `{}`) without throwing and then\n * silently fails to connect at runtime; rejecting it here surfaces a clear\n * registration-time error instead.\n * @since 1.0.0\n * @param options\n */\nexport const validateOpts = async (\n options: FastifyRabbitMQOptions,\n): Promise<void> => {\n const { connection } = options;\n\n // Mandatory\n if (connection === undefined) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(\n \"connection must be defined.\",\n );\n }\n\n if (typeof connection === \"string\") {\n if (connection.length === 0) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(\n \"connection string must not be empty.\",\n );\n }\n return;\n }\n\n const isConnectionOptions =\n typeof connection === \"object\" &&\n connection !== null &&\n !Array.isArray(connection);\n\n if (!isConnectionOptions) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(\n \"connection must be a connection string or a ConnectionOptions object.\",\n );\n }\n};\n","/*\nMIT License\n\nCopyright (c) 2026 Shane Froebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n*/\nimport { FastifyInstance } from \"fastify\";\nimport fp from \"fastify-plugin\";\nimport { Connection as RabbitMQConnection } from \"rabbitmq-client\";\n\nimport { FastifyRabbitMQOptions } from \"./decorate\";\nimport { errors } from \"./errors\";\nimport { validateOpts } from \"./validation\";\nexport { type FastifyRabbitMQOptions } from \"./decorate\";\n\n/**\n * How we talk with Fastify\n * @since 1.0.0\n * @param fastify\n * @param options\n * @param connection\n */\nconst decorateFastifyInstance = (\n fastify: FastifyInstance,\n options: FastifyRabbitMQOptions,\n connection: any,\n): void => {\n const { namespace = \"\" } = options;\n\n if (namespace !== undefined && namespace !== \"\") {\n fastify.log.debug(\"[fastify-rabbitmq] Namespace Attempt: %s\", namespace);\n }\n if (namespace !== undefined && namespace !== \"\") {\n if (fastify.rabbitmq === undefined) {\n fastify.decorate(\"rabbitmq\", Object.create(null));\n }\n\n if (fastify.rabbitmq[namespace] !== undefined) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(\n `Already registered with namespace: ${namespace}`,\n );\n }\n\n fastify.log.trace(\n `[fastify-rabbitmq] Decorate Fastify with Namespace: ${namespace}`,\n );\n fastify.rabbitmq[namespace] = connection;\n } else {\n if (fastify.rabbitmq !== undefined) {\n throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(\n \"Already registered.\",\n );\n }\n }\n\n if (fastify.rabbitmq === undefined) {\n fastify.log.trace(\"[fastify-rabbitmq] Decorate Fastify\");\n fastify.decorate(\"rabbitmq\", connection);\n }\n};\n\n/**\n * Main Function\n * @since 1.0.0\n * @example\n * This is the basics on how to use this plugin:\n * ```js\n * app.register(fastifyRabbit, {\n * connection: 'amqp://guest:guest@localhost'\n * })\n * ```\n * This will allow you to read from your Fastify \"object\" and\n * use this plugin at the \"rabbitmq\" level. From there you can execute and maintain\n * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around\n * this plugin to execute functions it provides.\n *\n * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)\n *\n */\nconst fastifyRabbit = fp<FastifyRabbitMQOptions>(async (fastify, opts) => {\n await validateOpts(opts);\n\n const { connection } = opts;\n\n const c = new RabbitMQConnection(connection);\n\n decorateFastifyInstance(fastify, opts, c);\n});\n\nexport default fastifyRabbit;\n\nexport { decorateFastifyInstance };\n\nexport * from \"./types\";\n\n// Re-export the rabbitmq-client surface so consumers import from this package\n// instead of reaching for the wrapped client. These are the exact types the\n// app.rabbitmq decorator hands back, so they stay correct without owning a\n// parallel definition.\nexport type {\n AsyncMessage,\n Channel,\n Connection,\n ConnectionOptions,\n Consumer,\n ConsumerHandler,\n ConsumerProps,\n Envelope,\n HeaderFields,\n MessageBody,\n Publisher,\n PublisherProps,\n ReturnedMessage,\n RPCClient,\n RPCProps,\n SyncMessage,\n} from \"rabbitmq-client\";\nexport {\n AMQPChannelError,\n AMQPConnectionError,\n AMQPError,\n ConsumerStatus,\n} from \"rabbitmq-client\";\n"],"mappings":";;;;AAwBA,MAAa,SAAS;;CAEpB,oCAAoC,YAClC,sCACA,qBACF;;CAEA,oCAAoC,YAClC,sCACA,iBACF;;CAEA,6BAA6B,YAC3B,+BACA,iBACF;AACF;;;;;;;;;;;;;;;;ACFA,MAAa,eAAe,OAC1B,YACkB;CAClB,MAAM,EAAE,eAAe;CAGvB,IAAI,eAAe,KAAA,GACjB,MAAM,IAAI,OAAO,mCACf,6BACF;CAGF,IAAI,OAAO,eAAe,UAAU;EAClC,IAAI,WAAW,WAAW,GACxB,MAAM,IAAI,OAAO,mCACf,sCACF;EAEF;CACF;CAOA,IAAI,EAJF,OAAO,eAAe,YACtB,eAAe,QACf,CAAC,MAAM,QAAQ,UAAU,IAGzB,MAAM,IAAI,OAAO,mCACf,uEACF;AAEJ;;;;;;;;;;AC/BA,MAAM,2BACJ,SACA,SACA,eACS;CACT,MAAM,EAAE,YAAY,OAAO;CAE3B,IAAI,cAAc,KAAA,KAAa,cAAc,IAC3C,QAAQ,IAAI,MAAM,4CAA4C,SAAS;CAEzE,IAAI,cAAc,KAAA,KAAa,cAAc,IAAI;EAC/C,IAAI,QAAQ,aAAa,KAAA,GACvB,QAAQ,SAAS,YAAY,OAAO,OAAO,IAAI,CAAC;EAGlD,IAAI,QAAQ,SAAS,eAAe,KAAA,GAClC,MAAM,IAAI,OAAO,mCACf,sCAAsC,WACxC;EAGF,QAAQ,IAAI,MACV,uDAAuD,WACzD;EACA,QAAQ,SAAS,aAAa;CAChC,OACE,IAAI,QAAQ,aAAa,KAAA,GACvB,MAAM,IAAI,OAAO,mCACf,qBACF;CAIJ,IAAI,QAAQ,aAAa,KAAA,GAAW;EAClC,QAAQ,IAAI,MAAM,qCAAqC;EACvD,QAAQ,SAAS,YAAY,UAAU;CACzC;AACF;;;;;;;;;;;;;;;;;;;AAoBA,MAAM,gBAAgB,GAA2B,OAAO,SAAS,SAAS;CACxE,MAAM,aAAa,IAAI;CAEvB,MAAM,EAAE,eAAe;CAIvB,wBAAwB,SAAS,MAAM,IAFzBA,WAAmB,UAEM,CAAC;AAC1C,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { Connection as RabbitMQConnection } from "rabbitmq-client";
2
+ declare module "fastify" {
3
+ interface FastifyInstance {
4
+ /** Main Decorator for Fastify **/
5
+ rabbitmq: fastifyRabbitMQ.FastifyRabbitMQNO & RabbitMQConnection;
6
+ }
7
+ }
8
+ export declare namespace fastifyRabbitMQ {
9
+ interface FastifyRabbitMQNO {
10
+ [namespace: string]: RabbitMQConnection;
11
+ }
12
+ }
13
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,UAAU,IAAI,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAEnE,OAAO,QAAQ,SAAS,CAAC;IACvB,UAAiB,eAAe;QAC9B,kCAAkC;QAClC,QAAQ,EAAE,eAAe,CAAC,iBAAiB,GAAG,kBAAkB,CAAC;KAClE;CACF;AAGD,MAAM,CAAC,OAAO,WAAW,eAAe,CAAC;IACvC,UAAiB,iBAAiB;QAChC,CAAC,SAAS,EAAE,MAAM,GAAG,kBAAkB,CAAC;KACzC;CACF"}
@@ -0,0 +1,16 @@
1
+ import { FastifyRabbitMQOptions } from "./decorate";
2
+ /**
3
+ * Validate Options
4
+ *
5
+ * The plugin validates only the *shape* of `connection` -- that it is a
6
+ * non-empty connection string or a `ConnectionOptions` object. Parsing the URL
7
+ * and validating the broker options (hosts, TLS, reconnect, etc.) is delegated
8
+ * to `rabbitmq-client`. The shape guard exists because `new Connection(...)`
9
+ * accepts garbage (a number, an array, `null`, `{}`) without throwing and then
10
+ * silently fails to connect at runtime; rejecting it here surfaces a clear
11
+ * registration-time error instead.
12
+ * @since 1.0.0
13
+ * @param options
14
+ */
15
+ export declare const validateOpts: (options: FastifyRabbitMQOptions) => Promise<void>;
16
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAGpD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,GACvB,SAAS,sBAAsB,KAC9B,OAAO,CAAC,IAAI,CA6Bd,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fastify-rabbitmq",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "A Fastify RabbitMQ Plugin Developed in Pure TypeScript.",
5
5
  "keywords": [
6
6
  "rabbitmq-client",
@@ -21,32 +21,34 @@
21
21
  "author": "Shane Froebel",
22
22
  "exports": {
23
23
  ".": {
24
- "types": "./lib/types/index.d.ts",
25
- "import": "./lib/esm/index.mjs",
26
- "require": "./lib/cjs/index.js",
27
- "default": "./lib/cjs/index.js"
24
+ "import": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.mjs"
27
+ },
28
+ "require": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.cjs"
31
+ }
28
32
  }
29
33
  },
30
- "main": "./lib/cjs/index.js",
31
- "module": "./lib/esm/index.mjs",
32
- "types": "./lib/types/index.d.ts",
34
+ "main": "./dist/index.cjs",
35
+ "module": "./dist/index.mjs",
36
+ "types": "./dist/index.d.ts",
33
37
  "files": [
34
- "lib/",
38
+ "dist",
35
39
  "README.md",
36
- "LICENSE"
40
+ "LICENSE",
41
+ "CHANGELOG.md"
37
42
  ],
38
43
  "scripts": {
39
- "build": "tsup",
40
- "build:dev": "NODE_ENV=development tsup",
41
- "clean": "rm -rf coverage docs lib temp",
42
- "format:check": "prettier --check '**/*.{md,ts,json,mts}'",
43
- "format:write": "prettier --write '**/*.{md,ts,json,mts}'",
44
- "lint": "npm run lint:npm && eslint | snazzy && npm run format:check",
45
- "lint:fix": "npm run lint:npm && eslint --fix | snazzy && npm run format:write",
44
+ "build": "tsdown && tsc --emitDeclarationOnly",
45
+ "clean": "rm -rf coverage docs dist temp",
46
+ "lint": "eslint .",
47
+ "lint:fix": "eslint . --fix",
46
48
  "lint:npm": "npmPkgJsonLint .",
47
49
  "lint:package": "npx sort-package-json",
48
50
  "pack": "npm pack",
49
- "prepublishOnly": "npm run clean && npm run build && npm run pack",
51
+ "prepublishOnly": "npm run clean && npm run build",
50
52
  "test": "vitest run",
51
53
  "test:coverage": "vitest --coverage",
52
54
  "test:verbose": "vitest run --reporter verbose",
@@ -54,16 +56,17 @@
54
56
  "typedoc": "typedoc",
55
57
  "typedoc:watch": "typedoc -watch",
56
58
  "update": "npx npm-check-updates -u --enginesNode && npm run update:post-update",
57
- "update:post-update": "npm install && npm run test"
59
+ "update:post-update": "npm install && npm run test",
60
+ "build:watch": "tsdown --watch",
61
+ "typecheck": "tsc --noEmit"
58
62
  },
59
63
  "dependencies": {
60
- "@fastify/error": "^4.1.0",
61
- "fastify-plugin": "^5.0.1",
62
- "rabbitmq-client": "^5.0.4"
64
+ "@fastify/error": "^4.2.0",
65
+ "fastify-plugin": "^5.1.0",
66
+ "rabbitmq-client": "^5.0.8"
63
67
  },
64
68
  "devDependencies": {
65
69
  "@eslint/js": "^9.28.0",
66
- "@ianvs/prettier-plugin-sort-imports": "^4.4.2",
67
70
  "@shipgirl/typedoc-plugin-versions": "^0.3.1",
68
71
  "@types/node": "^22.15.29",
69
72
  "@typescript-eslint/eslint-plugin": "^8.33.0",
@@ -71,27 +74,25 @@
71
74
  "@vitest/coverage-v8": "^3.1.4",
72
75
  "@vitest/ui": "^3.1.4",
73
76
  "eslint": "^9.28.0",
74
- "eslint-config-prettier": "^10.1.5",
75
- "eslint-plugin-prettier": "^5.4.1",
76
77
  "eslint-plugin-sort-class-members": "^1.21.0",
77
78
  "fastify": "^5.3.3",
78
79
  "npm-check-updates": "^18.0.1",
79
80
  "npm-package-json-lint": "^8.0.0",
80
81
  "npm-package-json-lint-config-default": "^7.0.1",
81
82
  "pre-commit": "^1.2.2",
82
- "prettier-plugin-organize-imports": "^4.1.0",
83
83
  "snazzy": "^9.0.0",
84
84
  "sort-package-json": "^3.2.1",
85
85
  "ts-node": "^10.9.2",
86
86
  "tsd": "^0.32.0",
87
- "tsup": "^8.5.0",
88
87
  "typedoc": "^0.28.5",
89
88
  "typescript": "^5.8.3",
90
89
  "typescript-eslint": "^8.33.0",
91
- "vitest": "^3.1.4"
90
+ "vitest": "^3.1.4",
91
+ "@the-rabbit-hole/eslint-config": "^0.4.0",
92
+ "tsdown": "^0.22.2"
92
93
  },
93
94
  "engines": {
94
- "node": ">=20.11.0"
95
+ "node": ">=20.15.0"
95
96
  },
96
97
  "precommit": [
97
98
  "test",
package/lib/cjs/index.js DELETED
@@ -1,115 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- decorateFastifyInstance: () => decorateFastifyInstance,
34
- default: () => index_default
35
- });
36
- module.exports = __toCommonJS(index_exports);
37
- var import_fastify_plugin = __toESM(require("fastify-plugin"));
38
- var import_rabbitmq_client = require("rabbitmq-client");
39
-
40
- // src/errors.ts
41
- var import_error = __toESM(require("@fastify/error"));
42
- var errors = {
43
- /** Error if there is an invalid option used during registration. */
44
- FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: (0, import_error.default)(
45
- "FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS",
46
- "Invalid options: %s"
47
- ),
48
- /** Error if there is an setup error of the plugin itself. */
49
- FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: (0, import_error.default)(
50
- "FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS",
51
- "Setup error: %s"
52
- ),
53
- /** If an invalid usage error was done, this error would pop up. */
54
- FASTIFY_RABBIT_MQ_ERR_USAGE: (0, import_error.default)(
55
- "FASTIFY_RABBIT_MQ_ERR_USAGE",
56
- "Usage error: %s"
57
- )
58
- };
59
-
60
- // src/validation.ts
61
- var validateOpts = async (options) => {
62
- if (typeof options.connection === "undefined") {
63
- throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(
64
- "connection or findServers must be defined."
65
- );
66
- }
67
- if (typeof options.connection !== "undefined") {
68
- if (typeof options.connection !== "object") {
69
- }
70
- }
71
- };
72
-
73
- // src/index.ts
74
- var decorateFastifyInstance = (fastify, options, connection) => {
75
- const { namespace = "" } = options;
76
- if (typeof namespace !== "undefined" && namespace !== "") {
77
- fastify.log.debug("[fastify-rabbitmq] Namespace Attempt: %s", namespace);
78
- }
79
- if (typeof namespace !== "undefined" && namespace !== "") {
80
- if (typeof fastify.rabbitmq === "undefined") {
81
- fastify.decorate("rabbitmq", /* @__PURE__ */ Object.create(null));
82
- }
83
- if (typeof fastify.rabbitmq[namespace] !== "undefined") {
84
- throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(
85
- `Already registered with namespace: ${namespace}`
86
- );
87
- }
88
- fastify.log.trace(
89
- "[fastify-rabbitmq] Decorate Fastify with Namespace: %",
90
- namespace
91
- );
92
- fastify.rabbitmq[namespace] = connection;
93
- } else {
94
- if (typeof fastify.rabbitmq !== "undefined") {
95
- throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(
96
- "Already registered."
97
- );
98
- }
99
- }
100
- if (typeof fastify.rabbitmq === "undefined") {
101
- fastify.log.trace("[fastify-rabbitmq] Decorate Fastify");
102
- fastify.decorate("rabbitmq", connection);
103
- }
104
- };
105
- var fastifyRabbit = (0, import_fastify_plugin.default)(async (fastify, opts) => {
106
- await validateOpts(opts);
107
- const { connection } = opts;
108
- const c = new import_rabbitmq_client.Connection(connection);
109
- decorateFastifyInstance(fastify, opts, c);
110
- });
111
- var index_default = fastifyRabbit;
112
- // Annotate the CommonJS export names for ESM import in node:
113
- 0 && (module.exports = {
114
- decorateFastifyInstance
115
- });
package/lib/esm/index.mjs DELETED
@@ -1,82 +0,0 @@
1
- // src/index.ts
2
- import fp from "fastify-plugin";
3
- import {
4
- Connection as RabbitMQConnection
5
- } from "rabbitmq-client";
6
-
7
- // src/errors.ts
8
- import createError from "@fastify/error";
9
- var errors = {
10
- /** Error if there is an invalid option used during registration. */
11
- FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS: createError(
12
- "FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS",
13
- "Invalid options: %s"
14
- ),
15
- /** Error if there is an setup error of the plugin itself. */
16
- FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS: createError(
17
- "FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS",
18
- "Setup error: %s"
19
- ),
20
- /** If an invalid usage error was done, this error would pop up. */
21
- FASTIFY_RABBIT_MQ_ERR_USAGE: createError(
22
- "FASTIFY_RABBIT_MQ_ERR_USAGE",
23
- "Usage error: %s"
24
- )
25
- };
26
-
27
- // src/validation.ts
28
- var validateOpts = async (options) => {
29
- if (typeof options.connection === "undefined") {
30
- throw new errors.FASTIFY_RABBIT_MQ_ERR_INVALID_OPTS(
31
- "connection or findServers must be defined."
32
- );
33
- }
34
- if (typeof options.connection !== "undefined") {
35
- if (typeof options.connection !== "object") {
36
- }
37
- }
38
- };
39
-
40
- // src/index.ts
41
- var decorateFastifyInstance = (fastify, options, connection) => {
42
- const { namespace = "" } = options;
43
- if (typeof namespace !== "undefined" && namespace !== "") {
44
- fastify.log.debug("[fastify-rabbitmq] Namespace Attempt: %s", namespace);
45
- }
46
- if (typeof namespace !== "undefined" && namespace !== "") {
47
- if (typeof fastify.rabbitmq === "undefined") {
48
- fastify.decorate("rabbitmq", /* @__PURE__ */ Object.create(null));
49
- }
50
- if (typeof fastify.rabbitmq[namespace] !== "undefined") {
51
- throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(
52
- `Already registered with namespace: ${namespace}`
53
- );
54
- }
55
- fastify.log.trace(
56
- "[fastify-rabbitmq] Decorate Fastify with Namespace: %",
57
- namespace
58
- );
59
- fastify.rabbitmq[namespace] = connection;
60
- } else {
61
- if (typeof fastify.rabbitmq !== "undefined") {
62
- throw new errors.FASTIFY_RABBIT_MQ_ERR_SETUP_ERRORS(
63
- "Already registered."
64
- );
65
- }
66
- }
67
- if (typeof fastify.rabbitmq === "undefined") {
68
- fastify.log.trace("[fastify-rabbitmq] Decorate Fastify");
69
- fastify.decorate("rabbitmq", connection);
70
- }
71
- };
72
- var fastifyRabbit = fp(async (fastify, opts) => {
73
- await validateOpts(opts);
74
- const { connection } = opts;
75
- const c = new RabbitMQConnection(connection);
76
- decorateFastifyInstance(fastify, opts, c);
77
- });
78
- var index_default = fastifyRabbit;
79
- export {
80
- decorateFastifyInstance,
81
- index_default as default
82
- };
@@ -1,59 +0,0 @@
1
- import * as fastify from 'fastify';
2
- import { FastifyInstance } from 'fastify';
3
- import { ConnectionOptions, Connection } from 'rabbitmq-client';
4
- export { ConnectionOptions } from 'rabbitmq-client';
5
-
6
- interface FastifyRabbitMQOptions {
7
- /**
8
- * @since 1.0.0
9
- * @remarks Connection String or object pointing to the RabbitMQ Broker Services
10
- */
11
- connection: string | ConnectionOptions;
12
- /**
13
- * @since 1.0.0
14
- * @remarks To set the custom nNamespace within this plugin instance. Used to register this plugin more than one time.
15
- */
16
- namespace?: string;
17
- }
18
-
19
- declare module "fastify" {
20
- interface FastifyInstance {
21
- /** Main Decorator for Fastify **/
22
- rabbitmq: Connection & fastifyRabbitMQ.FastifyRabbitMQNO;
23
- }
24
- }
25
- declare namespace fastifyRabbitMQ {
26
- interface FastifyRabbitMQNO {
27
- [namespace: string]: Connection;
28
- }
29
- }
30
-
31
- /**
32
- * How we talk with Fastify
33
- * @since 1.0.0
34
- * @param fastify
35
- * @param options
36
- * @param connection
37
- */
38
- declare const decorateFastifyInstance: (fastify: FastifyInstance, options: FastifyRabbitMQOptions, connection: any) => void;
39
- /**
40
- * Main Function
41
- * @since 1.0.0
42
- * @example
43
- * This is the basics on how to use this plugin:
44
- * ```js
45
- * app.register(fastifyRabbit, {
46
- * connection: 'amqp://guest:guest@localhost'
47
- * })
48
- * ```
49
- * This will allow you to read from your Fastify "object" and
50
- * use this plugin at the "rabbitmq" level. From there you can execute and maintain
51
- * the RabbitMQ Connection using the 'rabbitmq-client' package, which is wrapping around
52
- * this plugin to execute functions it provides.
53
- *
54
- * @see [https://cody-greene.github.io/node-rabbitmq-client/latest/index.html](https://cody-greene.github.io/node-rabbitmq-client/latest/index.html)
55
- *
56
- */
57
- declare const fastifyRabbit: fastify.FastifyPluginCallback<FastifyRabbitMQOptions, fastify.RawServerDefault, fastify.FastifyTypeProviderDefault, fastify.FastifyBaseLogger>;
58
-
59
- export { type FastifyRabbitMQOptions, decorateFastifyInstance, fastifyRabbit as default, fastifyRabbitMQ };