@jsnw/nestjs-rabbitmq 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.
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
+ var _, done = false;
8
+ for (var i = decorators.length - 1; i >= 0; i--) {
9
+ var context = {};
10
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
+ if (kind === "accessor") {
15
+ if (result === void 0) continue;
16
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
+ if (_ = accept(result.get)) descriptor.get = _;
18
+ if (_ = accept(result.set)) descriptor.set = _;
19
+ if (_ = accept(result.init)) initializers.unshift(_);
20
+ }
21
+ else if (_ = accept(result)) {
22
+ if (kind === "field") initializers.unshift(_);
23
+ else descriptor[key] = _;
24
+ }
25
+ }
26
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
+ done = true;
28
+ };
29
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
+ var useValue = arguments.length > 2;
31
+ for (var i = 0; i < initializers.length; i++) {
32
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
+ }
34
+ return useValue ? value : void 0;
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.RabbitmqExplorerService = void 0;
38
+ const common_1 = require("@nestjs/common");
39
+ const rabbitmq_metadata_storage_1 = require("./rabbitmq-metadata-storage");
40
+ const rabbitmq_helpers_1 = require("./rabbitmq.helpers");
41
+ const rabbitmq_consts_1 = require("./rabbitmq.consts");
42
+ let RabbitmqExplorerService = (() => {
43
+ let _classDecorators = [(0, common_1.Injectable)()];
44
+ let _classDescriptor;
45
+ let _classExtraInitializers = [];
46
+ let _classThis;
47
+ var RabbitmqExplorerService = class {
48
+ static { _classThis = this; }
49
+ static {
50
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
51
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
52
+ RabbitmqExplorerService = _classThis = _classDescriptor.value;
53
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
54
+ __runInitializers(_classThis, _classExtraInitializers);
55
+ }
56
+ discoveryService;
57
+ metadataScanner;
58
+ reflector;
59
+ instancesManager;
60
+ logger = new common_1.Logger(RabbitmqExplorerService.name);
61
+ constructor(discoveryService, metadataScanner, reflector, instancesManager) {
62
+ this.discoveryService = discoveryService;
63
+ this.metadataScanner = metadataScanner;
64
+ this.reflector = reflector;
65
+ this.instancesManager = instancesManager;
66
+ }
67
+ /**
68
+ * @return {Promise<void>}
69
+ */
70
+ async onApplicationBootstrap() {
71
+ await this.setupInfrastructure();
72
+ await this.setupSubscribers();
73
+ }
74
+ /**
75
+ * @return {Promise<void>}
76
+ * @private
77
+ */
78
+ async setupInfrastructure() {
79
+ const instances = this.instancesManager.getAllInstances();
80
+ for (const instance of instances) {
81
+ const metadata = rabbitmq_metadata_storage_1.RabbitmqMetadataStorage.getMetadata((0, rabbitmq_helpers_1.getInstanceToken)(instance.name));
82
+ if (!metadata || (metadata.exchanges.size === 0 && metadata.queues.size === 0))
83
+ continue;
84
+ const exchanges = Array.from(metadata.exchanges), queues = Array.from(metadata.queues);
85
+ if (exchanges.length > 0)
86
+ await Promise.all(exchanges.map(exchange => instance.declareExchange(exchange)));
87
+ if (queues.length > 0)
88
+ await Promise.all(queues.map(queue => instance.declareQueue(queue)));
89
+ }
90
+ }
91
+ /**
92
+ * @return {Promise<void>}
93
+ * @private
94
+ */
95
+ async setupSubscribers() {
96
+ const wrappers = [
97
+ ...this.discoveryService.getProviders(),
98
+ ...this.discoveryService.getControllers()
99
+ ];
100
+ for (const wrapper of wrappers) {
101
+ const { instance } = wrapper;
102
+ if (!instance || typeof instance !== 'object')
103
+ continue;
104
+ const prototype = Object.getPrototypeOf(instance);
105
+ if (!prototype)
106
+ continue;
107
+ const methodNames = this.metadataScanner.getAllMethodNames(prototype);
108
+ for (const methodName of methodNames)
109
+ await this.tryRegisterSubscriber(instance, methodName);
110
+ }
111
+ }
112
+ /**
113
+ * @param {any} instance
114
+ * @param {string} methodName
115
+ * @return {Promise<void>}
116
+ * @private
117
+ */
118
+ async tryRegisterSubscriber(instance, methodName) {
119
+ const methodRef = instance[methodName];
120
+ const subscriptionMetadata = this.reflector.get(rabbitmq_consts_1.RABBITMQ_SUBSCRIBE_METADATA_KEY, methodRef);
121
+ if (!subscriptionMetadata)
122
+ return;
123
+ const rabbitmqInstance = this.instancesManager.getInstance(subscriptionMetadata.instanceToken);
124
+ if (!rabbitmqInstance) {
125
+ this.logger.error(`Instance ${subscriptionMetadata.instanceName}" not found for subscriber ${instance.constructor.name}.${methodName}`);
126
+ return;
127
+ }
128
+ this.logger.log(`Registering subscriber: ${instance.constructor.name}.${methodName} -> ${subscriptionMetadata.queue.name}`);
129
+ await rabbitmqInstance.subscribe({
130
+ id: subscriptionMetadata.id,
131
+ queue: subscriptionMetadata.queue,
132
+ requeue: subscriptionMetadata.requeue,
133
+ concurrency: subscriptionMetadata.concurrency,
134
+ prefetchSize: subscriptionMetadata.prefetchSize,
135
+ prefetchCount: subscriptionMetadata.prefetchCount,
136
+ autoStart: subscriptionMetadata.autoStart,
137
+ validation: subscriptionMetadata.validation
138
+ }, { instance: instance, methodName: methodName });
139
+ }
140
+ };
141
+ return RabbitmqExplorerService = _classThis;
142
+ })();
143
+ exports.RabbitmqExplorerService = RabbitmqExplorerService;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
+ var _, done = false;
8
+ for (var i = decorators.length - 1; i >= 0; i--) {
9
+ var context = {};
10
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
+ if (kind === "accessor") {
15
+ if (result === void 0) continue;
16
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
+ if (_ = accept(result.get)) descriptor.get = _;
18
+ if (_ = accept(result.set)) descriptor.set = _;
19
+ if (_ = accept(result.init)) initializers.unshift(_);
20
+ }
21
+ else if (_ = accept(result)) {
22
+ if (kind === "field") initializers.unshift(_);
23
+ else descriptor[key] = _;
24
+ }
25
+ }
26
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
+ done = true;
28
+ };
29
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
+ var useValue = arguments.length > 2;
31
+ for (var i = 0; i < initializers.length; i++) {
32
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
+ }
34
+ return useValue ? value : void 0;
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.RabbitmqInstancesManager = void 0;
38
+ const common_1 = require("@nestjs/common");
39
+ const rabbitmq_helpers_1 = require("./rabbitmq.helpers");
40
+ let RabbitmqInstancesManager = (() => {
41
+ let _classDecorators = [(0, common_1.Injectable)()];
42
+ let _classDescriptor;
43
+ let _classExtraInitializers = [];
44
+ let _classThis;
45
+ var RabbitmqInstancesManager = class {
46
+ static { _classThis = this; }
47
+ static {
48
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
49
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
50
+ RabbitmqInstancesManager = _classThis = _classDescriptor.value;
51
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
52
+ __runInitializers(_classThis, _classExtraInitializers);
53
+ }
54
+ /**
55
+ * @type {Map<string, Rabbitmq>}
56
+ * @private
57
+ */
58
+ instances = new Map();
59
+ /**
60
+ * @param {string | RabbitmqConstructorParams} token
61
+ * @param {Rabbitmq} instance
62
+ */
63
+ addInstance(token, instance) {
64
+ token = typeof token === 'string' ? token : (0, rabbitmq_helpers_1.getInstanceToken)(token);
65
+ if (this.instances.has(token))
66
+ return;
67
+ this.instances.set(token, instance);
68
+ }
69
+ /**
70
+ * @param {string | RabbitmqConstructorParams} token
71
+ * @return {Rabbitmq | null}
72
+ */
73
+ getInstance(token) {
74
+ token = typeof token === 'string' ? token : (0, rabbitmq_helpers_1.getInstanceToken)(token);
75
+ return this.instances.get(token) ?? null;
76
+ }
77
+ /**
78
+ * @param {string | RabbitmqConstructorParams} token
79
+ * @return {boolean}
80
+ */
81
+ hasInstance(token) {
82
+ token = typeof token === 'string' ? token : (0, rabbitmq_helpers_1.getInstanceToken)(token);
83
+ return this.instances.has(token);
84
+ }
85
+ /**
86
+ * @return {Rabbitmq[]}
87
+ */
88
+ getAllInstances() {
89
+ return Array.from(this.instances.values());
90
+ }
91
+ /**
92
+ * @return {Promise<void>}
93
+ */
94
+ async onApplicationShutdown() {
95
+ await Promise.allSettled(this.getAllInstances().map(instance => instance.close()));
96
+ }
97
+ };
98
+ return RabbitmqInstancesManager = _classThis;
99
+ })();
100
+ exports.RabbitmqInstancesManager = RabbitmqInstancesManager;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RabbitmqMetadataStorage = void 0;
4
+ const rabbitmq_helpers_1 = require("./rabbitmq.helpers");
5
+ class RabbitmqMetadataStorage {
6
+ /**
7
+ * @type {Map<string, Metadata>}
8
+ * @private
9
+ */
10
+ static storage = new Map();
11
+ /**
12
+ * @param {string | RabbitmqConstructorParams} token
13
+ * @param {AddMetadataParams} metadata
14
+ */
15
+ static addMetadata(token, metadata = {}) {
16
+ token = typeof token === 'string' ? token : (0, rabbitmq_helpers_1.getInstanceToken)(token);
17
+ const { exchanges, queues } = metadata;
18
+ if (!this.storage.has(token))
19
+ this.storage.set(token, { exchanges: new Set(), queues: new Set() });
20
+ const metadataStorage = this.storage.get(token);
21
+ if (exchanges && exchanges.length > 0)
22
+ for (const exchange of exchanges)
23
+ metadataStorage.exchanges.add(exchange);
24
+ if (queues && queues.length > 0)
25
+ for (const queue of queues)
26
+ metadataStorage.queues.add(queue);
27
+ }
28
+ /**
29
+ * @param {string | RabbitmqConstructorParams} token
30
+ * @return {Metadata}
31
+ */
32
+ static getMetadata(token) {
33
+ token = typeof token === 'string' ? token : (0, rabbitmq_helpers_1.getInstanceToken)(token);
34
+ const metadataStorage = this.storage.get(token);
35
+ return metadataStorage ?? { exchanges: new Set(), queues: new Set() };
36
+ }
37
+ }
38
+ exports.RabbitmqMetadataStorage = RabbitmqMetadataStorage;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RABBITMQ_SUBSCRIBE_METADATA_KEY = exports.RABBITMQ_INSTANCE_TOKEN_PREFIX = exports.RABBITMQ_INSTANCE_DEFAULT_NAME = void 0;
4
+ exports.RABBITMQ_INSTANCE_DEFAULT_NAME = 'default';
5
+ exports.RABBITMQ_INSTANCE_TOKEN_PREFIX = 'RABBITMQ_INSTANCE_';
6
+ exports.RABBITMQ_SUBSCRIBE_METADATA_KEY = Symbol('RABBITMQ_SUBSCRIBE_METADATA');
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RabbitmqSubscribe = exports.InjectRabbitmq = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const rabbitmq_consts_1 = require("./rabbitmq.consts");
6
+ const rabbitmq_helpers_1 = require("./rabbitmq.helpers");
7
+ /**
8
+ * @param {string} [instanceName = RABBITMQ_INSTANCE_DEFAULT_NAME]
9
+ * @return {PropertyDecorator & ParameterDecorator}
10
+ * @constructor
11
+ */
12
+ const InjectRabbitmq = (instanceName = rabbitmq_consts_1.RABBITMQ_INSTANCE_DEFAULT_NAME) => (0, common_1.Inject)((0, rabbitmq_helpers_1.getInstanceToken)(instanceName));
13
+ exports.InjectRabbitmq = InjectRabbitmq;
14
+ /**
15
+ * @return {MethodDecorator}
16
+ * @constructor
17
+ */
18
+ const RabbitmqSubscribe = (params) => {
19
+ return (target, key, descriptor) => {
20
+ (0, common_1.SetMetadata)(rabbitmq_consts_1.RABBITMQ_SUBSCRIBE_METADATA_KEY, {
21
+ instanceName: params.instanceName ?? rabbitmq_consts_1.RABBITMQ_INSTANCE_DEFAULT_NAME,
22
+ instanceToken: (0, rabbitmq_helpers_1.getInstanceToken)(params.instanceName ?? rabbitmq_consts_1.RABBITMQ_INSTANCE_DEFAULT_NAME),
23
+ id: params.id,
24
+ queue: params.queue,
25
+ autoStart: params.autoStart !== undefined ? params.autoStart : true,
26
+ concurrency: params.concurrency ?? 1,
27
+ prefetchSize: params.prefetchSize ?? 0,
28
+ prefetchCount: params.prefetchCount ?? 1,
29
+ requeue: params.requeue,
30
+ validation: params.validation ? {
31
+ schema: params.validation.schema,
32
+ onFail: params.validation.onFail ?? 'drop'
33
+ } : null
34
+ })(target, key, descriptor);
35
+ return descriptor;
36
+ };
37
+ };
38
+ exports.RabbitmqSubscribe = RabbitmqSubscribe;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveInstanceName = resolveInstanceName;
4
+ exports.getInstanceToken = getInstanceToken;
5
+ const rabbitmq_consts_1 = require("./rabbitmq.consts");
6
+ /**
7
+ * @param {string | RabbitmqConstructorParams} arg
8
+ * @return {string}
9
+ */
10
+ function resolveInstanceName(arg) {
11
+ if (typeof arg === 'string')
12
+ return arg.toLowerCase();
13
+ if (arg.name && arg.name.trim() !== '')
14
+ return arg.name.trim().toLowerCase();
15
+ return `${arg.hostname}:${arg.port}/${(arg.vhost?.trim() ?? '').replace(/^\/|\/$/, '')}`.toLowerCase();
16
+ }
17
+ /**
18
+ * @param {string | RabbitmqConstructorParams} arg
19
+ * @return {string}
20
+ */
21
+ function getInstanceToken(arg) {
22
+ if (typeof arg === 'string') {
23
+ // It is an instance name
24
+ return `${rabbitmq_consts_1.RABBITMQ_INSTANCE_TOKEN_PREFIX}${arg}`.toLowerCase();
25
+ }
26
+ return `${rabbitmq_consts_1.RABBITMQ_INSTANCE_TOKEN_PREFIX}${resolveInstanceName(arg)}`.toLowerCase();
27
+ }
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
+ var _, done = false;
8
+ for (var i = decorators.length - 1; i >= 0; i--) {
9
+ var context = {};
10
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
+ if (kind === "accessor") {
15
+ if (result === void 0) continue;
16
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
+ if (_ = accept(result.get)) descriptor.get = _;
18
+ if (_ = accept(result.set)) descriptor.set = _;
19
+ if (_ = accept(result.init)) initializers.unshift(_);
20
+ }
21
+ else if (_ = accept(result)) {
22
+ if (kind === "field") initializers.unshift(_);
23
+ else descriptor[key] = _;
24
+ }
25
+ }
26
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
+ done = true;
28
+ };
29
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
+ var useValue = arguments.length > 2;
31
+ for (var i = 0; i < initializers.length; i++) {
32
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
+ }
34
+ return useValue ? value : void 0;
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.RabbitmqModule = void 0;
38
+ const common_1 = require("@nestjs/common");
39
+ const rabbitmq_metadata_storage_1 = require("./rabbitmq-metadata-storage");
40
+ const rabbitmq_core_module_1 = require("./rabbitmq-core.module");
41
+ const rabbitmq_helpers_1 = require("./rabbitmq.helpers");
42
+ let RabbitmqModule = (() => {
43
+ let _classDecorators = [(0, common_1.Module)({})];
44
+ let _classDescriptor;
45
+ let _classExtraInitializers = [];
46
+ let _classThis;
47
+ var RabbitmqModule = class {
48
+ static { _classThis = this; }
49
+ static {
50
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
51
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
52
+ RabbitmqModule = _classThis = _classDescriptor.value;
53
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
54
+ __runInitializers(_classThis, _classExtraInitializers);
55
+ }
56
+ /**
57
+ * @param {RabbitmqForRootParams} params
58
+ * @return {DynamicModule}
59
+ */
60
+ static forRoot(params) {
61
+ rabbitmq_metadata_storage_1.RabbitmqMetadataStorage.addMetadata(params, {
62
+ exchanges: params.exchanges ?? [],
63
+ queues: params.queues ?? []
64
+ });
65
+ return {
66
+ module: RabbitmqModule,
67
+ imports: [
68
+ rabbitmq_core_module_1.RabbitmqCoreModule.forRoot(params)
69
+ ],
70
+ exports: [],
71
+ providers: []
72
+ };
73
+ }
74
+ /**
75
+ * @param {RabbitmqForFeatureParams} params
76
+ * @return {DynamicModule}
77
+ */
78
+ static forFeature(params) {
79
+ rabbitmq_metadata_storage_1.RabbitmqMetadataStorage.addMetadata((0, rabbitmq_helpers_1.getInstanceToken)((0, rabbitmq_helpers_1.resolveInstanceName)(params.name)), {
80
+ exchanges: params.exchanges ?? [],
81
+ queues: params.queues ?? []
82
+ });
83
+ return {
84
+ module: RabbitmqModule,
85
+ imports: [],
86
+ providers: [],
87
+ exports: []
88
+ };
89
+ }
90
+ };
91
+ return RabbitmqModule = _classThis;
92
+ })();
93
+ exports.RabbitmqModule = RabbitmqModule;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,5 @@
1
+ export * from './rabbitmq';
2
+ export { RabbitmqModule } from './rabbitmq.module';
3
+ export type { RabbitmqForRootParams, RabbitmqForFeatureParams, RabbitmqSubscribeDecoratorParams } from './rabbitmq.types';
4
+ export { RabbitmqSubscribe, InjectRabbitmq } from './rabbitmq.decorators';
5
+ export { type AsyncMessage } from 'rabbitmq-client';
@@ -0,0 +1,3 @@
1
+ export { Rabbitmq, type RabbitmqConstructorParams, type RabbitmqResponse, type RabbitmqSubscribeParams, type RabbitmqMessageValidation, type RabbitmqSubscriber, type RabbitmqPublishOptions } from './rabbitmq';
2
+ export { RabbitmqExchange, type RabbitmqExchangeType, type RabbitmqExchangeDeclaration } from './rabbitmq-exchange';
3
+ export { RabbitmqQueue, type RabbitmqQueueArguments, type RabbitmqQueueBinding, type RabbitmqQueueDeclaration } from './rabbitmq-queue';
@@ -0,0 +1,18 @@
1
+ export type RabbitmqExchangeType = 'direct' | 'topic';
2
+ export type RabbitmqExchangeDeclaration = {
3
+ name: string;
4
+ type: RabbitmqExchangeType;
5
+ durable?: boolean;
6
+ autoDelete?: boolean;
7
+ };
8
+ export declare class RabbitmqExchange {
9
+ readonly _$type: 'exchange';
10
+ readonly name: string;
11
+ readonly type: RabbitmqExchangeType;
12
+ readonly durable: boolean;
13
+ readonly autoDelete: boolean;
14
+ /**
15
+ * @param {RabbitmqExchangeDeclaration} declaration
16
+ */
17
+ constructor(declaration: RabbitmqExchangeDeclaration);
18
+ }
@@ -0,0 +1,49 @@
1
+ import { type RabbitmqExchange } from './rabbitmq-exchange';
2
+ export type RabbitmqQueueArguments = {
3
+ /** Per-Queue Message TTL https://www.rabbitmq.com/ttl.html#per-queue-message-ttl */
4
+ 'x-message-ttl'?: number;
5
+ /** Queue Expiry https://www.rabbitmq.com/ttl.html#queue-ttl */
6
+ 'x-expires'?: number;
7
+ /** https://www.rabbitmq.com/maxlength.html */
8
+ 'x-max-length'?: number;
9
+ /** https://www.rabbitmq.com/maxlength.html */
10
+ 'x-overflow'?: 'drop-head' | 'reject-publish' | 'reject-publish-dlx';
11
+ /** https://www.rabbitmq.com/priority.html */
12
+ 'x-max-priority'?: number;
13
+ /** https://www.rabbitmq.com/quorum-queues.html
14
+ * https://www.rabbitmq.com/streams.html */
15
+ 'x-queue-type'?: 'quorum' | 'classic' | 'stream';
16
+ [k: string]: any;
17
+ };
18
+ export type RabbitmqQueueBinding = {
19
+ exchange: RabbitmqExchange;
20
+ routingKeys?: string[];
21
+ };
22
+ export type RabbitmqQueueDeclaration = {
23
+ name: string;
24
+ deadLetterExchange?: RabbitmqExchange | null;
25
+ deadLetterRoutingKey?: string | null;
26
+ arguments?: RabbitmqQueueArguments;
27
+ durable?: boolean;
28
+ autoDelete?: boolean;
29
+ exclusive?: boolean;
30
+ bindings?: RabbitmqQueueBinding[];
31
+ };
32
+ export declare class RabbitmqQueue {
33
+ readonly _$type: 'queue';
34
+ readonly name: string;
35
+ readonly arguments: RabbitmqQueueArguments;
36
+ readonly durable: boolean;
37
+ readonly autoDelete: boolean;
38
+ readonly exclusive: boolean;
39
+ /** https://www.rabbitmq.com/dlx.html */
40
+ readonly deadLetterExchange: RabbitmqExchange | null;
41
+ /** https://www.rabbitmq.com/dlx.html */
42
+ readonly deadLetterRoutingKey: string | null;
43
+ private readonly _bindings;
44
+ get bindings(): Required<RabbitmqQueueBinding>[];
45
+ /**
46
+ * @param {RabbitmqQueueDeclaration} declaration
47
+ */
48
+ constructor(declaration: RabbitmqQueueDeclaration);
49
+ }
@@ -0,0 +1,123 @@
1
+ import { z } from 'zod';
2
+ import { type AsyncMessage, Connection, type Consumer, ConsumerStatus, Publisher } from 'rabbitmq-client';
3
+ import { RabbitmqExchange } from './rabbitmq-exchange';
4
+ import { RabbitmqQueue } from './rabbitmq-queue';
5
+ import { Logger } from '@nestjs/common';
6
+ import { Jsonifiable } from 'type-fest';
7
+ export type RabbitmqConstructorParams = {
8
+ name: string;
9
+ /**
10
+ * The name that will be displayed in RabbitMQ management UI. By default - the same as the name
11
+ */
12
+ connectionName?: string;
13
+ hostname: string;
14
+ port: number;
15
+ username: string;
16
+ password: string;
17
+ vhost?: string;
18
+ connectionTimeout?: number;
19
+ };
20
+ export type RabbitmqResponse = 'ack' | 'drop' | 'requeue';
21
+ export type RabbitmqMessageValidation = {
22
+ schema: z.ZodTypeAny;
23
+ onFail?: RabbitmqResponse;
24
+ };
25
+ export type RabbitmqSubscribeParams = {
26
+ queue: RabbitmqQueue;
27
+ requeue?: boolean;
28
+ concurrency?: number;
29
+ prefetchSize?: number;
30
+ prefetchCount?: number;
31
+ validation?: RabbitmqMessageValidation;
32
+ } & ({
33
+ id: string;
34
+ autoStart: boolean;
35
+ } | {
36
+ id?: never;
37
+ autoStart?: never;
38
+ });
39
+ export type RabbitmqSubscriber = {
40
+ instance: any;
41
+ methodName: string;
42
+ } | ((data: any, message: AsyncMessage) => RabbitmqResponse | Promise<RabbitmqResponse>);
43
+ export type RabbitmqPublishOptions = {
44
+ exchange: RabbitmqExchange;
45
+ routingKey: string;
46
+ ttlMs?: number;
47
+ durable?: boolean;
48
+ } & ({
49
+ type: 'raw';
50
+ message: string | Buffer;
51
+ } | {
52
+ type: 'json';
53
+ message: Jsonifiable;
54
+ });
55
+ export declare class Rabbitmq {
56
+ readonly name: string;
57
+ protected readonly logger: Logger;
58
+ protected readonly connection: Connection;
59
+ protected readonly exchanges: Map<string, RabbitmqExchange>;
60
+ protected readonly queues: Map<string, RabbitmqQueue>;
61
+ protected readonly consumers: Set<Consumer>;
62
+ protected readonly consumersById: Map<string, {
63
+ isStarted: boolean;
64
+ consumer: Consumer;
65
+ }>;
66
+ protected publisher: Publisher | null;
67
+ constructor(name: string, connection: Connection);
68
+ constructor(params: RabbitmqConstructorParams);
69
+ /**
70
+ * @param {RabbitmqExchange} exchange
71
+ * @returns {Promise<boolean>}
72
+ */
73
+ declareExchange(exchange: RabbitmqExchange): Promise<boolean>;
74
+ /**
75
+ * @param {RabbitmqQueue} queue
76
+ * @returns {Promise<boolean>}
77
+ */
78
+ declareQueue(queue: RabbitmqQueue): Promise<boolean>;
79
+ /**
80
+ * @param {RabbitmqQueue} queue
81
+ * @returns {Promise<void>}
82
+ * @protected
83
+ */
84
+ protected setupQueueBindings(queue: RabbitmqQueue): Promise<void>;
85
+ /**
86
+ * @param {RabbitmqSubscribeParams} params
87
+ * @param {RabbitmqSubscriber} subscriber
88
+ * @returns {Promise<void>}
89
+ */
90
+ subscribe(params: RabbitmqSubscribeParams, subscriber: RabbitmqSubscriber): Promise<void>;
91
+ /**
92
+ * @param {string} id
93
+ * @returns {void}
94
+ */
95
+ startSubscriber(id: string): void;
96
+ /**
97
+ * @returns {void}
98
+ */
99
+ startPendingSubscribers(): void;
100
+ /**
101
+ * @param {RabbitmqSubscribeParams} params
102
+ * @param {RabbitmqSubscriber} subscriber
103
+ * @param {AsyncMessage} message
104
+ * @returns {Promise<ConsumerStatus>}
105
+ * @private
106
+ */
107
+ private internalConsumer;
108
+ /**
109
+ * @param {RabbitmqPublishOptions} options
110
+ * @return {Promise<void>}
111
+ */
112
+ publish(options: RabbitmqPublishOptions): Promise<void>;
113
+ /**
114
+ * @param {RabbitmqResponse | string} response
115
+ * @return {ConsumerStatus}
116
+ * @protected
117
+ */
118
+ protected mapRabbitmqResponseToConsumerStatus(response: RabbitmqResponse | string): ConsumerStatus;
119
+ /**
120
+ * @return {Promise<void>}
121
+ */
122
+ close(): Promise<void>;
123
+ }