@rxdi/nats 0.7.240
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +395 -0
- package/jest-setup.ts +1 -0
- package/package.json +63 -0
- package/src/decorators/index.ts +3 -0
- package/src/decorators/nats-call.decorator.ts +42 -0
- package/src/decorators/nats-emit.decorator.ts +59 -0
- package/src/decorators/nats-listener.decorator.ts +37 -0
- package/src/index.ts +5 -0
- package/src/interfaces/index.ts +2 -0
- package/src/interfaces/nats-logger.ts +41 -0
- package/src/interfaces/nats-module.config.spec.ts +210 -0
- package/src/interfaces/nats-module.config.ts +61 -0
- package/src/nats-decorators.spec.ts +96 -0
- package/src/nats-logger.spec.ts +171 -0
- package/src/nats.module.ts +86 -0
- package/src/services/index.ts +8 -0
- package/src/services/microservice-registry.service.ts +56 -0
- package/src/services/nats-client.service.ts +187 -0
- package/src/services/nats-listener.host.ts +132 -0
- package/src/services/nats-logger.service.ts +46 -0
- package/src/services/nats-pubsub.class.ts +152 -0
- package/src/services/nats-pubsub.service.ts +95 -0
- package/src/services/pubsub-async-iterator.spec.ts +78 -0
- package/src/services/pubsub-async-iterator.ts +61 -0
- package/src/services/service-discovery.service.ts +57 -0
- package/tsconfig.json +26 -0
- package/tslint.json +6 -0
package/README.md
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
# @rxdi/nats
|
|
2
|
+
|
|
3
|
+
NATS messaging module for @rxdi/core framework with decorators for service-to-service communication.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
This module provides NATS integration with three main decorators:
|
|
8
|
+
|
|
9
|
+
- **`@NatsCall`** - Request/reply handler (subscribes to channel, called when NATS request arrives)
|
|
10
|
+
- **`@NatsEmit`** - Fire-and-forget event publishing (wraps method + publishes result)
|
|
11
|
+
- **`@NatsListener`** - Event subscription handler (subscribes to channel, called when NATS event arrives)
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @rxdi/nats
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { Module } from '@rxdi/core';
|
|
23
|
+
import { NatsModule } from '@rxdi/nats';
|
|
24
|
+
|
|
25
|
+
@Module({
|
|
26
|
+
imports: [
|
|
27
|
+
NatsModule.forRoot({
|
|
28
|
+
servers: ['nats://localhost:4222'],
|
|
29
|
+
name: 'my-service',
|
|
30
|
+
logging: true, // Enable debug logging
|
|
31
|
+
}),
|
|
32
|
+
],
|
|
33
|
+
})
|
|
34
|
+
export class AppModule {}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Configuration
|
|
38
|
+
|
|
39
|
+
### NatsModuleConfiguration
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
interface NatsModuleConfiguration {
|
|
43
|
+
host?: string; // NATS host (default: localhost)
|
|
44
|
+
port?: number; // NATS port (default: 4222)
|
|
45
|
+
servers?: string[]; // Array of NATS server URLs
|
|
46
|
+
name?: string; // Service name for NATS connection
|
|
47
|
+
user?: string; // NATS username
|
|
48
|
+
pass?: string; // NATS password
|
|
49
|
+
logging?: boolean; // Enable/disable logging (default: false)
|
|
50
|
+
logger?: NatsLogger; // Custom logger implementation
|
|
51
|
+
serviceName?: string; // Service name for queue groups
|
|
52
|
+
maxReconnectAttempts?: number;
|
|
53
|
+
reconnectTimeWait?: number;
|
|
54
|
+
timeout?: number;
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### Example with full configuration:
|
|
59
|
+
|
|
60
|
+
```typescript
|
|
61
|
+
NatsModule.forRoot({
|
|
62
|
+
servers: ['nats://nats-1:4222', 'nats://nats-2:4222'],
|
|
63
|
+
name: 'crash-game-backend',
|
|
64
|
+
logging: true,
|
|
65
|
+
maxReconnectAttempts: -1, // Infinite reconnect
|
|
66
|
+
})
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Decorators
|
|
70
|
+
|
|
71
|
+
### @NatsCall
|
|
72
|
+
|
|
73
|
+
**Purpose:** Request/reply handler - the decorated method is called when a NATS request arrives on the channel. The return value is sent as the reply.
|
|
74
|
+
|
|
75
|
+
**Important:** `@NatsCall` does NOT send NATS requests when you call the method. It sets up a subscription to handle incoming requests.
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import { Service } from '@rxdi/core';
|
|
79
|
+
import { NatsCall } from '@rxdi/nats';
|
|
80
|
+
|
|
81
|
+
@Service()
|
|
82
|
+
export class WalletService {
|
|
83
|
+
// This method is called when external NATS client sends request to 'wallet.balance.get'
|
|
84
|
+
@NatsCall({ channel: 'wallet.balance.get', timeout: 5000 })
|
|
85
|
+
async getBalance({ playerId }: { playerId: string }) {
|
|
86
|
+
return {
|
|
87
|
+
playerId,
|
|
88
|
+
balance: 1000,
|
|
89
|
+
currency: 'USD'
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
**Options:**
|
|
96
|
+
- `channel: string` - NATS subject to subscribe to
|
|
97
|
+
- `timeout?: number` - Request timeout in ms (default: 30000)
|
|
98
|
+
- `queueGroup?: string` - Queue group for scaling (default: undefined)
|
|
99
|
+
|
|
100
|
+
**How it works:**
|
|
101
|
+
1. Decorator subscribes to `wallet.balance.get` channel
|
|
102
|
+
2. When a NATS request arrives, the decorated method is called
|
|
103
|
+
3. The return value is automatically sent as the reply to the caller
|
|
104
|
+
|
|
105
|
+
### To send NATS requests from your code:
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
import { NatsClientService } from '@rxdi/nats';
|
|
109
|
+
|
|
110
|
+
@Controller()
|
|
111
|
+
export class WalletController {
|
|
112
|
+
constructor(private natsClient: NatsClientService) {}
|
|
113
|
+
|
|
114
|
+
async getBalance(playerId: string) {
|
|
115
|
+
// Use natsClient.request() to send requests
|
|
116
|
+
const result = await this.natsClient.request('wallet.balance.get', { playerId });
|
|
117
|
+
return result;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
### @NatsEmit
|
|
123
|
+
|
|
124
|
+
**Purpose:** Fire-and-forget event publishing - when you call the method, it executes and ALSO publishes the result to NATS.
|
|
125
|
+
|
|
126
|
+
```typescript
|
|
127
|
+
import { Service } from '@rxdi/core';
|
|
128
|
+
import { NatsEmit } from '@rxdi/nats';
|
|
129
|
+
|
|
130
|
+
@Service()
|
|
131
|
+
export class GameService {
|
|
132
|
+
// When called, it executes the method AND publishes to 'game.crash'
|
|
133
|
+
@NatsEmit({ channel: 'game.crash', fireAndForget: true })
|
|
134
|
+
async publishCrashEvent({ crashPoint, timestamp }: { crashPoint: number; timestamp: number }) {
|
|
135
|
+
console.log(`Publishing crash: ${crashPoint}`);
|
|
136
|
+
return { crashPoint, timestamp }; // This becomes the NATS payload
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Usage:
|
|
141
|
+
const result = await gameService.publishCrashEvent({ crashPoint: 2.5, timestamp: Date.now() });
|
|
142
|
+
// console output: "Publishing crash: 2.5"
|
|
143
|
+
// NATS publishes: { crashPoint: 2.5, timestamp: ... } to 'game.crash'
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
**Options:**
|
|
147
|
+
- `channel: string` - NATS subject to publish to
|
|
148
|
+
- `fireAndForget: boolean` - If true, returns method result; if false, returns `{ success: true, channel, data }`
|
|
149
|
+
|
|
150
|
+
**How it works:**
|
|
151
|
+
1. Call the decorated method
|
|
152
|
+
2. The method executes normally (you get the return value)
|
|
153
|
+
3. The return value (or args if no return) is published to the channel
|
|
154
|
+
|
|
155
|
+
### @NatsListener
|
|
156
|
+
|
|
157
|
+
**Purpose:** Event handler - subscribes to a channel. When a NATS message arrives, the decorated method is called. No reply is sent.
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import { Service } from '@rxdi/core';
|
|
161
|
+
import { NatsListener } from '@rxdi/nats';
|
|
162
|
+
|
|
163
|
+
@Service()
|
|
164
|
+
export class NotificationService {
|
|
165
|
+
// This is called when NATS message arrives on 'player.joined'
|
|
166
|
+
@NatsListener({ channel: 'player.joined', queueGroup: 'notifications' })
|
|
167
|
+
async onPlayerJoined({ playerId, tableId }: { playerId: string; tableId: string }) {
|
|
168
|
+
console.log(`Player ${playerId} joined table ${tableId}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
**Options:**
|
|
174
|
+
- `channel: string` - NATS subject to subscribe to
|
|
175
|
+
- `queueGroup?: string` - Queue group for scaling
|
|
176
|
+
|
|
177
|
+
**How it works:**
|
|
178
|
+
1. Decorator subscribes to `player.joined` channel
|
|
179
|
+
2. When a NATS message arrives, the decorated method is called with the payload
|
|
180
|
+
3. No reply is sent back to NATS
|
|
181
|
+
|
|
182
|
+
## Scaling with Queue Groups
|
|
183
|
+
|
|
184
|
+
When running multiple instances of your service, use queue groups to distribute messages:
|
|
185
|
+
|
|
186
|
+
```
|
|
187
|
+
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
|
188
|
+
│ Instance 1 │ │ Instance 2 │ │ Instance 3 │
|
|
189
|
+
│ @Listener │ │ @Listener │ │ @Listener │
|
|
190
|
+
│ queue: "svc" │ │ queue: "svc" │ │ queue: "svc" │
|
|
191
|
+
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
|
|
192
|
+
│ │ │
|
|
193
|
+
└────────────────────┼────────────────────┘
|
|
194
|
+
▼
|
|
195
|
+
┌───────────────┐
|
|
196
|
+
│ NATS │
|
|
197
|
+
│ Round Robin │
|
|
198
|
+
└───────────────┘
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
**Without queue group:** All instances receive every message (fan-out)
|
|
202
|
+
|
|
203
|
+
**With queue group:** Messages are distributed round-robin (load balancing)
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
// All instances use same queue group - only one instance receives each message
|
|
207
|
+
@NatsListener({ channel: 'game.crash', queueGroup: 'crash-handlers' })
|
|
208
|
+
async onGameCrash(data) { }
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## Logging
|
|
212
|
+
|
|
213
|
+
Logging is disabled by default. Enable it in module config:
|
|
214
|
+
|
|
215
|
+
```typescript
|
|
216
|
+
NatsModule.forRoot({
|
|
217
|
+
servers: ['nats://localhost:4222'],
|
|
218
|
+
logging: true,
|
|
219
|
+
})
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Log levels:
|
|
223
|
+
- `debug` - Subscription registration, message flow
|
|
224
|
+
- `info` - Connection status, handler setup
|
|
225
|
+
- `warn` - Connection issues, missing clients
|
|
226
|
+
- `error` - Handler errors, connection failures
|
|
227
|
+
|
|
228
|
+
### Custom Logger
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
import { NatsLogger, NatsLogLevel } from '@rxdi/nats';
|
|
232
|
+
|
|
233
|
+
class CustomLogger implements NatsLogger {
|
|
234
|
+
debug(message: string, ...args: any[]) {
|
|
235
|
+
console.debug(`[CUSTOM] ${message}`, ...args);
|
|
236
|
+
}
|
|
237
|
+
info(message: string, ...args: any[]) {
|
|
238
|
+
console.log(`[CUSTOM] ${message}`, ...args);
|
|
239
|
+
}
|
|
240
|
+
warn(message: string, ...args: any[]) {
|
|
241
|
+
console.warn(`[CUSTOM] ${message}`, ...args);
|
|
242
|
+
}
|
|
243
|
+
error(message: string, ...args: any[]) {
|
|
244
|
+
console.error(`[CUSTOM] ${message}`, ...args);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
NatsModule.forRoot({
|
|
249
|
+
servers: ['nats://localhost:4222'],
|
|
250
|
+
logger: new CustomLogger(),
|
|
251
|
+
})
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Complete Example
|
|
255
|
+
|
|
256
|
+
### Service Definition
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
// wallet.service.ts
|
|
260
|
+
import { Service } from '@rxdi/core';
|
|
261
|
+
import { NatsCall, NatsListener, NatsEmit } from '@rxdi/nats';
|
|
262
|
+
|
|
263
|
+
@Service()
|
|
264
|
+
export class WalletService {
|
|
265
|
+
// Handler for incoming NATS requests - returns balance
|
|
266
|
+
@NatsCall({ channel: 'wallet.balance.get', timeout: 5000, queueGroup: 'wallet-service' })
|
|
267
|
+
async getBalance({ playerId }: { playerId: string }) {
|
|
268
|
+
console.log(`Getting balance for player: ${playerId}`);
|
|
269
|
+
return {
|
|
270
|
+
playerId,
|
|
271
|
+
balance: Math.random() * 10000,
|
|
272
|
+
currency: 'USD'
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Handler for incoming NATS events - logs transactions
|
|
277
|
+
@NatsListener({ channel: 'wallet.transaction.created', queueGroup: 'wallet-service' })
|
|
278
|
+
async onTransactionCreated({ transactionId, amount }: { transactionId: string; amount: number }) {
|
|
279
|
+
console.log(`Transaction created: ${transactionId}`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Emits events when called - publishes balance changes
|
|
283
|
+
@NatsEmit({ channel: 'wallet.balance.changed', fireAndForget: true })
|
|
284
|
+
async notifyBalanceChange({ playerId, newBalance }: { playerId: string; newBalance: number }) {
|
|
285
|
+
console.log(`Balance changed for ${playerId}: ${newBalance}`);
|
|
286
|
+
return { playerId, newBalance, timestamp: Date.now() };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
### Controller with GraphQL Mutation
|
|
292
|
+
|
|
293
|
+
```typescript
|
|
294
|
+
// wallet.controller.ts
|
|
295
|
+
import { Controller, Query, Mutation, Type, GraphQLString, GraphQLFloat } from '@gapi/core';
|
|
296
|
+
import { WalletService } from './wallet.service';
|
|
297
|
+
import { NatsClientService } from '@rxdi/nats';
|
|
298
|
+
|
|
299
|
+
@Controller()
|
|
300
|
+
export class WalletController {
|
|
301
|
+
constructor(
|
|
302
|
+
private walletService: WalletService,
|
|
303
|
+
private natsClient: NatsClientService
|
|
304
|
+
) {}
|
|
305
|
+
|
|
306
|
+
// Send NATS request to get balance (external service handles it)
|
|
307
|
+
@Type(GraphQLString)
|
|
308
|
+
@Mutation()
|
|
309
|
+
async getPlayerBalance({ playerId }: { playerId: string }): Promise<string> {
|
|
310
|
+
const balance = await this.natsClient.request('wallet.balance.get', { playerId });
|
|
311
|
+
return JSON.stringify(balance);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Call notifyBalanceChange - it will execute and publish to NATS
|
|
315
|
+
@Type(GraphQLString)
|
|
316
|
+
@Mutation()
|
|
317
|
+
async triggerBalanceNotification({ playerId, amount }: { playerId: string; amount: number }): Promise<string> {
|
|
318
|
+
const result = await this.walletService.notifyBalanceChange({ playerId, newBalance: amount });
|
|
319
|
+
return JSON.stringify(result);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
## Architecture
|
|
325
|
+
|
|
326
|
+
```
|
|
327
|
+
┌─────────────────────────────────────────────────────────────────┐
|
|
328
|
+
│ NATS Server │
|
|
329
|
+
│ │
|
|
330
|
+
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
|
|
331
|
+
│ │ External │ │ External │ │ External │ │ External │ │
|
|
332
|
+
│ │ Client │ │ Client │ │ Client │ │ Client │ │
|
|
333
|
+
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │
|
|
334
|
+
│ │ │ │ │ │
|
|
335
|
+
│ └─────────────┼─────────────┼─────────────┘ │
|
|
336
|
+
│ ▼ │
|
|
337
|
+
│ ┌─────────────────────────────────────────────────────────┐ │
|
|
338
|
+
│ │ Your Service │ │
|
|
339
|
+
│ │ │ │
|
|
340
|
+
│ │ @NatsCall @NatsEmit @NatsListener │ │
|
|
341
|
+
│ │ (handler) (publisher) (subscriber) │ │
|
|
342
|
+
│ │ │ │
|
|
343
|
+
│ │ NatsClientService ◄───────── listens to requests │ │
|
|
344
|
+
│ └─────────────────────────────────────────────────────────┘ │
|
|
345
|
+
└─────────────────────────────────────────────────────────────────┘
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
## Token Exports
|
|
349
|
+
|
|
350
|
+
```typescript
|
|
351
|
+
import {
|
|
352
|
+
NATS_MODULE_CONFIG,
|
|
353
|
+
NATS_CLIENT_SERVICE,
|
|
354
|
+
NATS_PUBSUB_SERVICE,
|
|
355
|
+
NATS_LOGGER,
|
|
356
|
+
NatsLogger,
|
|
357
|
+
NatsModuleConfiguration,
|
|
358
|
+
} from '@rxdi/nats';
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
## Error Handling
|
|
362
|
+
|
|
363
|
+
```typescript
|
|
364
|
+
@NatsCall({ channel: 'wallet.create', timeout: 5000 })
|
|
365
|
+
async createWallet(params) {
|
|
366
|
+
try {
|
|
367
|
+
return await this.walletService.createWallet(params);
|
|
368
|
+
} catch (error) {
|
|
369
|
+
return { error: error.message }; // Errors are sent back as response
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
```
|
|
373
|
+
|
|
374
|
+
## Best Practices
|
|
375
|
+
|
|
376
|
+
1. **Use queue groups** for scalable services to prevent duplicate message processing
|
|
377
|
+
2. **Set appropriate timeouts** for `@NatsCall` based on expected processing time
|
|
378
|
+
3. **Enable logging** during development, disable in production
|
|
379
|
+
4. **Handle errors** in decorated methods to return meaningful error responses
|
|
380
|
+
5. **Use descriptive channel names** following `service.resource.action` pattern
|
|
381
|
+
|
|
382
|
+
## Channel Naming Convention
|
|
383
|
+
|
|
384
|
+
Recommended pattern: `domain.resource.action`
|
|
385
|
+
|
|
386
|
+
```
|
|
387
|
+
wallet.balance.get - Get balance (request/reply)
|
|
388
|
+
wallet.balance.updated - Balance changed (event)
|
|
389
|
+
game.crash.event - Game crashed (event)
|
|
390
|
+
player.joined - Player joined (event)
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
## License
|
|
394
|
+
|
|
395
|
+
MIT
|
package/jest-setup.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import 'jest';
|
package/package.json
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@rxdi/nats",
|
|
3
|
+
"version": "0.7.240",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "https://github.com/rxdi/nats"
|
|
7
|
+
},
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"module": "./dist/index.js",
|
|
11
|
+
"typings": "./dist/index.d.ts",
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "jest",
|
|
14
|
+
"build": "tsc",
|
|
15
|
+
"lint": "echo 'Lint skipped'"
|
|
16
|
+
},
|
|
17
|
+
"author": {
|
|
18
|
+
"name": "Kristian Tachev(Stradivario)",
|
|
19
|
+
"email": "kristiqn.tachev@gmail.com"
|
|
20
|
+
},
|
|
21
|
+
"keywords": [
|
|
22
|
+
"nats",
|
|
23
|
+
"messaging",
|
|
24
|
+
"microservices",
|
|
25
|
+
"gapi",
|
|
26
|
+
"node"
|
|
27
|
+
],
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"bugs": {
|
|
30
|
+
"url": "https://github.com/rxdi/nats/issues"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/rxdi/nats#readme",
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"nats": "^2.29.3"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@rxdi/core": "^0.7.239",
|
|
38
|
+
"@types/node": "^25.0.3",
|
|
39
|
+
"tslint": "^5.20.1",
|
|
40
|
+
"tslint-language-service": "^0.9.9",
|
|
41
|
+
"typescript": "^5.9.3"
|
|
42
|
+
},
|
|
43
|
+
"jest": {
|
|
44
|
+
"testEnvironment": "node",
|
|
45
|
+
"testPathIgnorePatterns": [
|
|
46
|
+
"/node_modules/"
|
|
47
|
+
],
|
|
48
|
+
"rootDir": "./",
|
|
49
|
+
"transform": {
|
|
50
|
+
"^.+\\.tsx?$": [
|
|
51
|
+
"ts-jest",
|
|
52
|
+
{
|
|
53
|
+
"useESM": true,
|
|
54
|
+
"diagnostics": false
|
|
55
|
+
}
|
|
56
|
+
]
|
|
57
|
+
},
|
|
58
|
+
"testRegex": "/src/.*\\.spec\\.(ts|tsx|js)$",
|
|
59
|
+
"moduleNameMapper": {
|
|
60
|
+
"^(\\.{1,2}/.*)\\.js$": "$1"
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { Container } from '@rxdi/core';
|
|
2
|
+
import { NatsClientService } from '../services/nats-client.service';
|
|
3
|
+
import { NatsListenerHost } from '../services/nats-listener.host';
|
|
4
|
+
import { NATS_LOGGER, NatsLogger } from '../interfaces';
|
|
5
|
+
import { NatsLoggerService } from '../services/nats-logger.service';
|
|
6
|
+
import { ConsoleNatsLogger } from '../interfaces/nats-logger';
|
|
7
|
+
|
|
8
|
+
export interface NatsCallOptions {
|
|
9
|
+
channel: string;
|
|
10
|
+
timeout?: number;
|
|
11
|
+
queueGroup?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function getLogger(): NatsLoggerService {
|
|
15
|
+
try {
|
|
16
|
+
return Container.get(NATS_LOGGER) as NatsLoggerService;
|
|
17
|
+
} catch {
|
|
18
|
+
const logger = new ConsoleNatsLogger(false);
|
|
19
|
+
return new NatsLoggerService(false, logger);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function NatsCall(options: NatsCallOptions): MethodDecorator {
|
|
24
|
+
return function (
|
|
25
|
+
target: Object,
|
|
26
|
+
propertyKey: string | symbol,
|
|
27
|
+
descriptor: TypedPropertyDescriptor<any>
|
|
28
|
+
) {
|
|
29
|
+
const methodName = String(propertyKey);
|
|
30
|
+
const classCtor = target.constructor;
|
|
31
|
+
|
|
32
|
+
NatsListenerHost.registerCall(classCtor, methodName, options.channel, options.timeout || 30000, options.queueGroup);
|
|
33
|
+
const logger = getLogger();
|
|
34
|
+
logger.debug(`[@NatsCall] Registered: ${classCtor.name}.${methodName} on ${options.channel}${options.queueGroup ? ` (queue: ${options.queueGroup})` : ''}`);
|
|
35
|
+
|
|
36
|
+
return descriptor;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function NatsCallHandler(channel: string, timeout?: number, queueGroup?: string) {
|
|
41
|
+
return NatsCall({ channel, timeout, queueGroup });
|
|
42
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Container } from '@rxdi/core';
|
|
2
|
+
import { NatsClientService } from '../services/nats-client.service';
|
|
3
|
+
import { NATS_LOGGER } from '../interfaces';
|
|
4
|
+
import { NatsLoggerService } from '../services/nats-logger.service';
|
|
5
|
+
import { ConsoleNatsLogger } from '../interfaces/nats-logger';
|
|
6
|
+
|
|
7
|
+
export interface NatsEmitOptions {
|
|
8
|
+
channel: string;
|
|
9
|
+
fireAndForget: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function getLogger(): NatsLoggerService {
|
|
13
|
+
try {
|
|
14
|
+
return Container.get(NATS_LOGGER) as NatsLoggerService;
|
|
15
|
+
} catch {
|
|
16
|
+
const logger = new ConsoleNatsLogger(false);
|
|
17
|
+
return new NatsLoggerService(false, logger);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function NatsEmit(options: NatsEmitOptions): MethodDecorator {
|
|
22
|
+
return function (
|
|
23
|
+
target: Object,
|
|
24
|
+
propertyKey: string | symbol,
|
|
25
|
+
descriptor: TypedPropertyDescriptor<any>
|
|
26
|
+
) {
|
|
27
|
+
const originalMethod = descriptor.value;
|
|
28
|
+
|
|
29
|
+
descriptor.value = async function (this: any, ...args: any[]) {
|
|
30
|
+
const result = await originalMethod.apply(this, args);
|
|
31
|
+
const emitData = result !== undefined ? result : args[0] || args[1] || args[2] || {};
|
|
32
|
+
|
|
33
|
+
const natsClient = Container.get(NatsClientService);
|
|
34
|
+
const logger = getLogger();
|
|
35
|
+
|
|
36
|
+
if (!natsClient.isReady()) {
|
|
37
|
+
if (options.fireAndForget) {
|
|
38
|
+
logger.warn(`[NatsEmit] NATS not ready, skipping emit to ${options.channel}`);
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
throw new Error('NATS client is not connected');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
await natsClient.publish(options.channel, emitData);
|
|
45
|
+
logger.debug(`[NatsEmit] Published to ${options.channel}:`, emitData);
|
|
46
|
+
|
|
47
|
+
if (!options.fireAndForget) {
|
|
48
|
+
return { success: true, channel: options.channel, data: result };
|
|
49
|
+
}
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
return descriptor;
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function NatsEmitHandler(channel: string) {
|
|
58
|
+
return NatsEmit({ channel, fireAndForget: true });
|
|
59
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Container } from '@rxdi/core';
|
|
2
|
+
import { NatsClientService } from '../services/nats-client.service';
|
|
3
|
+
import { NatsListenerHost } from '../services/nats-listener.host';
|
|
4
|
+
import { NATS_LOGGER } from '../interfaces';
|
|
5
|
+
import { NatsLoggerService } from '../services/nats-logger.service';
|
|
6
|
+
import { ConsoleNatsLogger } from '../interfaces/nats-logger';
|
|
7
|
+
|
|
8
|
+
export interface NatsListenerOptions {
|
|
9
|
+
channel: string;
|
|
10
|
+
queueGroup?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function getLogger(): NatsLoggerService {
|
|
14
|
+
try {
|
|
15
|
+
return Container.get(NATS_LOGGER) as NatsLoggerService;
|
|
16
|
+
} catch {
|
|
17
|
+
const logger = new ConsoleNatsLogger(false);
|
|
18
|
+
return new NatsLoggerService(false, logger);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function NatsListener(options: NatsListenerOptions): MethodDecorator {
|
|
23
|
+
return function (
|
|
24
|
+
target: Object,
|
|
25
|
+
propertyKey: string | symbol,
|
|
26
|
+
descriptor: TypedPropertyDescriptor<any>
|
|
27
|
+
) {
|
|
28
|
+
const methodName = String(propertyKey);
|
|
29
|
+
const classCtor = target.constructor;
|
|
30
|
+
|
|
31
|
+
NatsListenerHost.registerListener(classCtor, methodName, options.channel, options.queueGroup);
|
|
32
|
+
const logger = getLogger();
|
|
33
|
+
logger.debug(`[@NatsListener] Registered: ${classCtor.name}.${methodName} on ${options.channel}${options.queueGroup ? ` (queue: ${options.queueGroup})` : ''}`);
|
|
34
|
+
|
|
35
|
+
return descriptor;
|
|
36
|
+
};
|
|
37
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export enum NatsLogLevel {
|
|
2
|
+
Debug = 'debug',
|
|
3
|
+
Info = 'info',
|
|
4
|
+
Warn = 'warn',
|
|
5
|
+
Error = 'error',
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface NatsLogger {
|
|
9
|
+
debug(message: string, ...args: any[]): void;
|
|
10
|
+
info(message: string, ...args: any[]): void;
|
|
11
|
+
warn(message: string, ...args: any[]): void;
|
|
12
|
+
error(message: string, ...args: any[]): void;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class ConsoleNatsLogger implements NatsLogger {
|
|
16
|
+
constructor(private enabled: boolean = false) {}
|
|
17
|
+
|
|
18
|
+
debug(message: string, ...args: any[]): void {
|
|
19
|
+
if (this.enabled) {
|
|
20
|
+
console.debug(`[NATS] [DEBUG] ${message}`, ...args);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
info(message: string, ...args: any[]): void {
|
|
25
|
+
if (this.enabled) {
|
|
26
|
+
console.log(`[NATS] [INFO] ${message}`, ...args);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
warn(message: string, ...args: any[]): void {
|
|
31
|
+
if (this.enabled) {
|
|
32
|
+
console.warn(`[NATS] [WARN] ${message}`, ...args);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
error(message: string, ...args: any[]): void {
|
|
37
|
+
if (this.enabled) {
|
|
38
|
+
console.error(`[NATS] [ERROR] ${message}`, ...args);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|