@lokative/messaging 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +458 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +8 -0
- package/dist/messaging.config.d.ts +15 -0
- package/dist/messaging.config.js +1 -0
- package/dist/messaging.decorator.d.ts +2 -0
- package/dist/messaging.decorator.js +16 -0
- package/dist/messaging.module.d.ts +5 -0
- package/dist/messaging.module.js +31 -0
- package/dist/messaging.publisher.d.ts +6 -0
- package/dist/messaging.publisher.js +29 -0
- package/dist/messaging.registry.d.ts +12 -0
- package/dist/messaging.registry.js +64 -0
- package/dist/transport.interface.d.ts +18 -0
- package/dist/transport.interface.js +1 -0
- package/dist/transports/kafka.transport.d.ts +15 -0
- package/dist/transports/kafka.transport.js +79 -0
- package/dist/transports/nats.transport.d.ts +20 -0
- package/dist/transports/nats.transport.js +87 -0
- package/dist/transports/redis.transport.d.ts +16 -0
- package/dist/transports/redis.transport.js +68 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lokative (https://lokative.com)
|
|
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,458 @@
|
|
|
1
|
+
# @lokative/messaging
|
|
2
|
+
|
|
3
|
+
A transport-agnostic messaging module for NestJS. Ships with built-in NATS JetStream, Kafka, and Redis transports. Swap transports with a single config change — your handlers and publishers stay the same.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @lokative/messaging
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Install the peer dependency for your chosen transport:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
# NATS JetStream
|
|
15
|
+
npm install nats
|
|
16
|
+
|
|
17
|
+
# Kafka
|
|
18
|
+
npm install kafkajs
|
|
19
|
+
|
|
20
|
+
# Redis
|
|
21
|
+
npm install redis
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## Quick Start
|
|
27
|
+
|
|
28
|
+
### NATS JetStream
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { Module } from '@nestjs/common';
|
|
32
|
+
import { MessagingModule, NatsTransport } from '@lokative/messaging';
|
|
33
|
+
|
|
34
|
+
@Module({
|
|
35
|
+
imports: [
|
|
36
|
+
MessagingModule.register({
|
|
37
|
+
transport: NatsTransport,
|
|
38
|
+
transportOptions: {
|
|
39
|
+
servers: ['nats://localhost:4222'],
|
|
40
|
+
},
|
|
41
|
+
streams: [
|
|
42
|
+
{ name: 'ORDERS', subjects: ['order.created', 'order.updated'] },
|
|
43
|
+
],
|
|
44
|
+
consumers: {
|
|
45
|
+
group: 'order-service',
|
|
46
|
+
},
|
|
47
|
+
}),
|
|
48
|
+
],
|
|
49
|
+
})
|
|
50
|
+
export class AppModule {}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Kafka
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { Module } from '@nestjs/common';
|
|
57
|
+
import { MessagingModule, KafkaTransport } from '@lokative/messaging';
|
|
58
|
+
|
|
59
|
+
@Module({
|
|
60
|
+
imports: [
|
|
61
|
+
MessagingModule.register({
|
|
62
|
+
transport: KafkaTransport,
|
|
63
|
+
transportOptions: {
|
|
64
|
+
brokers: ['localhost:9092'],
|
|
65
|
+
clientId: 'order-service',
|
|
66
|
+
},
|
|
67
|
+
consumers: {
|
|
68
|
+
group: 'order-service-group',
|
|
69
|
+
},
|
|
70
|
+
}),
|
|
71
|
+
],
|
|
72
|
+
})
|
|
73
|
+
export class AppModule {}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Redis
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
import { Module } from '@nestjs/common';
|
|
80
|
+
import { MessagingModule, RedisTransport } from '@lokative/messaging';
|
|
81
|
+
|
|
82
|
+
@Module({
|
|
83
|
+
imports: [
|
|
84
|
+
MessagingModule.register({
|
|
85
|
+
transport: RedisTransport,
|
|
86
|
+
transportOptions: {
|
|
87
|
+
url: 'redis://localhost:6379',
|
|
88
|
+
},
|
|
89
|
+
}),
|
|
90
|
+
],
|
|
91
|
+
})
|
|
92
|
+
export class AppModule {}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Redis can also be configured with `host` and `port` instead of `url`:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
transportOptions: {
|
|
99
|
+
host: '10.0.0.5',
|
|
100
|
+
port: 6380,
|
|
101
|
+
}
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Configuration
|
|
107
|
+
|
|
108
|
+
`MessagingModule.register()` accepts a `MessagingConfig` object:
|
|
109
|
+
|
|
110
|
+
| Property | Type | Required | Description |
|
|
111
|
+
| ------------------ | --------------------------- | -------- | ------------------------------------------------ |
|
|
112
|
+
| `transport` | `Type<MessagingTransport>` | Yes | The transport class to use |
|
|
113
|
+
| `transportOptions` | `Record<string, any>` | No | Transport-specific connection options |
|
|
114
|
+
| `streams` | `{ name, subjects[] }[]` | No | Stream/topic definitions (used by NATS transport) |
|
|
115
|
+
| `consumers` | `ConsumerOptions` | No | Consumer group configuration |
|
|
116
|
+
|
|
117
|
+
### Consumer Options
|
|
118
|
+
|
|
119
|
+
| Property | Type | Description |
|
|
120
|
+
| -------- | --------- | -------------------------------------------- |
|
|
121
|
+
| `group` | `string` | Consumer group / durable name |
|
|
122
|
+
| `retry` | `number` | Number of retry attempts on failure |
|
|
123
|
+
| `dlq` | `boolean` | Enable dead-letter queue for failed messages |
|
|
124
|
+
|
|
125
|
+
### Transport Options
|
|
126
|
+
|
|
127
|
+
#### `NatsTransportOptions`
|
|
128
|
+
|
|
129
|
+
| Property | Type | Required | Description |
|
|
130
|
+
| --------- | --------------------------- | -------- | ------------------------------------ |
|
|
131
|
+
| `servers` | `string[]` | Yes | NATS server URLs |
|
|
132
|
+
| `streams` | `{ name, subjects[] }[]` | No | Overrides top-level `streams` config |
|
|
133
|
+
|
|
134
|
+
#### `KafkaTransportOptions`
|
|
135
|
+
|
|
136
|
+
| Property | Type | Required | Description |
|
|
137
|
+
| ---------- | ---------- | -------- | ---------------------------------- |
|
|
138
|
+
| `brokers` | `string[]` | Yes | Kafka broker addresses |
|
|
139
|
+
| `clientId` | `string` | No | Client identifier (default: `nestjs-app`) |
|
|
140
|
+
|
|
141
|
+
#### `RedisTransportOptions`
|
|
142
|
+
|
|
143
|
+
| Property | Type | Required | Description |
|
|
144
|
+
| -------- | -------- | -------- | -------------------------------------------- |
|
|
145
|
+
| `url` | `string` | No | Redis connection URL (e.g. `redis://localhost:6379`) |
|
|
146
|
+
| `host` | `string` | No | Redis host (default: `localhost`) |
|
|
147
|
+
| `port` | `number` | No | Redis port (default: `6379`) |
|
|
148
|
+
|
|
149
|
+
Provide either `url` or `host`/`port`. If both are given, `url` takes precedence.
|
|
150
|
+
|
|
151
|
+
---
|
|
152
|
+
|
|
153
|
+
## Decorators
|
|
154
|
+
|
|
155
|
+
### `@Incoming(subject: string)`
|
|
156
|
+
|
|
157
|
+
Marks a method as a message handler. The module auto-discovers decorated methods at startup and subscribes them to the given subject.
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { Injectable } from '@nestjs/common';
|
|
161
|
+
import { Incoming } from '@lokative/messaging';
|
|
162
|
+
|
|
163
|
+
@Injectable()
|
|
164
|
+
export class OrderHandler {
|
|
165
|
+
|
|
166
|
+
@Incoming('order.created')
|
|
167
|
+
async handleOrderCreated(data: any) {
|
|
168
|
+
console.log('New order:', data);
|
|
169
|
+
// Auto-acked on success, nak'd on thrown error
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### `@Outgoing(subject: string)`
|
|
176
|
+
|
|
177
|
+
Wraps a method so its return value is automatically published to the given subject. The decorated class must have a `publisher` property (typically injected).
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
import { Injectable } from '@nestjs/common';
|
|
181
|
+
import { Outgoing, MessagingPublisher } from '@lokative/messaging';
|
|
182
|
+
|
|
183
|
+
@Injectable()
|
|
184
|
+
export class OrderService {
|
|
185
|
+
|
|
186
|
+
constructor(public publisher: MessagingPublisher) {}
|
|
187
|
+
|
|
188
|
+
@Outgoing('order.confirmed')
|
|
189
|
+
async confirmOrder(orderId: string) {
|
|
190
|
+
const order = await this.processConfirmation(orderId);
|
|
191
|
+
return order; // automatically published to 'order.confirmed'
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
---
|
|
198
|
+
|
|
199
|
+
## Publishing Messages
|
|
200
|
+
|
|
201
|
+
Inject `MessagingPublisher` to publish messages manually:
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
import { Injectable } from '@nestjs/common';
|
|
205
|
+
import { MessagingPublisher } from '@lokative/messaging';
|
|
206
|
+
|
|
207
|
+
@Injectable()
|
|
208
|
+
export class NotificationService {
|
|
209
|
+
|
|
210
|
+
constructor(private publisher: MessagingPublisher) {}
|
|
211
|
+
|
|
212
|
+
async notifyUser(userId: string, event: string) {
|
|
213
|
+
await this.publisher.publish('notification.send', {
|
|
214
|
+
userId,
|
|
215
|
+
event,
|
|
216
|
+
timestamp: Date.now(),
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
---
|
|
224
|
+
|
|
225
|
+
## Transport Comparison
|
|
226
|
+
|
|
227
|
+
| Feature | NATS JetStream | Kafka | Redis Pub/Sub |
|
|
228
|
+
| -------------------- | -------------------- | -------------------- | -------------------- |
|
|
229
|
+
| Message persistence | Yes (streams) | Yes (log) | No |
|
|
230
|
+
| Consumer groups | Yes (durable) | Yes (group id) | No |
|
|
231
|
+
| Ack/Nak | Yes | Auto-commit | N/A |
|
|
232
|
+
| Ordering | Per-subject | Per-partition | Per-channel |
|
|
233
|
+
| Best for | Microservices, CQRS | Event streaming, ETL | Real-time, fire-and-forget |
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
|
|
237
|
+
## Custom Transports
|
|
238
|
+
|
|
239
|
+
Implement the `MessagingTransport` interface to add support for any broker:
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
import { Injectable, Inject } from '@nestjs/common';
|
|
243
|
+
import type {
|
|
244
|
+
MessagingTransport,
|
|
245
|
+
MessageEnvelope,
|
|
246
|
+
Subscription,
|
|
247
|
+
SubscribeOptions,
|
|
248
|
+
MessagingConfig,
|
|
249
|
+
} from '@lokative/messaging';
|
|
250
|
+
|
|
251
|
+
@Injectable()
|
|
252
|
+
export class MyCustomTransport implements MessagingTransport {
|
|
253
|
+
|
|
254
|
+
constructor(@Inject('MSG_CONFIG') private config: MessagingConfig) {}
|
|
255
|
+
|
|
256
|
+
async connect(): Promise<void> {
|
|
257
|
+
// establish connection using this.config.transportOptions
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async publish(subject: string, payload: any): Promise<void> {
|
|
261
|
+
// publish serialized payload to subject/topic
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async subscribe(subject: string, options?: SubscribeOptions): Promise<Subscription> {
|
|
265
|
+
// return an async-iterable of MessageEnvelope
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
Then register it:
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
MessagingModule.register({
|
|
275
|
+
transport: MyCustomTransport,
|
|
276
|
+
transportOptions: { /* ... */ },
|
|
277
|
+
})
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
### Interface Reference
|
|
281
|
+
|
|
282
|
+
```typescript
|
|
283
|
+
interface MessagingTransport {
|
|
284
|
+
connect(): Promise<void>;
|
|
285
|
+
publish(subject: string, payload: any): Promise<void>;
|
|
286
|
+
subscribe(subject: string, options?: SubscribeOptions): Promise<Subscription>;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
interface MessageEnvelope {
|
|
290
|
+
subject: string;
|
|
291
|
+
data: any;
|
|
292
|
+
ack(): void;
|
|
293
|
+
nak(): void;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
interface Subscription {
|
|
297
|
+
[Symbol.asyncIterator](): AsyncIterator<MessageEnvelope>;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
interface SubscribeOptions {
|
|
301
|
+
group?: string;
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Full Application Example
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
// app.module.ts
|
|
311
|
+
import { Module } from '@nestjs/common';
|
|
312
|
+
import { MessagingModule, NatsTransport } from '@lokative/messaging';
|
|
313
|
+
import { OrderModule } from './order/order.module';
|
|
314
|
+
|
|
315
|
+
@Module({
|
|
316
|
+
imports: [
|
|
317
|
+
MessagingModule.register({
|
|
318
|
+
transport: NatsTransport,
|
|
319
|
+
transportOptions: {
|
|
320
|
+
servers: ['nats://localhost:4222'],
|
|
321
|
+
},
|
|
322
|
+
streams: [
|
|
323
|
+
{ name: 'ORDERS', subjects: ['order.*'] },
|
|
324
|
+
{ name: 'NOTIFICATIONS', subjects: ['notification.*'] },
|
|
325
|
+
],
|
|
326
|
+
consumers: { group: 'api-service' },
|
|
327
|
+
}),
|
|
328
|
+
OrderModule,
|
|
329
|
+
],
|
|
330
|
+
})
|
|
331
|
+
export class AppModule {}
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
```typescript
|
|
335
|
+
// order/order.module.ts
|
|
336
|
+
import { Module } from '@nestjs/common';
|
|
337
|
+
import { OrderService } from './order.service';
|
|
338
|
+
import { OrderHandler } from './order.handler';
|
|
339
|
+
|
|
340
|
+
@Module({
|
|
341
|
+
providers: [OrderService, OrderHandler],
|
|
342
|
+
exports: [OrderService],
|
|
343
|
+
})
|
|
344
|
+
export class OrderModule {}
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
```typescript
|
|
348
|
+
// order/order.service.ts
|
|
349
|
+
import { Injectable } from '@nestjs/common';
|
|
350
|
+
import { MessagingPublisher, Outgoing } from '@lokative/messaging';
|
|
351
|
+
|
|
352
|
+
@Injectable()
|
|
353
|
+
export class OrderService {
|
|
354
|
+
|
|
355
|
+
constructor(public publisher: MessagingPublisher) {}
|
|
356
|
+
|
|
357
|
+
@Outgoing('order.created')
|
|
358
|
+
async createOrder(dto: any) {
|
|
359
|
+
return { id: '123', ...dto, status: 'created' };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async cancelOrder(orderId: string) {
|
|
363
|
+
await this.publisher.publish('order.cancelled', { orderId });
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
}
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
```typescript
|
|
370
|
+
// order/order.handler.ts
|
|
371
|
+
import { Injectable } from '@nestjs/common';
|
|
372
|
+
import { Incoming } from '@lokative/messaging';
|
|
373
|
+
|
|
374
|
+
@Injectable()
|
|
375
|
+
export class OrderHandler {
|
|
376
|
+
|
|
377
|
+
@Incoming('order.created')
|
|
378
|
+
async onOrderCreated(data: any) {
|
|
379
|
+
console.log('Processing new order:', data.id);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
@Incoming('order.cancelled')
|
|
383
|
+
async onOrderCancelled(data: any) {
|
|
384
|
+
console.log('Order cancelled:', data.orderId);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
}
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
To switch this app to Kafka, change only the module registration:
|
|
391
|
+
|
|
392
|
+
```typescript
|
|
393
|
+
import { KafkaTransport } from '@lokative/messaging';
|
|
394
|
+
|
|
395
|
+
MessagingModule.register({
|
|
396
|
+
transport: KafkaTransport,
|
|
397
|
+
transportOptions: {
|
|
398
|
+
brokers: ['localhost:9092'],
|
|
399
|
+
clientId: 'api-service',
|
|
400
|
+
},
|
|
401
|
+
consumers: { group: 'api-service' },
|
|
402
|
+
})
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
Or to Redis:
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
import { RedisTransport } from '@lokative/messaging';
|
|
409
|
+
|
|
410
|
+
MessagingModule.register({
|
|
411
|
+
transport: RedisTransport,
|
|
412
|
+
transportOptions: { url: 'redis://localhost:6379' },
|
|
413
|
+
})
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
No changes needed in services or handlers.
|
|
417
|
+
|
|
418
|
+
---
|
|
419
|
+
|
|
420
|
+
## API Reference
|
|
421
|
+
|
|
422
|
+
### Exports
|
|
423
|
+
|
|
424
|
+
| Export | Type | Description |
|
|
425
|
+
| -------------------------- | ----------- | ---------------------------------------------- |
|
|
426
|
+
| `MessagingModule` | Module | NestJS dynamic module |
|
|
427
|
+
| `MessagingPublisher` | Injectable | Service for publishing messages |
|
|
428
|
+
| `MessagingConsumerRegistry`| Injectable | Auto-discovers and starts `@Incoming` handlers |
|
|
429
|
+
| `MessagingConfig` | Interface | Configuration shape for `register()` |
|
|
430
|
+
| `MessagingTransport` | Interface | Contract for custom transports |
|
|
431
|
+
| `MessageEnvelope` | Interface | Incoming message wrapper |
|
|
432
|
+
| `Subscription` | Interface | Async-iterable subscription |
|
|
433
|
+
| `SubscribeOptions` | Interface | Options passed to `subscribe()` |
|
|
434
|
+
| `MESSAGING_TRANSPORT` | Token | DI token for the transport provider |
|
|
435
|
+
| `NatsTransport` | Injectable | Built-in NATS JetStream transport |
|
|
436
|
+
| `NatsTransportOptions` | Interface | Options for `NatsTransport` |
|
|
437
|
+
| `KafkaTransport` | Injectable | Built-in Kafka transport |
|
|
438
|
+
| `KafkaTransportOptions` | Interface | Options for `KafkaTransport` |
|
|
439
|
+
| `RedisTransport` | Injectable | Built-in Redis Pub/Sub transport |
|
|
440
|
+
| `RedisTransportOptions` | Interface | Options for `RedisTransport` |
|
|
441
|
+
| `Incoming` | Decorator | Subscribe a method to a subject |
|
|
442
|
+
| `Outgoing` | Decorator | Auto-publish a method's return value |
|
|
443
|
+
|
|
444
|
+
### Injection
|
|
445
|
+
|
|
446
|
+
```typescript
|
|
447
|
+
// Inject the publisher
|
|
448
|
+
constructor(private publisher: MessagingPublisher) {}
|
|
449
|
+
|
|
450
|
+
// Inject the raw transport (advanced)
|
|
451
|
+
constructor(@Inject(MESSAGING_TRANSPORT) private transport: MessagingTransport) {}
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
---
|
|
455
|
+
|
|
456
|
+
## License
|
|
457
|
+
|
|
458
|
+
MIT — Made with care by [Lokative](https://lokative.com)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export { MessagingConfig } from './messaging.config';
|
|
2
|
+
export { MessagingTransport, MessageEnvelope, Subscription, SubscribeOptions, MESSAGING_TRANSPORT } from './transport.interface';
|
|
3
|
+
export { Incoming, Outgoing } from './messaging.decorator';
|
|
4
|
+
export { MessagingModule } from './messaging.module';
|
|
5
|
+
export { MessagingPublisher } from './messaging.publisher';
|
|
6
|
+
export { MessagingConsumerRegistry } from './messaging.registry';
|
|
7
|
+
export { NatsTransport, NatsTransportOptions } from './transports/nats.transport';
|
|
8
|
+
export { KafkaTransport, KafkaTransportOptions } from './transports/kafka.transport';
|
|
9
|
+
export { RedisTransport, RedisTransportOptions } from './transports/redis.transport';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { MESSAGING_TRANSPORT } from './transport.interface';
|
|
2
|
+
export { Incoming, Outgoing } from './messaging.decorator';
|
|
3
|
+
export { MessagingModule } from './messaging.module';
|
|
4
|
+
export { MessagingPublisher } from './messaging.publisher';
|
|
5
|
+
export { MessagingConsumerRegistry } from './messaging.registry';
|
|
6
|
+
export { NatsTransport } from './transports/nats.transport';
|
|
7
|
+
export { KafkaTransport } from './transports/kafka.transport';
|
|
8
|
+
export { RedisTransport } from './transports/redis.transport';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Type } from '@nestjs/common';
|
|
2
|
+
import type { MessagingTransport } from './transport.interface';
|
|
3
|
+
export interface MessagingConfig {
|
|
4
|
+
transport: Type<MessagingTransport>;
|
|
5
|
+
transportOptions?: Record<string, any>;
|
|
6
|
+
streams?: {
|
|
7
|
+
name: string;
|
|
8
|
+
subjects: string[];
|
|
9
|
+
}[];
|
|
10
|
+
consumers?: {
|
|
11
|
+
group?: string;
|
|
12
|
+
retry?: number;
|
|
13
|
+
dlq?: boolean;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function Incoming(subject) {
|
|
2
|
+
return (target, key) => {
|
|
3
|
+
Reflect.defineMetadata("msg:incoming", { subject }, target[key]);
|
|
4
|
+
};
|
|
5
|
+
}
|
|
6
|
+
export function Outgoing(subject) {
|
|
7
|
+
return (target, key, descriptor) => {
|
|
8
|
+
const original = descriptor.value;
|
|
9
|
+
descriptor.value = async function (...args) {
|
|
10
|
+
const result = await original.apply(this, args);
|
|
11
|
+
const publisher = this.publisher;
|
|
12
|
+
await publisher.publish(subject, result);
|
|
13
|
+
return result;
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var MessagingModule_1;
|
|
8
|
+
import { Module } from "@nestjs/common";
|
|
9
|
+
import { DiscoveryModule } from "@nestjs/core";
|
|
10
|
+
import { MESSAGING_TRANSPORT } from "./transport.interface";
|
|
11
|
+
import { MessagingPublisher } from "./messaging.publisher";
|
|
12
|
+
import { MessagingConsumerRegistry } from "./messaging.registry";
|
|
13
|
+
let MessagingModule = MessagingModule_1 = class MessagingModule {
|
|
14
|
+
static register(config) {
|
|
15
|
+
return {
|
|
16
|
+
module: MessagingModule_1,
|
|
17
|
+
imports: [DiscoveryModule],
|
|
18
|
+
providers: [
|
|
19
|
+
{ provide: "MSG_CONFIG", useValue: config },
|
|
20
|
+
{ provide: MESSAGING_TRANSPORT, useClass: config.transport },
|
|
21
|
+
MessagingPublisher,
|
|
22
|
+
MessagingConsumerRegistry,
|
|
23
|
+
],
|
|
24
|
+
exports: [MessagingPublisher],
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
MessagingModule = MessagingModule_1 = __decorate([
|
|
29
|
+
Module({})
|
|
30
|
+
], MessagingModule);
|
|
31
|
+
export { MessagingModule };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
14
|
+
import { MESSAGING_TRANSPORT } from "./transport.interface";
|
|
15
|
+
let MessagingPublisher = class MessagingPublisher {
|
|
16
|
+
transport;
|
|
17
|
+
constructor(transport) {
|
|
18
|
+
this.transport = transport;
|
|
19
|
+
}
|
|
20
|
+
async publish(subject, payload) {
|
|
21
|
+
await this.transport.publish(subject, payload);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
MessagingPublisher = __decorate([
|
|
25
|
+
Injectable(),
|
|
26
|
+
__param(0, Inject(MESSAGING_TRANSPORT)),
|
|
27
|
+
__metadata("design:paramtypes", [Object])
|
|
28
|
+
], MessagingPublisher);
|
|
29
|
+
export { MessagingPublisher };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { OnModuleInit } from "@nestjs/common";
|
|
2
|
+
import { DiscoveryService } from "@nestjs/core/discovery";
|
|
3
|
+
import { MessagingTransport } from "./transport.interface";
|
|
4
|
+
import type { MessagingConfig } from "./messaging.config";
|
|
5
|
+
export declare class MessagingConsumerRegistry implements OnModuleInit {
|
|
6
|
+
private transport;
|
|
7
|
+
private discovery;
|
|
8
|
+
private config;
|
|
9
|
+
constructor(transport: MessagingTransport, discovery: DiscoveryService, config: MessagingConfig);
|
|
10
|
+
onModuleInit(): Promise<void>;
|
|
11
|
+
private startConsumer;
|
|
12
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from "@nestjs/common";
|
|
14
|
+
import { DiscoveryService } from "@nestjs/core/discovery";
|
|
15
|
+
import { MESSAGING_TRANSPORT } from "./transport.interface";
|
|
16
|
+
let MessagingConsumerRegistry = class MessagingConsumerRegistry {
|
|
17
|
+
transport;
|
|
18
|
+
discovery;
|
|
19
|
+
config;
|
|
20
|
+
constructor(transport, discovery, config) {
|
|
21
|
+
this.transport = transport;
|
|
22
|
+
this.discovery = discovery;
|
|
23
|
+
this.config = config;
|
|
24
|
+
}
|
|
25
|
+
async onModuleInit() {
|
|
26
|
+
await this.transport.connect();
|
|
27
|
+
const providers = this.discovery.getProviders();
|
|
28
|
+
for (const provider of providers) {
|
|
29
|
+
const instance = provider.instance;
|
|
30
|
+
if (!instance)
|
|
31
|
+
continue;
|
|
32
|
+
const proto = Object.getPrototypeOf(instance);
|
|
33
|
+
for (const key of Object.getOwnPropertyNames(proto)) {
|
|
34
|
+
const handler = instance[key];
|
|
35
|
+
if (typeof handler !== 'function')
|
|
36
|
+
continue;
|
|
37
|
+
const meta = Reflect.getMetadata("msg:incoming", handler);
|
|
38
|
+
if (!meta)
|
|
39
|
+
continue;
|
|
40
|
+
this.startConsumer(instance, handler, meta);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
async startConsumer(instance, handler, meta) {
|
|
45
|
+
const group = this.config.consumers?.group;
|
|
46
|
+
const sub = await this.transport.subscribe(meta.subject, { group });
|
|
47
|
+
for await (const msg of sub) {
|
|
48
|
+
try {
|
|
49
|
+
await handler.call(instance, msg.data);
|
|
50
|
+
msg.ack();
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
msg.nak();
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
MessagingConsumerRegistry = __decorate([
|
|
59
|
+
Injectable(),
|
|
60
|
+
__param(0, Inject(MESSAGING_TRANSPORT)),
|
|
61
|
+
__param(2, Inject("MSG_CONFIG")),
|
|
62
|
+
__metadata("design:paramtypes", [Object, DiscoveryService, Object])
|
|
63
|
+
], MessagingConsumerRegistry);
|
|
64
|
+
export { MessagingConsumerRegistry };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface MessageEnvelope {
|
|
2
|
+
subject: string;
|
|
3
|
+
data: any;
|
|
4
|
+
ack(): void;
|
|
5
|
+
nak(): void;
|
|
6
|
+
}
|
|
7
|
+
export interface Subscription {
|
|
8
|
+
[Symbol.asyncIterator](): AsyncIterator<MessageEnvelope>;
|
|
9
|
+
}
|
|
10
|
+
export interface MessagingTransport {
|
|
11
|
+
connect(): Promise<void>;
|
|
12
|
+
publish(subject: string, payload: any): Promise<void>;
|
|
13
|
+
subscribe(subject: string, options?: SubscribeOptions): Promise<Subscription>;
|
|
14
|
+
}
|
|
15
|
+
export interface SubscribeOptions {
|
|
16
|
+
group?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare const MESSAGING_TRANSPORT = "MESSAGING_TRANSPORT";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const MESSAGING_TRANSPORT = 'MESSAGING_TRANSPORT';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { MessagingTransport, Subscription, SubscribeOptions } from '../transport.interface';
|
|
2
|
+
import type { MessagingConfig } from '../messaging.config';
|
|
3
|
+
export interface KafkaTransportOptions {
|
|
4
|
+
brokers: string[];
|
|
5
|
+
clientId?: string;
|
|
6
|
+
}
|
|
7
|
+
export declare class KafkaTransport implements MessagingTransport {
|
|
8
|
+
private config;
|
|
9
|
+
private kafka;
|
|
10
|
+
private producer;
|
|
11
|
+
constructor(config: MessagingConfig);
|
|
12
|
+
connect(): Promise<void>;
|
|
13
|
+
publish(subject: string, payload: any): Promise<void>;
|
|
14
|
+
subscribe(subject: string, options?: SubscribeOptions): Promise<Subscription>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
+
import { Kafka } from 'kafkajs';
|
|
15
|
+
let KafkaTransport = class KafkaTransport {
|
|
16
|
+
config;
|
|
17
|
+
kafka;
|
|
18
|
+
producer;
|
|
19
|
+
constructor(config) {
|
|
20
|
+
this.config = config;
|
|
21
|
+
}
|
|
22
|
+
async connect() {
|
|
23
|
+
const opts = this.config.transportOptions;
|
|
24
|
+
this.kafka = new Kafka({
|
|
25
|
+
clientId: opts.clientId ?? 'nestjs-app',
|
|
26
|
+
brokers: opts.brokers,
|
|
27
|
+
});
|
|
28
|
+
this.producer = this.kafka.producer();
|
|
29
|
+
await this.producer.connect();
|
|
30
|
+
}
|
|
31
|
+
async publish(subject, payload) {
|
|
32
|
+
await this.producer.send({
|
|
33
|
+
topic: subject,
|
|
34
|
+
messages: [{ value: JSON.stringify(payload) }],
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async subscribe(subject, options) {
|
|
38
|
+
const consumer = this.kafka.consumer({
|
|
39
|
+
groupId: options?.group ?? 'nest-consumer',
|
|
40
|
+
});
|
|
41
|
+
await consumer.connect();
|
|
42
|
+
await consumer.subscribe({ topic: subject, fromBeginning: false });
|
|
43
|
+
const buffer = [];
|
|
44
|
+
let waiting = null;
|
|
45
|
+
await consumer.run({
|
|
46
|
+
eachMessage: async ({ topic, message }) => {
|
|
47
|
+
const envelope = {
|
|
48
|
+
subject: topic,
|
|
49
|
+
data: JSON.parse(message.value?.toString() ?? '{}'),
|
|
50
|
+
ack: () => { }, // kafkajs auto-commits offsets
|
|
51
|
+
nak: () => { },
|
|
52
|
+
};
|
|
53
|
+
if (waiting) {
|
|
54
|
+
const resolve = waiting;
|
|
55
|
+
waiting = null;
|
|
56
|
+
resolve({ done: false, value: envelope });
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
buffer.push(envelope);
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
const iterator = {
|
|
64
|
+
next() {
|
|
65
|
+
if (buffer.length > 0) {
|
|
66
|
+
return Promise.resolve({ done: false, value: buffer.shift() });
|
|
67
|
+
}
|
|
68
|
+
return new Promise(r => { waiting = r; });
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
return { [Symbol.asyncIterator]: () => iterator };
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
KafkaTransport = __decorate([
|
|
75
|
+
Injectable(),
|
|
76
|
+
__param(0, Inject('MSG_CONFIG')),
|
|
77
|
+
__metadata("design:paramtypes", [Object])
|
|
78
|
+
], KafkaTransport);
|
|
79
|
+
export { KafkaTransport };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { MessagingTransport, Subscription, SubscribeOptions } from '../transport.interface';
|
|
2
|
+
import type { MessagingConfig } from '../messaging.config';
|
|
3
|
+
export interface NatsTransportOptions {
|
|
4
|
+
servers: string[];
|
|
5
|
+
streams?: {
|
|
6
|
+
name: string;
|
|
7
|
+
subjects: string[];
|
|
8
|
+
}[];
|
|
9
|
+
}
|
|
10
|
+
export declare class NatsTransport implements MessagingTransport {
|
|
11
|
+
private config;
|
|
12
|
+
private nc;
|
|
13
|
+
private js;
|
|
14
|
+
private jsm;
|
|
15
|
+
constructor(config: MessagingConfig);
|
|
16
|
+
connect(): Promise<void>;
|
|
17
|
+
publish(subject: string, payload: any): Promise<void>;
|
|
18
|
+
subscribe(subject: string, options?: SubscribeOptions): Promise<Subscription>;
|
|
19
|
+
private ensureStreams;
|
|
20
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
+
import { connect, consumerOpts } from 'nats';
|
|
15
|
+
let NatsTransport = class NatsTransport {
|
|
16
|
+
config;
|
|
17
|
+
nc;
|
|
18
|
+
js;
|
|
19
|
+
jsm;
|
|
20
|
+
constructor(config) {
|
|
21
|
+
this.config = config;
|
|
22
|
+
}
|
|
23
|
+
async connect() {
|
|
24
|
+
const opts = this.config.transportOptions;
|
|
25
|
+
this.nc = await connect({ servers: opts.servers });
|
|
26
|
+
this.js = this.nc.jetstream();
|
|
27
|
+
this.jsm = await this.nc.jetstreamManager();
|
|
28
|
+
await this.ensureStreams(opts.streams ?? this.config.streams ?? []);
|
|
29
|
+
}
|
|
30
|
+
async publish(subject, payload) {
|
|
31
|
+
await this.js.publish(subject, Buffer.from(JSON.stringify(payload)));
|
|
32
|
+
}
|
|
33
|
+
async subscribe(subject, options) {
|
|
34
|
+
const durable = options?.group ?? 'nest-consumer';
|
|
35
|
+
const opts = consumerOpts();
|
|
36
|
+
opts.durable(durable);
|
|
37
|
+
opts.ackExplicit();
|
|
38
|
+
opts.deliverTo(durable);
|
|
39
|
+
const sub = await this.js.subscribe(subject, opts);
|
|
40
|
+
const iterator = {
|
|
41
|
+
async next() {
|
|
42
|
+
const result = await sub[Symbol.asyncIterator]().next();
|
|
43
|
+
if (result.done)
|
|
44
|
+
return { done: true, value: undefined };
|
|
45
|
+
const msg = result.value;
|
|
46
|
+
return {
|
|
47
|
+
done: false,
|
|
48
|
+
value: {
|
|
49
|
+
subject: msg.subject,
|
|
50
|
+
data: JSON.parse(msg.data.toString()),
|
|
51
|
+
ack: () => msg.ack(),
|
|
52
|
+
nak: () => msg.nak(),
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
return { [Symbol.asyncIterator]: () => iterator };
|
|
58
|
+
}
|
|
59
|
+
async ensureStreams(streams) {
|
|
60
|
+
for (const stream of streams) {
|
|
61
|
+
try {
|
|
62
|
+
const info = await this.jsm.streams.info(stream.name);
|
|
63
|
+
const existing = info.config.subjects ?? [];
|
|
64
|
+
const missing = stream.subjects.filter(s => !existing.includes(s));
|
|
65
|
+
if (missing.length > 0) {
|
|
66
|
+
info.config.subjects = [...existing, ...missing];
|
|
67
|
+
await this.jsm.streams.update(stream.name, info.config);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
try {
|
|
72
|
+
await this.jsm.streams.add({ name: stream.name, subjects: stream.subjects });
|
|
73
|
+
}
|
|
74
|
+
catch (addErr) {
|
|
75
|
+
if (addErr?.api_error?.err_code !== 10065)
|
|
76
|
+
throw addErr;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
NatsTransport = __decorate([
|
|
83
|
+
Injectable(),
|
|
84
|
+
__param(0, Inject('MSG_CONFIG')),
|
|
85
|
+
__metadata("design:paramtypes", [Object])
|
|
86
|
+
], NatsTransport);
|
|
87
|
+
export { NatsTransport };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { MessagingTransport, Subscription, SubscribeOptions } from '../transport.interface';
|
|
2
|
+
import type { MessagingConfig } from '../messaging.config';
|
|
3
|
+
export interface RedisTransportOptions {
|
|
4
|
+
url?: string;
|
|
5
|
+
host?: string;
|
|
6
|
+
port?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare class RedisTransport implements MessagingTransport {
|
|
9
|
+
private config;
|
|
10
|
+
private pub;
|
|
11
|
+
private sub;
|
|
12
|
+
constructor(config: MessagingConfig);
|
|
13
|
+
connect(): Promise<void>;
|
|
14
|
+
publish(subject: string, payload: any): Promise<void>;
|
|
15
|
+
subscribe(subject: string, _options?: SubscribeOptions): Promise<Subscription>;
|
|
16
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
11
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
|
+
};
|
|
13
|
+
import { Inject, Injectable } from '@nestjs/common';
|
|
14
|
+
import { createClient } from 'redis';
|
|
15
|
+
let RedisTransport = class RedisTransport {
|
|
16
|
+
config;
|
|
17
|
+
pub;
|
|
18
|
+
sub;
|
|
19
|
+
constructor(config) {
|
|
20
|
+
this.config = config;
|
|
21
|
+
}
|
|
22
|
+
async connect() {
|
|
23
|
+
const opts = this.config.transportOptions;
|
|
24
|
+
const url = opts.url ?? `redis://${opts.host ?? 'localhost'}:${opts.port ?? 6379}`;
|
|
25
|
+
this.pub = createClient({ url });
|
|
26
|
+
this.sub = this.pub.duplicate();
|
|
27
|
+
await this.pub.connect();
|
|
28
|
+
await this.sub.connect();
|
|
29
|
+
}
|
|
30
|
+
async publish(subject, payload) {
|
|
31
|
+
await this.pub.publish(subject, JSON.stringify(payload));
|
|
32
|
+
}
|
|
33
|
+
async subscribe(subject, _options) {
|
|
34
|
+
const buffer = [];
|
|
35
|
+
let waiting = null;
|
|
36
|
+
await this.sub.subscribe(subject, (message, channel) => {
|
|
37
|
+
const envelope = {
|
|
38
|
+
subject: channel,
|
|
39
|
+
data: JSON.parse(message),
|
|
40
|
+
ack: () => { }, // redis pub/sub has no ack mechanism
|
|
41
|
+
nak: () => { },
|
|
42
|
+
};
|
|
43
|
+
if (waiting) {
|
|
44
|
+
const resolve = waiting;
|
|
45
|
+
waiting = null;
|
|
46
|
+
resolve({ done: false, value: envelope });
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
buffer.push(envelope);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
const iterator = {
|
|
53
|
+
next() {
|
|
54
|
+
if (buffer.length > 0) {
|
|
55
|
+
return Promise.resolve({ done: false, value: buffer.shift() });
|
|
56
|
+
}
|
|
57
|
+
return new Promise(r => { waiting = r; });
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
return { [Symbol.asyncIterator]: () => iterator };
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
RedisTransport = __decorate([
|
|
64
|
+
Injectable(),
|
|
65
|
+
__param(0, Inject('MSG_CONFIG')),
|
|
66
|
+
__metadata("design:paramtypes", [Object])
|
|
67
|
+
], RedisTransport);
|
|
68
|
+
export { RedisTransport };
|
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@lokative/messaging",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsc",
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"prepublishOnly": "npm run build"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [],
|
|
23
|
+
"author": "",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"peerDependencies": {
|
|
26
|
+
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
|
27
|
+
"@nestjs/core": "^10.0.0 || ^11.0.0",
|
|
28
|
+
"nats": "^2.0.0",
|
|
29
|
+
"kafkajs": "^2.0.0",
|
|
30
|
+
"redis": "^4.0.0",
|
|
31
|
+
"reflect-metadata": "^0.1.13 || ^0.2.0"
|
|
32
|
+
},
|
|
33
|
+
"peerDependenciesMeta": {
|
|
34
|
+
"nats": {
|
|
35
|
+
"optional": true
|
|
36
|
+
},
|
|
37
|
+
"kafkajs": {
|
|
38
|
+
"optional": true
|
|
39
|
+
},
|
|
40
|
+
"redis": {
|
|
41
|
+
"optional": true
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@nestjs/common": "^11.0.0",
|
|
46
|
+
"@nestjs/core": "^11.0.0",
|
|
47
|
+
"@types/node": "^25.5.0",
|
|
48
|
+
"kafkajs": "^2.0.0",
|
|
49
|
+
"nats": "^2.0.0",
|
|
50
|
+
"redis": "^4.0.0",
|
|
51
|
+
"reflect-metadata": "^0.2.0",
|
|
52
|
+
"rxjs": "^7.0.0",
|
|
53
|
+
"typescript": "^5.7.0",
|
|
54
|
+
"vitest": "^3.0.0"
|
|
55
|
+
}
|
|
56
|
+
}
|