@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
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import {
|
|
2
|
+
NatsModuleConfiguration,
|
|
3
|
+
NATS_MODULE_CONFIG,
|
|
4
|
+
NATS_CLIENT_SERVICE,
|
|
5
|
+
NATS_PUBSUB_SERVICE,
|
|
6
|
+
NATS_LOGGER,
|
|
7
|
+
NatsLogger,
|
|
8
|
+
NatsLogLevel,
|
|
9
|
+
} from '../interfaces';
|
|
10
|
+
import { NatsCallOptions } from '../decorators/nats-call.decorator';
|
|
11
|
+
import { NatsListenerOptions } from '../decorators/nats-listener.decorator';
|
|
12
|
+
import { NatsEmitOptions } from '../decorators/nats-emit.decorator';
|
|
13
|
+
|
|
14
|
+
describe('NatsModuleConfiguration Interface', () => {
|
|
15
|
+
it('should accept full configuration', () => {
|
|
16
|
+
const config: NatsModuleConfiguration = {
|
|
17
|
+
host: 'localhost',
|
|
18
|
+
port: 4222,
|
|
19
|
+
servers: ['nats://localhost:4222', 'nats://localhost:4223'],
|
|
20
|
+
name: 'test-service',
|
|
21
|
+
user: 'admin',
|
|
22
|
+
pass: 'password',
|
|
23
|
+
logging: true,
|
|
24
|
+
serviceName: 'test-queue',
|
|
25
|
+
maxReconnectAttempts: 10,
|
|
26
|
+
reconnectTimeWait: 1000,
|
|
27
|
+
timeout: 5000,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
expect(config.host).toBe('localhost');
|
|
31
|
+
expect(config.port).toBe(4222);
|
|
32
|
+
expect(config.servers).toHaveLength(2);
|
|
33
|
+
expect(config.name).toBe('test-service');
|
|
34
|
+
expect(config.user).toBe('admin');
|
|
35
|
+
expect(config.pass).toBe('password');
|
|
36
|
+
expect(config.logging).toBe(true);
|
|
37
|
+
expect(config.serviceName).toBe('test-queue');
|
|
38
|
+
expect(config.maxReconnectAttempts).toBe(10);
|
|
39
|
+
expect(config.reconnectTimeWait).toBe(1000);
|
|
40
|
+
expect(config.timeout).toBe(5000);
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('should accept minimal configuration', () => {
|
|
44
|
+
const config: NatsModuleConfiguration = {};
|
|
45
|
+
expect(config).toBeDefined();
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('should accept only servers array', () => {
|
|
49
|
+
const config: NatsModuleConfiguration = {
|
|
50
|
+
servers: ['nats://custom:5555'],
|
|
51
|
+
};
|
|
52
|
+
expect(config.servers).toEqual(['nats://custom:5555']);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('should accept host and port instead of servers', () => {
|
|
56
|
+
const config: NatsModuleConfiguration = {
|
|
57
|
+
host: 'custom-host',
|
|
58
|
+
port: 5555,
|
|
59
|
+
};
|
|
60
|
+
expect(config.host).toBe('custom-host');
|
|
61
|
+
expect(config.port).toBe(5555);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('should accept queue group via serviceName', () => {
|
|
65
|
+
const config: NatsModuleConfiguration = {
|
|
66
|
+
serviceName: 'wallet-service-queue',
|
|
67
|
+
};
|
|
68
|
+
expect(config.serviceName).toBe('wallet-service-queue');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('should accept logging option', () => {
|
|
72
|
+
const configEnabled: NatsModuleConfiguration = { logging: true };
|
|
73
|
+
const configDisabled: NatsModuleConfiguration = { logging: false };
|
|
74
|
+
|
|
75
|
+
expect(configEnabled.logging).toBe(true);
|
|
76
|
+
expect(configDisabled.logging).toBe(false);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('should accept maxReconnectAttempts', () => {
|
|
80
|
+
const config: NatsModuleConfiguration = {
|
|
81
|
+
maxReconnectAttempts: -1,
|
|
82
|
+
};
|
|
83
|
+
expect(config.maxReconnectAttempts).toBe(-1);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should accept reconnectTimeWait', () => {
|
|
87
|
+
const config: NatsModuleConfiguration = {
|
|
88
|
+
reconnectTimeWait: 2000,
|
|
89
|
+
};
|
|
90
|
+
expect(config.reconnectTimeWait).toBe(2000);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('should accept timeout', () => {
|
|
94
|
+
const config: NatsModuleConfiguration = {
|
|
95
|
+
timeout: 30000,
|
|
96
|
+
};
|
|
97
|
+
expect(config.timeout).toBe(30000);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
describe('NatsCallOptions Interface', () => {
|
|
102
|
+
it('should accept channel and timeout', () => {
|
|
103
|
+
const options: NatsCallOptions = {
|
|
104
|
+
channel: 'wallet.balance.get',
|
|
105
|
+
timeout: 5000,
|
|
106
|
+
};
|
|
107
|
+
expect(options.channel).toBe('wallet.balance.get');
|
|
108
|
+
expect(options.timeout).toBe(5000);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
it('should accept channel with queueGroup', () => {
|
|
112
|
+
const options: NatsCallOptions = {
|
|
113
|
+
channel: 'wallet.balance.get',
|
|
114
|
+
queueGroup: 'wallet-service',
|
|
115
|
+
};
|
|
116
|
+
expect(options.channel).toBe('wallet.balance.get');
|
|
117
|
+
expect(options.queueGroup).toBe('wallet-service');
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('should accept all options', () => {
|
|
121
|
+
const options: NatsCallOptions = {
|
|
122
|
+
channel: 'test.channel',
|
|
123
|
+
timeout: 10000,
|
|
124
|
+
queueGroup: 'test-queue',
|
|
125
|
+
};
|
|
126
|
+
expect(options.channel).toBe('test.channel');
|
|
127
|
+
expect(options.timeout).toBe(10000);
|
|
128
|
+
expect(options.queueGroup).toBe('test-queue');
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe('NatsListenerOptions Interface', () => {
|
|
133
|
+
it('should accept channel only', () => {
|
|
134
|
+
const options: NatsListenerOptions = {
|
|
135
|
+
channel: 'player.joined',
|
|
136
|
+
};
|
|
137
|
+
expect(options.channel).toBe('player.joined');
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('should accept channel with queueGroup', () => {
|
|
141
|
+
const options: NatsListenerOptions = {
|
|
142
|
+
channel: 'player.joined',
|
|
143
|
+
queueGroup: 'notification-service',
|
|
144
|
+
};
|
|
145
|
+
expect(options.channel).toBe('player.joined');
|
|
146
|
+
expect(options.queueGroup).toBe('notification-service');
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
describe('NatsEmitOptions Interface', () => {
|
|
151
|
+
it('should accept channel with fireAndForget true', () => {
|
|
152
|
+
const options: NatsEmitOptions = {
|
|
153
|
+
channel: 'wallet.balance.changed',
|
|
154
|
+
fireAndForget: true,
|
|
155
|
+
};
|
|
156
|
+
expect(options.channel).toBe('wallet.balance.changed');
|
|
157
|
+
expect(options.fireAndForget).toBe(true);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('should accept channel with fireAndForget false', () => {
|
|
161
|
+
const options: NatsEmitOptions = {
|
|
162
|
+
channel: 'wallet.balance.changed',
|
|
163
|
+
fireAndForget: false,
|
|
164
|
+
};
|
|
165
|
+
expect(options.channel).toBe('wallet.balance.changed');
|
|
166
|
+
expect(options.fireAndForget).toBe(false);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
describe('Token Exports', () => {
|
|
171
|
+
it('should export NATS_MODULE_CONFIG token', () => {
|
|
172
|
+
expect(NATS_MODULE_CONFIG).toBeDefined();
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('should export NATS_CLIENT_SERVICE token', () => {
|
|
176
|
+
expect(NATS_CLIENT_SERVICE).toBeDefined();
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('should export NATS_PUBSUB_SERVICE token', () => {
|
|
180
|
+
expect(NATS_PUBSUB_SERVICE).toBeDefined();
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('should export NATS_LOGGER token', () => {
|
|
184
|
+
expect(NATS_LOGGER).toBeDefined();
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
describe('NatsLogger Interface', () => {
|
|
189
|
+
it('should accept logger with all methods', () => {
|
|
190
|
+
const logger: NatsLogger = {
|
|
191
|
+
debug: (message: string, ...args: any[]) => {},
|
|
192
|
+
info: (message: string, ...args: any[]) => {},
|
|
193
|
+
warn: (message: string, ...args: any[]) => {},
|
|
194
|
+
error: (message: string, ...args: any[]) => {},
|
|
195
|
+
};
|
|
196
|
+
expect(logger.debug).toBeDefined();
|
|
197
|
+
expect(logger.info).toBeDefined();
|
|
198
|
+
expect(logger.warn).toBeDefined();
|
|
199
|
+
expect(logger.error).toBeDefined();
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
describe('NatsLogLevel Enum', () => {
|
|
204
|
+
it('should have correct log levels', () => {
|
|
205
|
+
expect(NatsLogLevel.Debug).toBe('debug');
|
|
206
|
+
expect(NatsLogLevel.Info).toBe('info');
|
|
207
|
+
expect(NatsLogLevel.Warn).toBe('warn');
|
|
208
|
+
expect(NatsLogLevel.Error).toBe('error');
|
|
209
|
+
});
|
|
210
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { InjectionToken } from '@rxdi/core';
|
|
2
|
+
import { NatsConnection } from 'nats';
|
|
3
|
+
import { NatsLogger } from './nats-logger';
|
|
4
|
+
|
|
5
|
+
export interface NatsModuleConfiguration {
|
|
6
|
+
host?: string;
|
|
7
|
+
port?: number;
|
|
8
|
+
user?: string;
|
|
9
|
+
pass?: string;
|
|
10
|
+
servers?: string[];
|
|
11
|
+
name?: string;
|
|
12
|
+
pedantic?: boolean;
|
|
13
|
+
maxReconnectAttempts?: number;
|
|
14
|
+
reconnectTimeWait?: number;
|
|
15
|
+
connectionTimeout?: number;
|
|
16
|
+
timeout?: number;
|
|
17
|
+
tls?: any;
|
|
18
|
+
maxPayload?: number;
|
|
19
|
+
logging?: boolean;
|
|
20
|
+
logger?: NatsLogger;
|
|
21
|
+
serviceName?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface ServiceDiscoveryOptions {
|
|
25
|
+
enabled?: boolean;
|
|
26
|
+
monitorInterval?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface NatsPubSubOptions {
|
|
30
|
+
triggerTransform?: (trigger: string) => string;
|
|
31
|
+
logger?: NatsLogger;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const NATS_MODULE_CONFIG = new InjectionToken<NatsModuleConfiguration>('nats-module-config-injection-token');
|
|
35
|
+
export const NATS_CLIENT_SERVICE = new InjectionToken<NatsClientInterface>('nats-client-service-injection-token');
|
|
36
|
+
export const NATS_PUBSUB_SERVICE = new InjectionToken<NatsPubSubInterface>('nats-pubsub-service-injection-token');
|
|
37
|
+
export const GRAPHQL_NATS_PUBSUB = new InjectionToken<boolean>('graphql-nats-pubsub-injection-token');
|
|
38
|
+
export const NATS_LOGGER = new InjectionToken<NatsLogger>('nats-logger-injection-token');
|
|
39
|
+
|
|
40
|
+
export interface NatsClientInterface {
|
|
41
|
+
connect(): Promise<void>;
|
|
42
|
+
publish(channel: string, data: any): Promise<void>;
|
|
43
|
+
subscribe(channel: string, callback: (msg: any) => void): Promise<number>;
|
|
44
|
+
unsubscribe(subId: number): void;
|
|
45
|
+
request(channel: string, data: any, timeout?: number): Promise<any>;
|
|
46
|
+
close(): void;
|
|
47
|
+
isReady(): boolean;
|
|
48
|
+
getClient(): NatsConnection | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface NatsPubSubInterface {
|
|
52
|
+
publish(trigger: string, payload: any): Promise<void>;
|
|
53
|
+
subscribe<T>(trigger: string, onMessage: (m: T) => Promise<void>): Promise<number>;
|
|
54
|
+
unsubscribe(subId: number): void;
|
|
55
|
+
asyncIterator<T>(triggers: string | string[]): AsyncIterator<T>;
|
|
56
|
+
asyncIterableIterator<T>(triggers: string | string[]): AsyncIterator<T>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export type Path = Array<string | number>;
|
|
60
|
+
export type Trigger = string | Path;
|
|
61
|
+
export type TriggerTransform = (trigger: Trigger) => string;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { Container, Service, Module } from '@rxdi/core';
|
|
2
|
+
import { NatsModule } from './nats.module';
|
|
3
|
+
import { NatsCall, NatsEmit, NatsListener } from './decorators';
|
|
4
|
+
import { ConsoleNatsLogger } from './interfaces/nats-logger';
|
|
5
|
+
|
|
6
|
+
@Service()
|
|
7
|
+
class TestServiceWithCall {
|
|
8
|
+
@NatsCall({ channel: 'test.call', timeout: 5000 })
|
|
9
|
+
async handleCall(data: { message: string }) {
|
|
10
|
+
return { received: true, data };
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
@Service()
|
|
15
|
+
class TestServiceWithEmit {
|
|
16
|
+
@NatsEmit({ channel: 'test.emit', fireAndForget: true })
|
|
17
|
+
async emitEvent(data: { event: string }) {
|
|
18
|
+
return { emitted: true, data };
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
@Service()
|
|
23
|
+
class TestServiceWithListener {
|
|
24
|
+
receivedMessages: any[] = [];
|
|
25
|
+
|
|
26
|
+
@NatsListener({ channel: 'test.listener' })
|
|
27
|
+
async handleListener(data: any) {
|
|
28
|
+
this.receivedMessages.push(data);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
@Module({
|
|
33
|
+
imports: [
|
|
34
|
+
NatsModule.forRoot({
|
|
35
|
+
servers: ['nats://localhost:4222'],
|
|
36
|
+
logging: false,
|
|
37
|
+
} as any),
|
|
38
|
+
],
|
|
39
|
+
services: [TestServiceWithCall, TestServiceWithEmit, TestServiceWithListener],
|
|
40
|
+
})
|
|
41
|
+
export class TestModule {}
|
|
42
|
+
|
|
43
|
+
describe('NatsCall Decorator', () => {
|
|
44
|
+
beforeAll(() => {
|
|
45
|
+
Container.get(TestModule);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('should register NatsCall decorated method', () => {
|
|
49
|
+
const service = Container.get(TestServiceWithCall);
|
|
50
|
+
expect(service).toBeDefined();
|
|
51
|
+
expect(typeof service.handleCall).toBe('function');
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('should call decorated method without root parameter', async () => {
|
|
55
|
+
const service = Container.get(TestServiceWithCall);
|
|
56
|
+
const result = await service.handleCall({ message: 'test' });
|
|
57
|
+
expect(result.received).toBe(true);
|
|
58
|
+
expect(result.data.message).toBe('test');
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
describe('NatsEmit Decorator', () => {
|
|
63
|
+
beforeAll(() => {
|
|
64
|
+
Container.get(TestModule);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should register NatsEmit decorated method', () => {
|
|
68
|
+
const service = Container.get(TestServiceWithEmit);
|
|
69
|
+
expect(service).toBeDefined();
|
|
70
|
+
expect(typeof service.emitEvent).toBe('function');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('should return result from emit method', async () => {
|
|
74
|
+
const service = Container.get(TestServiceWithEmit);
|
|
75
|
+
const result = await service.emitEvent({ event: 'test-event' });
|
|
76
|
+
expect(result.emitted).toBe(true);
|
|
77
|
+
expect(result.data.event).toBe('test-event');
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
describe('NatsListener Decorator', () => {
|
|
82
|
+
beforeAll(() => {
|
|
83
|
+
Container.get(TestModule);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('should register NatsListener decorated method', () => {
|
|
87
|
+
const service = Container.get(TestServiceWithListener);
|
|
88
|
+
expect(service).toBeDefined();
|
|
89
|
+
expect(typeof service.handleListener).toBe('function');
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('should store received messages', () => {
|
|
93
|
+
const service = Container.get(TestServiceWithListener);
|
|
94
|
+
expect(service.receivedMessages).toEqual([]);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { NatsLoggerService } from './services/nats-logger.service';
|
|
2
|
+
import { ConsoleNatsLogger } from './interfaces/nats-logger';
|
|
3
|
+
|
|
4
|
+
describe('ConsoleNatsLogger', () => {
|
|
5
|
+
it('should not log when disabled', () => {
|
|
6
|
+
const logger = new ConsoleNatsLogger(false);
|
|
7
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
8
|
+
|
|
9
|
+
logger.info('Test message');
|
|
10
|
+
expect(consoleSpy).not.toHaveBeenCalled();
|
|
11
|
+
|
|
12
|
+
consoleSpy.mockRestore();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it('should log when enabled', () => {
|
|
16
|
+
const logger = new ConsoleNatsLogger(true);
|
|
17
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
18
|
+
|
|
19
|
+
logger.info('Test message');
|
|
20
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [INFO] Test message');
|
|
21
|
+
|
|
22
|
+
consoleSpy.mockRestore();
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('should log debug messages', () => {
|
|
26
|
+
const logger = new ConsoleNatsLogger(true);
|
|
27
|
+
const consoleSpy = jest.spyOn(console, 'debug').mockImplementation();
|
|
28
|
+
|
|
29
|
+
logger.debug('Debug message');
|
|
30
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [DEBUG] Debug message');
|
|
31
|
+
|
|
32
|
+
consoleSpy.mockRestore();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('should log warn messages', () => {
|
|
36
|
+
const logger = new ConsoleNatsLogger(true);
|
|
37
|
+
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
|
|
38
|
+
|
|
39
|
+
logger.warn('Warn message');
|
|
40
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [WARN] Warn message');
|
|
41
|
+
|
|
42
|
+
consoleSpy.mockRestore();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('should log error messages', () => {
|
|
46
|
+
const logger = new ConsoleNatsLogger(true);
|
|
47
|
+
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
|
|
48
|
+
|
|
49
|
+
logger.error('Error message');
|
|
50
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [ERROR] Error message');
|
|
51
|
+
|
|
52
|
+
consoleSpy.mockRestore();
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
describe('NatsLoggerService', () => {
|
|
57
|
+
it('should not log when disabled', () => {
|
|
58
|
+
const logger = new NatsLoggerService(false);
|
|
59
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
60
|
+
|
|
61
|
+
logger.info('Test message');
|
|
62
|
+
expect(consoleSpy).not.toHaveBeenCalled();
|
|
63
|
+
|
|
64
|
+
consoleSpy.mockRestore();
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
it('should log when enabled', () => {
|
|
68
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
69
|
+
const logger = new NatsLoggerService(true, customLogger);
|
|
70
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
71
|
+
|
|
72
|
+
logger.info('Test message');
|
|
73
|
+
expect(consoleSpy).toHaveBeenCalled();
|
|
74
|
+
|
|
75
|
+
consoleSpy.mockRestore();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it('should not log if no logger provided and disabled', () => {
|
|
79
|
+
const logger = new NatsLoggerService(false);
|
|
80
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
81
|
+
|
|
82
|
+
logger.debug('Should not log');
|
|
83
|
+
expect(consoleSpy).not.toHaveBeenCalled();
|
|
84
|
+
|
|
85
|
+
consoleSpy.mockRestore();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('should setEnabled changes logging state', () => {
|
|
89
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
90
|
+
const logger = new NatsLoggerService(false, customLogger);
|
|
91
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
92
|
+
|
|
93
|
+
logger.info('Should not log');
|
|
94
|
+
expect(consoleSpy).not.toHaveBeenCalled();
|
|
95
|
+
|
|
96
|
+
logger.setEnabled(true);
|
|
97
|
+
logger.info('Should log now');
|
|
98
|
+
expect(consoleSpy).toHaveBeenCalled();
|
|
99
|
+
|
|
100
|
+
consoleSpy.mockRestore();
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it('should use default no-op logger when none provided and enabled', () => {
|
|
104
|
+
const logger = new NatsLoggerService(true);
|
|
105
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
106
|
+
|
|
107
|
+
logger.info('Should not throw');
|
|
108
|
+
expect(consoleSpy).not.toHaveBeenCalled();
|
|
109
|
+
|
|
110
|
+
consoleSpy.mockRestore();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('should pass through debug with args', () => {
|
|
114
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
115
|
+
const logger = new NatsLoggerService(true, customLogger);
|
|
116
|
+
const consoleSpy = jest.spyOn(console, 'debug').mockImplementation();
|
|
117
|
+
|
|
118
|
+
logger.debug('Debug message', { key: 'value' });
|
|
119
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [DEBUG] Debug message', { key: 'value' });
|
|
120
|
+
|
|
121
|
+
consoleSpy.mockRestore();
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('should pass through info with args', () => {
|
|
125
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
126
|
+
const logger = new NatsLoggerService(true, customLogger);
|
|
127
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
128
|
+
|
|
129
|
+
logger.info('Info message', 'arg1', 'arg2');
|
|
130
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [INFO] Info message', 'arg1', 'arg2');
|
|
131
|
+
|
|
132
|
+
consoleSpy.mockRestore();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('should pass through warn with args', () => {
|
|
136
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
137
|
+
const logger = new NatsLoggerService(true, customLogger);
|
|
138
|
+
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
|
|
139
|
+
|
|
140
|
+
logger.warn('Warn message', { error: 'details' });
|
|
141
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [WARN] Warn message', { error: 'details' });
|
|
142
|
+
|
|
143
|
+
consoleSpy.mockRestore();
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it('should pass through error with args', () => {
|
|
147
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
148
|
+
const logger = new NatsLoggerService(true, customLogger);
|
|
149
|
+
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
|
|
150
|
+
|
|
151
|
+
logger.error('Error message', new Error('oops'));
|
|
152
|
+
expect(consoleSpy).toHaveBeenCalledWith('[NATS] [ERROR] Error message', new Error('oops'));
|
|
153
|
+
|
|
154
|
+
consoleSpy.mockRestore();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('should setEnabled to false', () => {
|
|
158
|
+
const customLogger = new ConsoleNatsLogger(true);
|
|
159
|
+
const logger = new NatsLoggerService(true, customLogger);
|
|
160
|
+
const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
|
|
161
|
+
|
|
162
|
+
logger.info('Should log');
|
|
163
|
+
expect(consoleSpy).toHaveBeenCalled();
|
|
164
|
+
|
|
165
|
+
logger.setEnabled(false);
|
|
166
|
+
logger.info('Should not log');
|
|
167
|
+
expect(consoleSpy).toHaveBeenCalledTimes(1);
|
|
168
|
+
|
|
169
|
+
consoleSpy.mockRestore();
|
|
170
|
+
});
|
|
171
|
+
});
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { Module, ModuleWithServices, Injectable } from '@rxdi/core';
|
|
2
|
+
import {
|
|
3
|
+
NatsModuleConfiguration,
|
|
4
|
+
NATS_MODULE_CONFIG,
|
|
5
|
+
NATS_PUBSUB_SERVICE,
|
|
6
|
+
NATS_CLIENT_SERVICE,
|
|
7
|
+
NATS_LOGGER,
|
|
8
|
+
ServiceDiscoveryOptions,
|
|
9
|
+
} from './interfaces';
|
|
10
|
+
import { NatsClientService } from './services/nats-client.service';
|
|
11
|
+
import { NatsPubSubService } from './services/nats-pubsub.service';
|
|
12
|
+
import { ServiceDiscoveryService } from './services/service-discovery.service';
|
|
13
|
+
import { NatsListenerHost } from './services/nats-listener.host';
|
|
14
|
+
import { NatsLoggerService } from './services/nats-logger.service';
|
|
15
|
+
import { ConsoleNatsLogger, NatsLogger } from './interfaces/nats-logger';
|
|
16
|
+
|
|
17
|
+
@Injectable()
|
|
18
|
+
export class ConfiguredNatsLogger extends NatsLoggerService {
|
|
19
|
+
constructor(config: NatsModuleConfiguration) {
|
|
20
|
+
const logger = new ConsoleNatsLogger(config?.logging ?? false);
|
|
21
|
+
super(config?.logging ?? false, logger);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@Module()
|
|
26
|
+
export class NatsModule {
|
|
27
|
+
static forRoot(
|
|
28
|
+
config: NatsModuleConfiguration,
|
|
29
|
+
discovery?: ServiceDiscoveryOptions
|
|
30
|
+
): ModuleWithServices {
|
|
31
|
+
return {
|
|
32
|
+
module: NatsModule,
|
|
33
|
+
providers: [
|
|
34
|
+
{
|
|
35
|
+
provide: NATS_MODULE_CONFIG,
|
|
36
|
+
useValue: config,
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
provide: NATS_LOGGER,
|
|
40
|
+
useClass: ConfiguredNatsLogger,
|
|
41
|
+
},
|
|
42
|
+
NatsClientService,
|
|
43
|
+
{
|
|
44
|
+
provide: NATS_CLIENT_SERVICE,
|
|
45
|
+
useClass: NatsClientService,
|
|
46
|
+
},
|
|
47
|
+
NatsListenerHost,
|
|
48
|
+
{
|
|
49
|
+
provide: NATS_PUBSUB_SERVICE,
|
|
50
|
+
useClass: NatsPubSubService,
|
|
51
|
+
},
|
|
52
|
+
...(discovery?.enabled ? [ServiceDiscoveryService] : []),
|
|
53
|
+
],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
static forRootAsync(config: {
|
|
58
|
+
useFactory: () => NatsModuleConfiguration;
|
|
59
|
+
deps?: any[];
|
|
60
|
+
}): ModuleWithServices {
|
|
61
|
+
return {
|
|
62
|
+
module: NatsModule,
|
|
63
|
+
providers: [
|
|
64
|
+
{
|
|
65
|
+
provide: NATS_MODULE_CONFIG,
|
|
66
|
+
useFactory: config.useFactory,
|
|
67
|
+
deps: config.deps || [],
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
provide: NATS_LOGGER,
|
|
71
|
+
useClass: ConfiguredNatsLogger,
|
|
72
|
+
},
|
|
73
|
+
NatsClientService,
|
|
74
|
+
{
|
|
75
|
+
provide: NATS_CLIENT_SERVICE,
|
|
76
|
+
useClass: NatsClientService,
|
|
77
|
+
},
|
|
78
|
+
NatsListenerHost,
|
|
79
|
+
{
|
|
80
|
+
provide: NATS_PUBSUB_SERVICE,
|
|
81
|
+
useClass: NatsPubSubService,
|
|
82
|
+
},
|
|
83
|
+
],
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './nats-client.service';
|
|
2
|
+
export * from './nats-pubsub.class';
|
|
3
|
+
export * from './nats-pubsub.service';
|
|
4
|
+
export * from './pubsub-async-iterator';
|
|
5
|
+
export * from './service-discovery.service';
|
|
6
|
+
export * from './microservice-registry.service';
|
|
7
|
+
export * from './nats-listener.host';
|
|
8
|
+
export * from './nats-logger.service';
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { Service } from '@rxdi/core';
|
|
2
|
+
import { Observable, Subject } from 'rxjs';
|
|
3
|
+
import { NatsClientService } from './nats-client.service';
|
|
4
|
+
|
|
5
|
+
export interface MicroserviceEndpoint {
|
|
6
|
+
serviceName: string;
|
|
7
|
+
channel: string;
|
|
8
|
+
methods: string[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
@Service()
|
|
12
|
+
export class MicroserviceRegistry {
|
|
13
|
+
private endpoints: Map<string, MicroserviceEndpoint> = new Map();
|
|
14
|
+
private registryUpdate$ = new Subject<MicroserviceEndpoint[]>();
|
|
15
|
+
|
|
16
|
+
constructor(private natsClient: NatsClientService) {}
|
|
17
|
+
|
|
18
|
+
registerEndpoint(serviceName: string, channel: string, methods: string[]): void {
|
|
19
|
+
const endpoint: MicroserviceEndpoint = { serviceName, channel, methods };
|
|
20
|
+
this.endpoints.set(serviceName, endpoint);
|
|
21
|
+
this.registryUpdate$.next(this.getAllEndpoints());
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
unregisterEndpoint(serviceName: string): void {
|
|
25
|
+
this.endpoints.delete(serviceName);
|
|
26
|
+
this.registryUpdate$.next(this.getAllEndpoints());
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
getEndpoint(serviceName: string): MicroserviceEndpoint | undefined {
|
|
30
|
+
return this.endpoints.get(serviceName);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
getAllEndpoints(): MicroserviceEndpoint[] {
|
|
34
|
+
return Array.from(this.endpoints.values());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
getRegistryUpdates(): Observable<MicroserviceEndpoint[]> {
|
|
38
|
+
return this.registryUpdate$.asObservable();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async broadcastRegistration(serviceName: string, channel: string, methods: string[]): Promise<void> {
|
|
42
|
+
await this.natsClient.publish('microservice.registry.register', {
|
|
43
|
+
serviceName,
|
|
44
|
+
channel,
|
|
45
|
+
methods,
|
|
46
|
+
timestamp: Date.now(),
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async broadcastUnregistration(serviceName: string): Promise<void> {
|
|
51
|
+
await this.natsClient.publish('microservice.registry.unregister', {
|
|
52
|
+
serviceName,
|
|
53
|
+
timestamp: Date.now(),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
}
|