UNPKG

1.9 kBJavaScriptView Raw
1const PORT = process.env.PORT || 5000;
2const HOST = process.env.HOST || 'localhost';
3
4const _ = require('lodash');
5const express = require('express');
6const http = require('http');
7const logger = require('morgan');
8const helmet = require('helmet');
9const cookieParser = require('cookie-parser');
10const bodyParser = require('body-parser');
11const methodOverride = require('method-override');
12const session = require('express-session');
13const RedisStore = require('connect-redis')(session);
14
15const AceApiServer = require('./index');
16
17const defaultConfig = require('./config.default');
18
19function 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
77module.exports = Serve;