forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-nats.ts
More file actions
117 lines (103 loc) · 3.29 KB
/
Copy pathserver-nats.ts
File metadata and controls
117 lines (103 loc) · 3.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { isUndefined } from '@nestjs/common/utils/shared.utils';
import { Observable } from 'rxjs';
import {
CONNECT_EVENT,
ERROR_EVENT,
NATS_DEFAULT_URL,
NO_MESSAGE_HANDLER,
} from '../constants';
import { Client } from '../external/nats-client.interface';
import { CustomTransportStrategy, PacketId } from '../interfaces';
import {
MicroserviceOptions,
NatsOptions,
} from '../interfaces/microservice-configuration.interface';
import { ReadPacket } from '../interfaces/packet.interface';
import { Server } from './server';
let natsPackage: any = {};
export class ServerNats extends Server implements CustomTransportStrategy {
private readonly url: string;
private natsClient: Client;
constructor(private readonly options: MicroserviceOptions['options']) {
super();
this.url =
this.getOptionsProp<NatsOptions>(this.options, 'url') || NATS_DEFAULT_URL;
natsPackage = this.loadPackage('nats', ServerNats.name, () =>
require('nats'),
);
}
public listen(callback: () => void) {
this.natsClient = this.createNatsClient();
this.handleError(this.natsClient);
this.start(callback);
}
public start(callback?: () => void) {
this.bindEvents(this.natsClient);
this.natsClient.on(CONNECT_EVENT, callback);
}
public bindEvents(client: Client) {
const queue = this.getOptionsProp<NatsOptions>(this.options, 'queue');
const subscribe = queue
? (channel: string) =>
client.subscribe(
channel,
{ queue },
this.getMessageHandler(channel, client).bind(this),
)
: (channel: string) =>
client.subscribe(
channel,
this.getMessageHandler(channel, client).bind(this),
);
const registeredPatterns = [...this.messageHandlers.keys()];
registeredPatterns.forEach(channel => subscribe(channel));
}
public close() {
this.natsClient && this.natsClient.close();
this.natsClient = null;
}
public createNatsClient(): Client {
const options = this.options || ({} as NatsOptions);
return natsPackage.connect({
...options,
url: this.url,
json: true,
});
}
public getMessageHandler(channel: string, client: Client): Function {
return async (buffer: ReadPacket & PacketId, replyTo: string) =>
this.handleMessage(channel, buffer, client, replyTo);
}
public async handleMessage(
channel: string,
message: ReadPacket & Partial<PacketId>,
client: Client,
replyTo: string,
) {
if (isUndefined(message.id)) {
return this.handleEvent(channel, message);
}
const publish = this.getPublisher(client, replyTo, message.id);
const handler = this.getHandlerByPattern(channel);
if (!handler) {
const status = 'error';
return publish({ id: message.id, status, err: NO_MESSAGE_HANDLER });
}
const response$ = this.transformToObservable(
await handler(message.data),
) as Observable<any>;
response$ && this.send(response$, publish);
}
public getPublisher(publisher: Client, replyTo: string, id: string) {
return (response: any) =>
publisher.publish(
replyTo,
Object.assign(response, {
id,
}),
);
}
public handleError(stream: any) {
stream.on(ERROR_EVENT, (err: any) => this.logger.error(err));
}
}