-
-
Notifications
You must be signed in to change notification settings - Fork 281
/
PlatformHandler.ts
195 lines (159 loc) · 5.67 KB
/
PlatformHandler.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import {AnyToPromiseResponseTypes, AnyToPromiseStatus, catchAsyncError, isFunction, isStream} from "@tsed/core";
import {Inject, Injectable, Provider, ProviderScope} from "@tsed/di";
import {$log} from "@tsed/logger";
import {PlatformExceptions} from "@tsed/platform-exceptions";
import {PlatformParams, PlatformParamsCallback} from "@tsed/platform-params";
import {PlatformResponseFilter} from "@tsed/platform-response-filter";
import {
AlterEndpointHandlersArg,
PlatformHandlerMetadata,
PlatformHandlerType,
PlatformRouters,
useResponseHandler
} from "@tsed/platform-router";
import {JsonOperationRoute} from "@tsed/schema";
import {promisify} from "util";
import {AnyToPromiseWithCtx} from "../domain/AnyToPromiseWithCtx";
import {PlatformContext} from "../domain/PlatformContext";
import {setResponseHeaders} from "../utils/setResponseHeaders";
import {PlatformApplication} from "./PlatformApplication";
import {PlatformMiddlewaresChain} from "./PlatformMiddlewaresChain";
/**
* Platform Handler abstraction layer. Wrap original class method to a pure platform handler (Express, Koa, etc...).
* @platform
*/
@Injectable({
scope: ProviderScope.SINGLETON
})
export class PlatformHandler {
@Inject()
protected responseFilter: PlatformResponseFilter;
@Inject()
protected platformParams: PlatformParams;
@Inject()
protected platformExceptions: PlatformExceptions;
@Inject()
protected platformApplication: PlatformApplication;
@Inject()
protected platformMiddlewaresChain: PlatformMiddlewaresChain;
constructor(protected platformRouters: PlatformRouters) {
// configure the router module
platformRouters.hooks
.on("alterEndpointHandlers", (handlers: AlterEndpointHandlersArg, operationRoute: JsonOperationRoute) => {
handlers = this.platformMiddlewaresChain.get(handlers, operationRoute);
handlers.after.push(useResponseHandler(this.onFinish.bind(this)));
return handlers;
})
.on("alterHandler", (handlerMetadata: PlatformHandlerMetadata) => {
return this.platformApplication.adapter.mapHandler(this.createHandler(handlerMetadata), handlerMetadata);
});
}
createHandler(handlerMetadata: PlatformHandlerMetadata): any {
if (handlerMetadata.isInjectable()) {
const handler = this.platformParams.compileHandler(handlerMetadata);
return async ($ctx: PlatformContext) => {
$ctx.handlerMetadata = handlerMetadata;
await this.onRequest(handler, $ctx);
return this.next($ctx);
};
}
return handlerMetadata.handler;
}
/**
* @param provider
* @param propertyKey
*/
createCustomHandler(provider: Provider, propertyKey: string) {
const metadata = new PlatformHandlerMetadata({
provider,
type: PlatformHandlerType.CUSTOM,
propertyKey
});
const handler = this.platformParams.compileHandler(metadata.store);
return ($ctx: PlatformContext) => {
$ctx.handlerMetadata = metadata;
// @ts-ignore
return this.onRequest(handler, $ctx);
};
}
/**
* Send the response to the consumer.
* @protected
* @param $ctx
*/
async flush($ctx: PlatformContext) {
const {response} = $ctx;
if (!$ctx.isDone()) {
let data = await this.responseFilter.serialize($ctx.data, $ctx as any);
data = await this.responseFilter.transform(data, $ctx as any);
response.body(data);
}
}
/**
* @param $ctx
*/
next($ctx: PlatformContext) {
if (isStream($ctx.data) || $ctx.isDone()) {
return;
}
return $ctx.next && $ctx.error ? $ctx.next($ctx.error) : $ctx.next();
}
/**
* Call handler when a request his handle
*/
async onRequest(handler: PlatformParamsCallback, $ctx: PlatformContext): Promise<any> {
if ($ctx.isDone()) {
$log.error({
name: "HEADERS_SENT",
message: `An endpoint is called but the response is already send to the client. The call comes from the handler: ${$ctx.handlerMetadata.toString()}`
});
return;
}
if (($ctx.error instanceof Error && !$ctx.handlerMetadata.hasErrorParam) || ($ctx.handlerMetadata.hasErrorParam && !$ctx.error)) {
return;
}
try {
const {handlerMetadata} = $ctx;
if (handlerMetadata.type === PlatformHandlerType.CTX_FN) {
return await handler({$ctx});
}
const resolver = new AnyToPromiseWithCtx($ctx);
const {state, type, data, status, headers} = await resolver.call(handler);
// Note: restore previous handler metadata (for OIDC)
$ctx.handlerMetadata = handlerMetadata;
if (state === AnyToPromiseStatus.RESOLVED) {
if (status) {
$ctx.response.status(status);
}
if (headers) {
$ctx.response.setHeaders(headers);
}
if (data !== undefined) {
$ctx.data = data;
}
if (!$ctx.isDone()) {
$ctx.error = null;
// set headers each times that an endpoint is called
if (handlerMetadata.isEndpoint()) {
setResponseHeaders($ctx);
}
// call returned middleware
if (isFunction($ctx.data) && !isStream($ctx.data)) {
return promisify($ctx.data)($ctx.getRequest(), $ctx.getResponse());
}
if (type === AnyToPromiseResponseTypes.STREAM) {
return this.flush($ctx);
}
}
}
} catch (error) {
$ctx.error = error;
// TODO on v8, we have to use platformExceptions.catch directly. Error middleware won't be supported anymore
throw error;
}
}
async onFinish($ctx: PlatformContext) {
$ctx.error = await catchAsyncError(() => this.flush($ctx));
return $ctx.error && this.platformExceptions.catch($ctx.error, $ctx);
}
}