1 | const PORT = process.env.PORT || 5000;
|
2 | const HOST = process.env.HOST || 'localhost';
|
3 |
|
4 | const _ = require('lodash');
|
5 | const express = require('express');
|
6 | const http = require('http');
|
7 | const logger = require('morgan');
|
8 | const helmet = require('helmet');
|
9 | const cookieParser = require('cookie-parser');
|
10 | const bodyParser = require('body-parser');
|
11 | const methodOverride = require('method-override');
|
12 | const session = require('express-session');
|
13 | const RedisStore = require('connect-redis')(session);
|
14 |
|
15 | const AceApiServer = require('./index');
|
16 |
|
17 | const defaultConfig = require('./config.default');
|
18 |
|
19 | function Serve (customConfig = {}, listen = true) {
|
20 | const config = _.merge({}, defaultConfig, customConfig);
|
21 |
|
22 | const app = express();
|
23 |
|
24 | const sessionOptions = {
|
25 | secret: config.session.secret,
|
26 | resave: true,
|
27 | saveUninitialized: true,
|
28 | };
|
29 |
|
30 | if (config.redis.url || config.redis.host) {
|
31 | const redisOptions = {
|
32 | ttl: config.session.ttl,
|
33 | };
|
34 |
|
35 | if (config.redis.url) {
|
36 | redisOptions.url = config.redis.url;
|
37 | } else {
|
38 | redisOptions.host = config.redis.host;
|
39 | redisOptions.port = config.redis.port;
|
40 | redisOptions.password = config.redis.password;
|
41 | redisOptions.db = config.redis.db;
|
42 | }
|
43 |
|
44 | sessionOptions.store = new RedisStore(redisOptions);
|
45 | } else {
|
46 | sessionOptions.cookie = {
|
47 | maxAge: config.session.ttl,
|
48 | };
|
49 | }
|
50 |
|
51 | app.use(helmet());
|
52 | app.use(logger('tiny'));
|
53 | app.use(cookieParser());
|
54 | app.use(bodyParser.json({
|
55 | limit: '50mb',
|
56 | }));
|
57 | app.use(bodyParser.urlencoded({
|
58 | extended: true,
|
59 | limit: '50mb',
|
60 | }));
|
61 | app.use(methodOverride());
|
62 | app.use(session(sessionOptions));
|
63 |
|
64 | AceApiServer(app, config);
|
65 |
|
66 | if (listen) {
|
67 | const server = http.createServer(app);
|
68 | server.on('listening', () => {
|
69 | console.log(`listening: http://${HOST}:${PORT}`);
|
70 | });
|
71 | server.listen(PORT);
|
72 | }
|
73 |
|
74 | return app;
|
75 | }
|
76 |
|
77 | module.exports = Serve;
|