33ead877
Nattapon Wongpaet
first code
|
1
2
3
|
require('app-module-path').addPath(__dirname);
const express = require('express');
const app = express();
|
6fc87409
sumatek
update structure
|
4
|
|
c84b1639
sumatek
update data struc...
|
5
6
|
//core
|
6fc87409
sumatek
update structure
|
7
8
9
10
11
12
|
var core = require('./utils/core');
// var stats = core.stats;
var log = core.log;
var constants = core.constants;
var conf = core.config;
core.init(app);
|
c84b1639
sumatek
update data struc...
|
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
|
//helper
const utils = require('utils/utils');
//setup help build message resBody
function logResponseBody(req, res, next) {
var oldWrite = res.write,
oldEnd = res.end;
var chunks = [];
res.write = function (chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function (chunk) {
var body = '';
if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
res["resBody"] = body ;
oldEnd.apply(res, arguments);
return ;
}
if (!(chunk instanceof String || typeof chunk === 'string' ) )
chunks.push(chunk);
try {
//console.dir(chunks);
body = chunks.length > 0? Buffer.concat(chunks).toString('utf8') :'';
} catch (error) {
logger.errorStack(error);
}
res["resBody"] = body ;
oldEnd.apply(res, arguments);
};
next();
}
app.use(logResponseBody);
// setup json body parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// Enable CORS
app.use(function (req, res, next) {
// add generated request-id to session
//req.session.reqId = req.id;
// Enable CORS
// res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
|
6fc87409
sumatek
update structure
|
74
|
|
49559b6c
sumatek
merge
|
75
|
// console.log(conf.get('redis.host'));
|
33ead877
Nattapon Wongpaet
first code
|
76
|
|
8349d210
sumatek
update unittest
|
77
78
79
|
utils.test(1,2);
|
33ead877
Nattapon Wongpaet
first code
|
80
81
82
83
|
// setup generate request-id middleware
const addRequestId = require('express-request-id')();
app.use(addRequestId);
|
33ead877
Nattapon Wongpaet
first code
|
84
85
|
// setup express-session with redis store
const session = require('express-session');
|
49559b6c
sumatek
merge
|
86
|
// const RedisStore = require('connect-redis')(session);
|
33ead877
Nattapon Wongpaet
first code
|
87
88
|
const uuidV4 = require('uuid/v4');
|
49559b6c
sumatek
merge
|
89
90
91
92
93
94
95
96
97
98
99
100
101
102
|
// app.use(session({
// genid: function(req) {
// return uuidV4(); // generates session id using UUID
// },
// store: new RedisStore({
// host: conf.get('redis.host'),
// port: conf.get('redis.port'),
// ttl: 180
// }),
// secret: 'dbc33e678f',
// saveUninitialized: true,
// resave: false,
// cookie: { maxAge: 3600000 }
// }));
|
33ead877
Nattapon Wongpaet
first code
|
103
|
|
33ead877
Nattapon Wongpaet
first code
|
104
105
106
107
|
// setup logger
// const logger = require('utils/request-logger');
// setup express request/response logger
|
0b6272e0
sumatek
update template
|
108
109
|
// const log4js = require('log4js');
// log4js.configure('./config/log4js_config.json');
|
33ead877
Nattapon Wongpaet
first code
|
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
|
// const log4jsLogger = log4js.getLogger('express-project');
// const fileTransport = logger.fileTransport;
// const expressWinston = require('winston-express-middleware');
// expressWinston.requestWhitelist.push('session');
// expressWinston.requestWhitelist.push('body');
// expressWinston.responseWhitelist.push('session');
// expressWinston.responseWhitelist.push('body');
// app.use(expressWinston.logger({
// transports: [fileTransport],
// meta: true, // optional: control whether you want to log the meta data about the request (default to true)
// msg: "phoenix-partner - :: ## {{req.uid}} - {{req.id}} ## HTTP {{req.method}} {{req.url}} ",
// //msg: "SID:[{{req.session.id}}] UID:[{{req.id}}] HTTP {{req.method}} {{req.url}} ", //request-body:{{JSON.stringify(req.body)}}", // -- response-body:{{JSON.stringify(res.body)}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
// expressFormat: false, // Use the default Express/morgan request formatting, with the same colors. Enabling this will override any msg and colorStatus if true. Will only output colors on transports with colorize set to true
// colorStatus: true, // Color the status code, using the Express/morgan color palette (default green, 3XX cyan, 4XX yellow, 5XX red). Will not be recognized if expressFormat is true
// ignoreRoute: function (req, res) { return false; }, // optional: allows to skip some log messages based on request and/or response,
// customLogger: log4jsLogger,
// filterOutList: ['dropdown', 'loggedin', 'query-table', 'query-last-package-number', '.png', '.woff', '.ttf', 'jquery.nanoscroller', 'favicon.ico'], // not log any messages that have one of these words
// noExportData: true, // remove resultData in case message has '/export'
// noHeader: true, // not log headers if true
// noBody: false // not log body if true
// }));
// setup passport
|
49559b6c
sumatek
merge
|
136
137
138
139
140
|
// const passport = require('utils/passport-func')();
// const flash = require('connect-flash');
// app.use(flash());
// app.use(passport.initialize());
// app.use(passport.session());
|
33ead877
Nattapon Wongpaet
first code
|
141
142
|
|
6fc87409
sumatek
update structure
|
143
|
|
33ead877
Nattapon Wongpaet
first code
|
144
|
|
c84b1639
sumatek
update data struc...
|
145
|
//check header
|
0b6272e0
sumatek
update template
|
146
147
148
149
150
151
152
|
app.use(function( req, res, next ) {
if(req.headers["x-user"] && req.headers["usertoken"])
next();
else
res.status(401).json({resultCode:40100,resultDescription:'Access denied'});
});
|
49559b6c
sumatek
merge
|
153
|
|
c84b1639
sumatek
update data struc...
|
154
|
//prepare incomming
|
0b6272e0
sumatek
update template
|
155
|
app.use( function( req, res, next ) {
|
5a3cfae2
sumatek
update log
|
156
|
log.startEC(req);
|
58b47ee8
Nattapon Wongpaet
update query mongodb
|
157
|
req = utils.findQueryString(req);
|
58b47ee8
Nattapon Wongpaet
update query mongodb
|
158
|
next();
|
49559b6c
sumatek
merge
|
159
160
|
});
|
33ead877
Nattapon Wongpaet
first code
|
161
162
|
// get BE api configs
const apiUrlPrefix = conf.get('apiUrlPrefix');
|
30fb6c36
sumatek
update fixbug post
|
163
|
|
49559b6c
sumatek
merge
|
164
165
166
|
let preference = require('./controllers/preference/index');
app.use(apiUrlPrefix+'/preference', preference);
|
c84b1639
sumatek
update data struc...
|
167
|
//prepare outgoing
|
0b6272e0
sumatek
update template
|
168
169
170
171
172
173
174
175
176
177
178
|
app.use( function( req, res, next ) {
if(req.res.resBody)
{
try{
log.logSummary(req,JSON.parse(req.res.resBody));
} catch(err) {
log.logSummary(req,req.res.resBody);
}
}else
{
|
5a3cfae2
sumatek
update log
|
179
180
181
182
183
184
185
186
|
var response = constants.RESPONSERESULT.UNKNOW;
log.startlog(req,cmd,'session','identity');
log.detailRequestFE(req);
stat.receiveUnknow();
log.addErrorSummary(req,"Unknow",req.method+"_"+"Unknow",result)
res.status(200).json(response);
log.logSummary(req,response);
|
0b6272e0
sumatek
update template
|
187
188
|
}
|
5a3cfae2
sumatek
update log
|
189
|
log.endEC(req,res);
|
0b6272e0
sumatek
update template
|
190
191
|
next();
} );
|
33ead877
Nattapon Wongpaet
first code
|
192
|
|
180aaa4d
sumatek
update unit test
|
193
194
195
|
|
33ead877
Nattapon Wongpaet
first code
|
196
|
// handle not found
|
0b6272e0
sumatek
update template
|
197
|
// app.all('*', function(req, res) {
|
33ead877
Nattapon Wongpaet
first code
|
198
|
|
0b6272e0
sumatek
update template
|
199
200
201
|
// var response = {resultCode: 40400,resultDescription: 'Data not found'};
// log.endEC(req,response);
// res.status(404).send(response);
|
33ead877
Nattapon Wongpaet
first code
|
202
|
|
0b6272e0
sumatek
update template
|
203
|
// });
|
33ead877
Nattapon Wongpaet
first code
|
204
205
206
207
208
209
210
211
212
213
214
215
216
217
|
// // handle errors
// app.use(function (err, req, res, next) {
// // we may use properties of the error object
// // here and next(err) appropriately, or if
// // we possibly recovered from the error, simply next().
// res.status(err.status || 500).send(err.message || err);
// });
// winston-express-middleware errorLogger makes sense AFTER the router.
// app.use(expressWinston.errorLogger({
// transports: [fileTransport]
// }));
|
30fb6c36
sumatek
update fixbug post
|
218
|
const appPort = conf.get('appPort');
|
33ead877
Nattapon Wongpaet
first code
|
219
|
app.listen(appPort, function () {
|
49559b6c
sumatek
merge
|
220
|
console.log(conf.get('appName')+' listening on port ' + appPort + '!');
|
33ead877
Nattapon Wongpaet
first code
|
221
|
});
|