-
-
Notifications
You must be signed in to change notification settings - Fork 7.8k
/
Copy pathrouter-response-controller.ts
166 lines (147 loc) · 4.2 KB
/
router-response-controller.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
162
163
164
165
166
import {
HttpServer,
HttpStatus,
Logger,
RequestMethod,
MessageEvent,
} from '@nestjs/common';
import { isObject } from '@nestjs/common/utils/shared.utils';
import { IncomingMessage } from 'http';
import { EMPTY, lastValueFrom, Observable, isObservable } from 'rxjs';
import { catchError, debounce, map } from 'rxjs/operators';
import {
AdditionalHeaders,
WritableHeaderStream,
SseStream,
} from './sse-stream';
export interface CustomHeader {
name: string;
value: string | (() => string);
}
export interface RedirectResponse {
url: string;
statusCode?: number;
}
export class RouterResponseController {
private readonly logger = new Logger(RouterResponseController.name);
constructor(private readonly applicationRef: HttpServer) {}
public async apply<TInput = any, TResponse = any>(
result: TInput,
response: TResponse,
httpStatusCode?: number,
) {
return this.applicationRef.reply(response, result, httpStatusCode);
}
public async redirect<TInput = any, TResponse = any>(
resultOrDeferred: TInput,
response: TResponse,
redirectResponse: RedirectResponse,
) {
const result = await this.transformToResult(resultOrDeferred);
const statusCode =
result && result.statusCode
? result.statusCode
: redirectResponse.statusCode
? redirectResponse.statusCode
: HttpStatus.FOUND;
const url = result && result.url ? result.url : redirectResponse.url;
this.applicationRef.redirect(response, statusCode, url);
}
public async render<TInput = unknown, TResponse = unknown>(
resultOrDeferred: TInput,
response: TResponse,
template: string,
) {
const result = await this.transformToResult(resultOrDeferred);
return this.applicationRef.render(response, template, result);
}
public async transformToResult(resultOrDeferred: any) {
if (isObservable(resultOrDeferred)) {
return lastValueFrom(resultOrDeferred);
}
return resultOrDeferred;
}
public getStatusByMethod(requestMethod: RequestMethod): number {
switch (requestMethod) {
case RequestMethod.POST:
return HttpStatus.CREATED;
default:
return HttpStatus.OK;
}
}
public setHeaders<TResponse = unknown>(
response: TResponse,
headers: CustomHeader[],
) {
headers.forEach(({ name, value }) =>
this.applicationRef.setHeader(
response,
name,
typeof value === 'function' ? value() : value,
),
);
}
public setStatus<TResponse = unknown>(
response: TResponse,
statusCode: number,
) {
this.applicationRef.status(response, statusCode);
}
public sse<
TInput extends Observable<unknown> = any,
TResponse extends WritableHeaderStream = any,
TRequest extends IncomingMessage = any,
>(
result: TInput,
response: TResponse,
request: TRequest,
options?: { additionalHeaders: AdditionalHeaders },
) {
// It's possible that we sent headers already so don't use a stream
if (response.writableEnded) {
return;
}
this.assertObservable(result);
const stream = new SseStream(request);
stream.pipe(response, options);
const subscription = result
.pipe(
map((message): MessageEvent => {
if (isObject(message)) {
return message as MessageEvent;
}
return { data: message as object | string };
}),
debounce(
message =>
new Promise<void>(resolve =>
stream.writeMessage(message, () => resolve()),
),
),
catchError(err => {
const data = err instanceof Error ? err.message : err;
stream.writeMessage({ type: 'error', data }, writeError => {
if (writeError) {
this.logger.error(writeError);
}
});
return EMPTY;
}),
)
.subscribe({
complete: () => {
response.end();
},
});
request.on('close', () => {
subscription.unsubscribe();
});
}
private assertObservable(value: any) {
if (!isObservable(value)) {
throw new ReferenceError(
'You must return an Observable stream to use Server-Sent Events (SSE).',
);
}
}
}