@rtorcato/api-amqp 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Richard Torcato
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # @rtorcato/api-amqp
2
+
3
+ Typed [amqplib](https://github.com/amqp-node/amqplib) publisher/consumer helpers for RabbitMQ — JSON encoding, exchange/queue assertion, and ack-on-success / nack-on-throw.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @rtorcato/api-amqp amqplib
9
+ ```
10
+
11
+ `amqplib` is a peer dependency — you bring your own version (and often a shared connection).
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { connect, createPublisher, createConsumer } from '@rtorcato/api-amqp'
17
+
18
+ const { connection, channel } = await connect('amqp://localhost')
19
+
20
+ // Publisher — asserts the exchange, then JSON-encodes each message
21
+ const publish = await createPublisher<{ id: string }>(channel, { exchange: 'orders' })
22
+ publish('order.created', { id: '1' })
23
+
24
+ // Consumer — asserts the queue, acks on success, nacks when the handler throws
25
+ await createConsumer<{ id: string }>(channel, { queue: 'orders' }, async (order) => {
26
+ await process(order)
27
+ })
28
+ ```
29
+
30
+ `connect` returns `{ connection, channel }`; close the channel then the connection on shutdown. The publisher/consumer helpers also accept a channel you created yourself (e.g. a shared one).
31
+
32
+ ## Options
33
+
34
+ - **Publisher:** `{ exchange, exchangeType?, durable? }` — `exchangeType` defaults to `'topic'`, `durable` to `true`. Messages are published `persistent` with `content-type: application/json`.
35
+ - **Consumer:** `{ queue, durable?, prefetch?, requeueOnError? }` — `prefetch` defaults to `10`. On handler throw the message is nacked; set `requeueOnError: true` to requeue (beware poison-message loops).
36
+
37
+ ## Reconnection
38
+
39
+ Not included — amqplib does not reconnect on its own. For production resilience, wrap `connect` in a retry loop or use [`amqp-connection-manager`](https://github.com/jwalton/node-amqp-connection-manager) and pass its channel to these helpers.
40
+
41
+ Source: https://github.com/rtorcato/api-common/tree/main/packages/api-amqp
@@ -0,0 +1,48 @@
1
+ import amqp, { type Channel, type ConsumeMessage, type Options } from 'amqplib';
2
+ /** An open connection + channel. Close the channel then the connection when done. */
3
+ export type AmqpConnection = Awaited<ReturnType<typeof amqp.connect>>;
4
+ export interface AmqpChannel {
5
+ connection: AmqpConnection;
6
+ channel: Channel;
7
+ }
8
+ /** Open a connection and a channel to the broker (e.g. `amqp://localhost`). */
9
+ export declare function connect(url: string, socketOptions?: unknown): Promise<AmqpChannel>;
10
+ export interface PublisherOptions {
11
+ exchange: string;
12
+ /** Exchange type. Default: `'topic'`. */
13
+ exchangeType?: 'direct' | 'topic' | 'fanout' | 'headers';
14
+ /** Survive a broker restart. Default: `true`. */
15
+ durable?: boolean;
16
+ }
17
+ /**
18
+ * Assert the exchange and return a typed publish function that JSON-encodes messages.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const publish = await createPublisher(channel, { exchange: 'orders' })
23
+ * publish('order.created', { id: '1', total: 42 })
24
+ * ```
25
+ */
26
+ export declare function createPublisher<T = unknown>(channel: Channel, options: PublisherOptions): Promise<(routingKey: string, message: T, publishOptions?: Options.Publish) => boolean>;
27
+ export interface ConsumerOptions {
28
+ queue: string;
29
+ /** Survive a broker restart. Default: `true`. */
30
+ durable?: boolean;
31
+ /** Max unacknowledged messages in flight. Default: `10`. */
32
+ prefetch?: number;
33
+ /** Requeue a message when the handler throws (risks a poison-message loop). Default: `false`. */
34
+ requeueOnError?: boolean;
35
+ }
36
+ /**
37
+ * Assert the queue and consume JSON messages. The message is acked when the handler
38
+ * resolves, and nacked when it throws (requeued only if `requeueOnError`).
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * await createConsumer<OrderCreated>(channel, { queue: 'orders' }, async (order) => {
43
+ * await process(order)
44
+ * })
45
+ * ```
46
+ */
47
+ export declare function createConsumer<T = unknown>(channel: Channel, options: ConsumerOptions, handler: (message: T, raw: ConsumeMessage) => Promise<void> | void): Promise<void>;
48
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,EAAE,EAAE,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,KAAK,OAAO,EAAE,MAAM,SAAS,CAAA;AAU/E,qFAAqF;AACrF,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;AAErE,MAAM,WAAW,WAAW;IAC3B,UAAU,EAAE,cAAc,CAAA;IAC1B,OAAO,EAAE,OAAO,CAAA;CAChB;AAED,+EAA+E;AAC/E,wBAAsB,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,CAAC,CAIxF;AAED,MAAM,WAAW,gBAAgB;IAChC,QAAQ,EAAE,MAAM,CAAA;IAChB,yCAAyC;IACzC,YAAY,CAAC,EAAE,QAAQ,GAAG,OAAO,GAAG,QAAQ,GAAG,SAAS,CAAA;IACxD,iDAAiD;IACjD,OAAO,CAAC,EAAE,OAAO,CAAA;CACjB;AAED;;;;;;;;GAQG;AACH,wBAAsB,eAAe,CAAC,CAAC,GAAG,OAAO,EAChD,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,gBAAgB,GACvB,OAAO,CAAC,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,OAAO,KAAK,OAAO,CAAC,CAUxF;AAED,MAAM,WAAW,eAAe;IAC/B,KAAK,EAAE,MAAM,CAAA;IACb,iDAAiD;IACjD,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,iGAAiG;IACjG,cAAc,CAAC,EAAE,OAAO,CAAA;CACxB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,CAAC,GAAG,OAAO,EAC/C,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,eAAe,EACxB,OAAO,EAAE,CAAC,OAAO,EAAE,CAAC,EAAE,GAAG,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,GAChE,OAAO,CAAC,IAAI,CAAC,CAaf"}
package/dist/index.js ADDED
@@ -0,0 +1,54 @@
1
+ import amqp from 'amqplib';
2
+ /** Open a connection and a channel to the broker (e.g. `amqp://localhost`). */
3
+ export async function connect(url, socketOptions) {
4
+ const connection = await amqp.connect(url, socketOptions);
5
+ const channel = await connection.createChannel();
6
+ return { connection, channel };
7
+ }
8
+ /**
9
+ * Assert the exchange and return a typed publish function that JSON-encodes messages.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * const publish = await createPublisher(channel, { exchange: 'orders' })
14
+ * publish('order.created', { id: '1', total: 42 })
15
+ * ```
16
+ */
17
+ export async function createPublisher(channel, options) {
18
+ await channel.assertExchange(options.exchange, options.exchangeType ?? 'topic', {
19
+ durable: options.durable ?? true,
20
+ });
21
+ return (routingKey, message, publishOptions) => channel.publish(options.exchange, routingKey, Buffer.from(JSON.stringify(message)), {
22
+ contentType: 'application/json',
23
+ persistent: true,
24
+ ...publishOptions,
25
+ });
26
+ }
27
+ /**
28
+ * Assert the queue and consume JSON messages. The message is acked when the handler
29
+ * resolves, and nacked when it throws (requeued only if `requeueOnError`).
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * await createConsumer<OrderCreated>(channel, { queue: 'orders' }, async (order) => {
34
+ * await process(order)
35
+ * })
36
+ * ```
37
+ */
38
+ export async function createConsumer(channel, options, handler) {
39
+ await channel.assertQueue(options.queue, { durable: options.durable ?? true });
40
+ await channel.prefetch(options.prefetch ?? 10);
41
+ await channel.consume(options.queue, async (raw) => {
42
+ if (!raw)
43
+ return; // consumer cancelled by the broker
44
+ try {
45
+ const message = JSON.parse(raw.content.toString());
46
+ await handler(message, raw);
47
+ channel.ack(raw);
48
+ }
49
+ catch {
50
+ channel.nack(raw, false, options.requeueOnError ?? false);
51
+ }
52
+ });
53
+ }
54
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,IAAyD,MAAM,SAAS,CAAA;AAkB/E,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,GAAW,EAAE,aAAuB;IACjE,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,aAAa,CAAC,CAAA;IACzD,MAAM,OAAO,GAAG,MAAM,UAAU,CAAC,aAAa,EAAE,CAAA;IAChD,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,CAAA;AAC/B,CAAC;AAUD;;;;;;;;G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,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC,CAAA;QAC1D,CAAC;IACF,CAAC,CAAC,CAAA;AACH,CAAC"}
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@rtorcato/api-amqp",
3
+ "version": "0.2.0",
4
+ "description": "Typed amqplib publisher/consumer helpers for RabbitMQ — JSON encoding, exchange/queue assertion, and ack/nack handling.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Richard Torcato",
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "peerDependencies": {
23
+ "amqplib": "^0.10.0"
24
+ },
25
+ "devDependencies": {
26
+ "@types/amqplib": "^0.10.5",
27
+ "amqplib": "^0.10.9",
28
+ "typescript": "~6.0.3"
29
+ },
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "keywords": [
34
+ "api",
35
+ "nodejs",
36
+ "typescript",
37
+ "amqp",
38
+ "amqplib",
39
+ "rabbitmq",
40
+ "messaging"
41
+ ],
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/rtorcato/api-common.git",
45
+ "directory": "packages/api-amqp"
46
+ },
47
+ "homepage": "https://github.com/rtorcato/api-common/tree/main/packages/api-amqp#readme",
48
+ "bugs": {
49
+ "url": "https://github.com/rtorcato/api-common/issues"
50
+ },
51
+ "scripts": {
52
+ "build": "tsc -p tsconfig.build.json",
53
+ "typecheck": "tsc --noEmit",
54
+ "test": "vitest run"
55
+ }
56
+ }