/
mod.ts
269 lines (223 loc) · 7.78 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
// -------------------------------------------------------------------------
// Main exports
// -------------------------------------------------------------------------
// Http errors
export * from './http-error/HttpError.ts';
export * from './http-error/InternalServerError.ts';
export * from './http-error/BadRequestError.ts';
export * from './http-error/ForbiddenError.ts';
export * from './http-error/NotAcceptableError.ts';
export * from './http-error/MethodNotAllowedError.ts';
export * from './http-error/NotFoundError.ts';
export * from './http-error/UnauthorizedError.ts';
// Renderer
export * from './renderer/content.ts';
export * from './renderer/view.ts';
// Decorators
export * from './decorator/Area.ts';
export * from './decorator/Controller.ts';
export * from './decorator/Get.ts';
export * from './decorator/Post.ts';
export * from './decorator/Patch.ts';
export * from './decorator/Put.ts';
export * from './decorator/Delete.ts';
// Action decorators
export * from './decorator/Cookie.ts';
export * from './decorator/QueryParam.ts';
export * from './decorator/Body.ts';
export * from './decorator/Req.ts';
export * from './decorator/Res.ts';
export * from './decorator/Param.ts';
// Http exports
export { Response, ServerRequest } from './package.ts';
// Standart middlwares
export { CorsBuilder } from './middlewares/cors-builder.ts';
// DI
export * from './injection/index.ts';
// Interfaces
export * from './models/view-render-config.ts';
import { MetadataArgsStorage } from './metadata/metadata.ts';
import { serve, Response, Server, ServerRequest } from './package.ts';
import { getAction, notFoundAction } from './route/get-action.ts';
import { getActionParams } from './route/get-action-params.ts';
import { container } from './injection/index.ts';
import { send } from './static/send.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 { MetaRoute } from './models/meta-route.ts';
export type ObjectKeyAny = {[key: string]: any};
const global: ObjectKeyAny = {};
export function getMetadataArgsStorage(): MetadataArgsStorage {
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;
}
export interface AppSettings {
areas: Function[];
middlewares?: Function[];
staticConfig?: StaticFilesConfig;
viewRenderConfig?: ViewRenderConfig;
}
export class App {
private classes: ObjectKeyAny[] = [];
private metadata: MetadataArgsStorage;
private routes: MetaRoute[] = [];
private staticConfig: StaticFilesConfig | undefined = undefined;
private viewRenderConfig: ViewRenderConfig | undefined = undefined;
constructor(settings: AppSettings) {
this.metadata = getMetadataArgsStorage();
this.registerAreas(this.metadata);
this.registerControllers(this.metadata.controllers);
if(settings){
this.useStatic(settings.staticConfig);
this.useViewRender(settings.viewRenderConfig)
}
}
async listen(address: string = '0.0.0.0:8000') {
const s: Server = serve(address);
console.log(`Server start in ${address}`);
for await (const req of s) {
try {
const res: Response = {};
res.headers = new Headers();
if (await this.getStaticFile(req, res)) {
await req.respond(res);
} else {
// Get middlewares in request
const middlewares = this.metadata.middlewares.filter(m =>
m.route.test(req.url)
);
// Resolve every pre middleware
for (const middleware of middlewares) {
await middleware.target.onPreRequest(req, res);
}
const action = getAction(this.routes, req.method, req.url);
if (action === null) {
req.respond(notFoundAction());
} else {
// Get arguments in this action
const args = await getActionParams(req, res, action);
// Get Action result
const result = await action.target[action.actionName](...args);
// Resolve every post middleware
for (const middleware of middlewares) {
await middleware.target.onPostRequest(req, result);
}
req.respond(result);
}
}
} catch (error) {
req.respond(Content(error, error.httpCode || 500));
}
}
}
public useStatic(config?: StaticFilesConfig) {
if(config && !this.staticConfig) {
this.staticConfig = config;
}
}
public useViewRender(config?: ViewRenderConfig) {
if(config && !this.viewRenderConfig) {
this.viewRenderConfig = config;
(global as any).viewRenderConfig = config;
}
}
public useCors(builder: CorsBuilder) {
this.metadata.middlewares.push({
type: 'middleware',
target: builder,
route: /\//
});
}
private addRoute(route: MetaRoute) {
this.routes.push(route);
}
// Add area to controllers
private registerAreas(metadata: MetadataArgsStorage) {
metadata.controllers.map(controller => {
if (controller.area == null) {
const area: any = metadata.areas.find(area => {
if(area.controllers) {
return !!area.controllers.find(
areaController => areaController === controller.target
);
}
return false;
});
controller.area = area;
}
return controller;
});
}
private registerControllers(controllers: any[] = []) {
// TODO: add two route Map (with route params / exact match)
// example: new Map(); key = route, value = object
controllers.forEach(controller => {
const actions = getMetadataArgsStorage().actions.filter(
action => action.target === controller.target
);
const params = getMetadataArgsStorage().params.filter(
param => param.target === controller.target
);
// TODO: if obj not in classes
// resolve from DI
const obj: ObjectKeyAny = container.resolve(controller.target);
this.classes.push(obj);
console.log(
`register Controller: `,
controller.target.name || controller.target.constructor.name
);
let areaRoute = ``;
if (controller.area.baseRoute) {
areaRoute = controller.area.baseRoute;
}
actions.forEach(action => {
const metaRoute: MetaRoute = {
route: `${areaRoute}${controller.route}${action.route}`,
target: obj,
action: action.method,
method: action.type,
params: params.filter(param => param.method === action.method)
};
console.log(`register route: `, metaRoute.route);
this.addRoute(metaRoute);
});
});
}
private async getStaticFile(req: ServerRequest, res: Response) {
if (this.staticConfig == null) {
return false;
}
let url = req.url;
if (this.staticConfig.baseRoute) {
const regexUrl = new RegExp(`^${this.staticConfig.baseRoute}`);
if (regexUrl.test(req.url)) {
url = req.url.replace(regexUrl, '/');
} else {
return false;
}
}
// TODO: use normal parsers
const host = "http://localhost"; // need for parse
const pathname = new URL(host+url).pathname;
try {
const filePath = await send(
{ request: req, response: res },
pathname,
this.staticConfig
);
return filePath ? true : false;
} catch (error) {
// TODO: exception
if (this.staticConfig.baseRoute) {
console.warn(error);
}
return null;
}
}
}