-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
61 lines (54 loc) · 1.77 KB
/
app.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
import compression from 'compression';
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import routes from './api/routes/index';
import config from './config';
import { AddressInfo } from 'net';
import ServiceResult from './domain/business/serviceResult';
import ServiceResultCodes from './domain/business/serviceResultCodes';
const app = express();
app.use(cors());
app.use(express.json());
app.use(compression());
if (!config.isProduction) {
// log all coming requests
app.use(function(req: Request, res: Response, next: NextFunction) {
console.log('request', req.url, req.method, req.body);
next();
});
}
// root page
app.get('/', function(req: Request, res: Response) {
res.send('nodejs-ts-api-boilerplate');
});
/**
* Register all routes in 'api/routes/*'
* All routes is defined in 'api/routes/index.ts'. This file is a auto generated file.
* You do not need to update manually. Just run this command > yarn run fixRoutes.
*
* Examples;
* /mobile/device/register
* /user/account/login
* /wall/post/list
*/
for (const route in routes) {
for (const subRoute in routes[route]) {
app.use('/' + route + '/' + subRoute, routes[route][subRoute]);
}
}
// Final error handler
app.use(function(err: any, req: Request, res: Response, next: NextFunction) {
console.log('Catch error', err);
if (err instanceof ServiceResult) {
return res.status(400).json(err);
}
res.status(500).json(ServiceResult.instance().errorResult(ServiceResultCodes.ServerError));
//next();
});
// start server on defined port in config
const server = app.listen(config.port, function() {
let address: AddressInfo = server.address() as AddressInfo;
let host = address.address;
let port = address.port;
console.log('Running on http://%s:%s', host, port);
});