-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
client-proxy.ts
161 lines (146 loc) · 4.63 KB
/
client-proxy.ts
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util';
import { isNil } from '@nestjs/common/utils/shared.utils';
import {
ConnectableObservable,
defer,
fromEvent,
merge,
Observable,
Observer,
throwError as _throw,
} from 'rxjs';
import { map, mergeMap, publish, take } from 'rxjs/operators';
import { CONNECT_EVENT, ERROR_EVENT } from '../constants';
import { IncomingResponseDeserializer } from '../deserializers/incoming-response.deserializer';
import { InvalidMessageException } from '../errors/invalid-message.exception';
import {
ClientOptions,
KafkaOptions,
MqttOptions,
MsPattern,
NatsOptions,
PacketId,
ReadPacket,
RedisOptions,
RmqOptions,
TcpClientOptions,
WritePacket,
} from '../interfaces';
import { ProducerDeserializer } from '../interfaces/deserializer.interface';
import { ProducerSerializer } from '../interfaces/serializer.interface';
import { IdentitySerializer } from '../serializers/identity.serializer';
import { transformPatternToRoute } from '../utils';
export abstract class ClientProxy {
public abstract connect(): Promise<any>;
public abstract close(): any;
protected routingMap = new Map<string, Function>();
protected serializer: ProducerSerializer;
protected deserializer: ProducerDeserializer;
public send<TResult = any, TInput = any>(
pattern: any,
data: TInput,
): Observable<TResult> {
if (isNil(pattern) || isNil(data)) {
return _throw(new InvalidMessageException());
}
return defer(async () => this.connect()).pipe(
mergeMap(
() =>
new Observable((observer: Observer<TResult>) => {
const callback = this.createObserver(observer);
return this.publish({ pattern, data }, callback);
}),
),
);
}
public emit<TResult = any, TInput = any>(
pattern: any,
data: TInput,
): Observable<TResult> {
if (isNil(pattern) || isNil(data)) {
return _throw(new InvalidMessageException());
}
const source = defer(async () => this.connect()).pipe(
mergeMap(() => this.dispatchEvent({ pattern, data })),
publish(),
);
(source as ConnectableObservable<TResult>).connect();
return source;
}
protected abstract publish(
packet: ReadPacket,
callback: (packet: WritePacket) => void,
): Function;
protected abstract dispatchEvent<T = any>(packet: ReadPacket): Promise<T>;
protected createObserver<T>(
observer: Observer<T>,
): (packet: WritePacket) => void {
return ({ err, response, isDisposed }: WritePacket) => {
if (err) {
return observer.error(this.serializeError(err));
} else if (response !== undefined && isDisposed) {
observer.next(this.serializeResponse(response));
return observer.complete();
} else if (isDisposed) {
return observer.complete();
}
observer.next(this.serializeResponse(response));
};
}
protected serializeError(err: any): any {
return err;
}
protected serializeResponse(response: any): any {
return response;
}
protected assignPacketId(packet: ReadPacket): ReadPacket & PacketId {
const id = randomStringGenerator();
return Object.assign(packet, { id });
}
protected connect$(
instance: any,
errorEvent = ERROR_EVENT,
connectEvent = CONNECT_EVENT,
): Observable<any> {
const error$ = fromEvent(instance, errorEvent).pipe(
map((err: any) => {
throw err;
}),
);
const connect$ = fromEvent(instance, connectEvent);
return merge(error$, connect$).pipe(take(1));
}
protected getOptionsProp<
T extends ClientOptions['options'],
K extends keyof T
>(obj: T, prop: K, defaultValue: T[K] = undefined) {
return (obj && obj[prop]) || defaultValue;
}
protected normalizePattern(pattern: MsPattern): string {
return transformPatternToRoute(pattern);
}
protected initializeSerializer(options: ClientOptions['options']) {
this.serializer =
(options &&
(options as
| RedisOptions['options']
| NatsOptions['options']
| MqttOptions['options']
| TcpClientOptions['options']
| RmqOptions['options']
| KafkaOptions['options']).serializer) ||
new IdentitySerializer();
}
protected initializeDeserializer(options: ClientOptions['options']) {
this.deserializer =
(options &&
(options as
| RedisOptions['options']
| NatsOptions['options']
| MqttOptions['options']
| TcpClientOptions['options']
| RmqOptions['options']
| KafkaOptions['options']).deserializer) ||
new IncomingResponseDeserializer();
}
}