forked from nestjs/nest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
95 lines (85 loc) · 2.58 KB
/
Copy pathserver.ts
File metadata and controls
95 lines (85 loc) · 2.58 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
import { Logger } from '@nestjs/common/services/logger.service';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { isFunction, isString } from '@nestjs/common/utils/shared.utils';
import {
EMPTY as empty,
from as fromPromise,
Observable,
of,
Subscription,
} from 'rxjs';
import { catchError, finalize } from 'rxjs/operators';
import {
MessageHandler,
MicroserviceOptions,
ReadPacket,
WritePacket,
} from '../interfaces';
import { NO_EVENT_HANDLER } from './../constants';
export abstract class Server {
protected readonly messageHandlers = new Map<string, MessageHandler>();
protected readonly logger = new Logger(Server.name);
public addHandler(
pattern: any,
callback: MessageHandler,
isEventHandler = false,
) {
const key = isString(pattern) ? pattern : JSON.stringify(pattern);
callback.isEventHandler = isEventHandler;
this.messageHandlers.set(key, callback);
}
public getHandlers(): Map<string, MessageHandler> {
return this.messageHandlers;
}
public getHandlerByPattern(pattern: string): MessageHandler | null {
return this.messageHandlers.has(pattern)
? this.messageHandlers.get(pattern)
: null;
}
public send(
stream$: Observable<any>,
respond: (data: WritePacket) => void,
): Subscription {
return stream$
.pipe(
catchError((err: any) => {
respond({ err, response: null });
return empty;
}),
finalize(() => respond({ isDisposed: true })),
)
.subscribe((response: any) => respond({ err: null, response }));
}
public async handleEvent(pattern: string, packet: ReadPacket): Promise<any> {
const handler = this.getHandlerByPattern(pattern);
if (!handler) {
return this.logger.error(NO_EVENT_HANDLER);
}
await handler(packet.data);
}
public transformToObservable<T = any>(resultOrDeffered: any): Observable<T> {
if (resultOrDeffered instanceof Promise) {
return fromPromise(resultOrDeffered);
} else if (!(resultOrDeffered && isFunction(resultOrDeffered.subscribe))) {
return of(resultOrDeffered);
}
return resultOrDeffered;
}
public getOptionsProp<T extends { options?: any }>(
obj: MicroserviceOptions['options'],
prop: keyof T['options'],
defaultValue: any = undefined,
) {
return (obj && obj[prop as string]) || defaultValue;
}
protected handleError(error: string) {
this.logger.error(error);
}
protected loadPackage<T = any>(
name: string,
ctx: string,
loader?: Function,
): T {
return loadPackage(name, ctx, loader);
}
}