-
Notifications
You must be signed in to change notification settings - Fork 568
/
configuration.ts
95 lines (88 loc) 路 2.48 KB
/
configuration.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
import {
Configuration,
extractExpressLikeValue,
Init,
Inject,
MidwayConfigService,
MidwayDecoratorService,
WEB_ROUTER_PARAM_KEY,
} from '@midwayjs/core';
import * as session from '@midwayjs/express-session';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
import * as DefaultConfig from './config/config.default';
import { MidwayExpressFramework } from './framework';
@Configuration({
namespace: 'express',
imports: [session],
importConfigs: [
{
default: DefaultConfig,
},
],
})
export class ExpressConfiguration {
@Inject()
decoratorService: MidwayDecoratorService;
@Inject()
expressFramework: MidwayExpressFramework;
@Inject()
configService: MidwayConfigService;
@Init()
init() {
this.decoratorService.registerParameterHandler(
WEB_ROUTER_PARAM_KEY,
options => {
return extractExpressLikeValue(
options.metadata.type,
options.metadata.propertyData,
options.originParamType
)(options.originArgs[0], options.originArgs[1], options.originArgs[2]);
}
);
}
async onReady() {
const keys =
this.configService.getConfiguration('express.keys') ??
this.configService.getConfiguration('keys');
const cookieParserConfig =
this.configService.getConfiguration('cookieParser');
if (cookieParserConfig.enable) {
// add cookie parser middleware
this.expressFramework
.getMiddleware()
.insertFirst(
cookieParser(
cookieParserConfig.secret ?? keys,
cookieParserConfig.options
)
);
}
// add body parser
const bodyparserConfig = this.configService.getConfiguration('bodyParser');
if (bodyparserConfig.enable) {
// create application/json parser
if (bodyparserConfig.json.enable) {
this.expressFramework.useMiddleware(
bodyParser.json(bodyparserConfig.json)
);
}
if (bodyparserConfig.raw.enable) {
this.expressFramework.useMiddleware(
bodyParser.raw(bodyparserConfig.raw)
);
}
if (bodyparserConfig.text.enable) {
this.expressFramework.useMiddleware(
bodyParser.text(bodyparserConfig.text)
);
}
// create application/x-www-form-urlencoded parser
if (bodyparserConfig.urlencoded.enable) {
this.expressFramework.useMiddleware(
bodyParser.urlencoded(bodyparserConfig.urlencoded)
);
}
}
}
}