-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
mod.ts
346 lines (288 loc) · 9.83 KB
/
mod.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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import { MetadataArgsStorage } from "./metadata/metadata.ts";
import { serve, Server, HTTPOptions } from "./deps.ts";
import { getAction } from "./route/get-action.ts";
import { getActionParams } from "./route/get-action-params.ts";
import { StaticFilesConfig } from "./models/static-config.ts";
import { ViewRenderConfig } from "./models/view-render-config.ts";
import { CorsBuilder } from "./middlewares/cors-builder.ts";
import { Content } from "./renderer/content.ts";
import { RouteMetadata } from "./metadata/route.ts";
import { registerAreas } from "./utils/register-areas.ts";
import { registerControllers } from "./utils/register-controllers.ts";
import { getStaticFile } from "./utils/get-static-file.ts";
import { MiddlewareTarget } from "./models/middleware-target.ts";
import {
TransformConfigMap,
TransformConfig,
} from "./models/transform-config.ts";
import { HookMetadataArgs } from "./metadata/hook.ts";
import { Context } from "./models/context.ts";
import { notFoundAction } from "./renderer/not-found.ts";
import { AppSettings } from "./models/app-settings.ts";
import { getHooksForAction } from "./route/get-hooks.ts";
import { HookMethod } from "./models/hook.ts";
import { HttpError } from "./http-error/HttpError.ts";
import { container as defaultContainer } from "./injection/index.ts";
export type ObjectKeyAny = { [key: string]: any };
const global: ObjectKeyAny = {};
export function getMetadataArgsStorage<TState>(): MetadataArgsStorage<TState> {
if (!(global as any).routingControllersMetadataArgsStorage) {
(global as any).routingControllersMetadataArgsStorage =
new MetadataArgsStorage();
}
return (global as any).routingControllersMetadataArgsStorage;
}
export function getViewRenderConfig(): ViewRenderConfig {
return (global as any).viewRenderConfig;
}
// TODO(irustm): move to hooks function
/**
* Run hooks function and return true if response is immediately
*/
async function resolveHooks<TState, TPayload>(
context: Context<TState>,
actionName: HookMethod,
hooks?: HookMetadataArgs<TState, TPayload>[],
): Promise<boolean> {
const resolvedHooks = new Set<HookMetadataArgs<TState, TPayload>>();
if (hasHooks(hooks)) {
// @ts-ignore: Object is possibly 'undefined'.
for (const hook of hooks) {
const action: Function | undefined = (hook as any).instance[actionName];
if (action !== undefined) {
await (hook as any).instance[actionName](context, hook.payload);
if (context.response.isImmediately()) {
let reverseActionName: HookMethod = actionName === "onCatchAction"
? "onCatchAction"
: "onPostAction";
// run reverse resolved hooks
await runHooks(
context,
reverseActionName,
Array.from(resolvedHooks).reverse(),
);
await context.request.serverRequest.respond(
context.response.getMergedResult(),
);
return true;
}
}
resolvedHooks.add(hook);
}
}
return false;
}
function hasHooks<TState = any, TPayload = any>(
hooks?: HookMetadataArgs<TState, TPayload>[],
): boolean {
return hooks !== undefined && hooks.length > 0;
}
async function runHooks<TState, TPayload>(
context: Context<TState>,
actionName: HookMethod,
hooks: HookMetadataArgs<TState, TPayload>[],
) {
for (const hook of hooks) {
const action: Function | undefined = (hook as any).instance[actionName];
if (action !== undefined) {
await (hook as any).instance[actionName](context, hook.payload);
}
}
}
// TODO(irustm): move to hooks function
function hasHooksAction<TState, TPayload>(
actionName: string,
hooks?: HookMetadataArgs<TState, TPayload>[],
): boolean {
return !!(hooks &&
hooks.find((hook) => (hook as any).instance[actionName] !== undefined));
}
export class App<TState> {
private classes: ObjectKeyAny[] = [];
private readonly metadata: MetadataArgsStorage<TState>;
private routes: RouteMetadata[] = [];
private staticConfig: StaticFilesConfig | undefined = undefined;
private viewRenderConfig: ViewRenderConfig | undefined = undefined;
private transformConfigMap?: TransformConfigMap | undefined = undefined;
private globalErrorHandler?: (ctx: Context<TState>, error: Error) => void;
private server: Server | undefined = undefined;
constructor(settings: AppSettings) {
this.metadata = getMetadataArgsStorage();
this.metadata.container = settings.container || defaultContainer;
registerAreas(this.metadata);
registerControllers(
this.metadata.controllers,
this.classes,
(route) => this.routes.push(route),
settings.logging,
);
this.useStatic(settings.staticConfig);
this.useViewRender(settings.viewRenderConfig);
}
async listen(address: string | HTTPOptions = ":8000"): Promise<Server> {
const server: Server = serve(address);
this.server = server;
console.log("Server start in", address);
for await (const req of server) {
const context = new Context<TState>(req);
try {
// Get middlewares in request
const middlewares = this.metadata.middlewares.filter((m) =>
m.route.test(context.request.url)
);
// Resolve every pre middleware
for (const middleware of middlewares) {
await middleware.target.onPreRequest(context);
}
if (context.response.isImmediately()) {
req.respond(context.response.getRaw());
continue;
}
// try getting static file
if (
this.staticConfig && await getStaticFile(context, this.staticConfig)
) {
req.respond(context.response.getRaw());
continue;
}
const action = getAction(
this.routes,
context.request.method,
context.request.url,
);
if (action !== null) {
const hooks = getHooksForAction(this.metadata.hooks, action);
// try resolve hooks
if (
hasHooks(hooks) && await resolveHooks(context, "onPreAction", hooks)
) {
continue;
}
// Get arguments in this action
const args = await getActionParams(
context,
action,
this.transformConfigMap,
);
try {
// Get Action result from controller method
context.response.result = await action.target[action.action](
...args,
);
} catch (error) {
context.response.error = error;
// try resolve hooks
if (
hasHooks(hooks) &&
hasHooksAction("onCatchAction", hooks) &&
await resolveHooks(context, "onCatchAction", hooks)
) {
continue;
} else {
// Resolve every post middleware if error was not caught
for (const middleware of middlewares) {
await middleware.target.onPostRequest(context);
}
if (context.response.isImmediately()) {
req.respond(context.response.getMergedResult());
continue;
}
throw error;
}
}
// try resolve hooks
if (
hasHooks(hooks) &&
await resolveHooks(context, "onPostAction", hooks)
) {
continue;
}
}
if (context.response.isImmediately()) {
req.respond(context.response.getMergedResult());
continue;
}
// Resolve every post middleware
for (const middleware of middlewares) {
await middleware.target.onPostRequest(context);
}
if (context.response.isImmediately()) {
req.respond(context.response.getMergedResult());
continue;
}
if (context.response.result === undefined) {
context.response.result = notFoundAction();
req.respond(context.response.getMergedResult());
continue;
}
req.respond(context.response.getMergedResult());
} catch (error) {
if (this.globalErrorHandler) {
this.globalErrorHandler(context, error);
if (context.response.isImmediately()) {
req.respond(context.response.getMergedResult());
continue;
}
}
if (context.response.isImmediately()) {
req.respond(context.response.getMergedResult());
continue;
}
if (!(error instanceof HttpError)) {
console.error(error);
}
req.respond(Content(error, error.httpCode || 500));
}
}
return server;
}
public close(): void {
if (this.server) {
this.server.close();
} else {
console.warn("Server is not listening");
}
}
public useStatic(config?: StaticFilesConfig): void {
if (config && !this.staticConfig) {
this.staticConfig = config;
}
}
public useViewRender(config?: ViewRenderConfig): void {
if (config && !this.viewRenderConfig) {
this.viewRenderConfig = config;
(global as any).viewRenderConfig = config;
}
}
public useTransform(transform: TransformConfig): void {
if (!this.transformConfigMap) {
this.transformConfigMap = new Map();
}
this.transformConfigMap.set(transform.type, transform);
}
/**
* Deprecate
*/
public useCors(builder: CorsBuilder<TState>): void {
this.metadata.middlewares.push({
type: "middleware",
target: builder,
route: /\//,
});
}
public use(route: RegExp, middleware: MiddlewareTarget<TState>): void {
this.metadata.middlewares.push({
type: "middleware",
target: middleware,
route,
});
}
/**
* Create one global error handler
*/
public error(
globalErrorHandler: (ctx: Context<TState>, error: Error) => void,
): void {
this.globalErrorHandler = globalErrorHandler;
}
}