-
Notifications
You must be signed in to change notification settings - Fork 9
/
server.js
96 lines (89 loc) · 2.56 KB
/
server.js
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
96
require('./config/default')();
const fs = require('fs');
const path = require('path');
const express = require('express');
const exphbs = require('express-handlebars');
const morgan = require('morgan');
const http = require('http');
const handlebarsHelpers = require('./helpers.js');
const apiRouter = require('./routes/api');
const appRouter = require('./routes/app');
const testApiRouter = require('./routes/testapi');
const rtmRouter = require('./routes/rtm');
const { spawn } = require('child_process');
const port = process.env.PORT;
const host = process.env.HOST;
/* eslint-disable-next-line */
const format =
':remote-addr - :remote-user [:date[clf]] ":method '
+ ':url HTTP/:http-version" :type :status :res[content-length] ":referrer" ":user-agent"';
morgan.format('full', format);
const app = express();
require('express-ws')(app);
app.use(express.static('public'));
app.use('/assets', express.static('node_modules'));
app.engine('.hbs', exphbs({ extname: '.hbs', helpers: handlebarsHelpers }));
app.set('view engine', '.hbs');
morgan.token('type', (req) => {
return req.headers['content-type'];
});
app.use(
morgan('dev', {
skip: (_, res) => {
return res.statusCode < 400 || res.statusCode === 404;
}
})
);
app.use(
morgan('full', {
stream: fs.createWriteStream(path.join('/tmp', 'access.log'), { flags: 'a' })
})
);
app.use((req, res, next) => {
const token = (req.body && req.body.token) || req.headers.Authorization;
req.token = token;
req.requestTime = Date.now();
next();
});
app.use('/', rtmRouter);
app.use('/', appRouter);
app.use('/api/db', testApiRouter);
app.use('/api', apiRouter);
function createUIServer({ httpPort, httpHost }) {
const server = http.createServer(app);
let serverPort = httpPort;
let serverHost = httpHost;
// eslint-disable-next-line global-require
require('express-ws')(app, server);
return {
start(env) {
if (env && typeof env === 'object') {
process.env = {
...process.env,
...env
};
serverPort = process.env.PORT;
serverHost = process.env.HOST;
}
return new Promise(resolve => {
server.listen(serverPort, serverHost, () => {
resolve(server);
});
});
},
close() {
server.close();
}
};
}
if (require.main === module) {
app.listen(port, host, () => {
if (fs.existsSync('bot.js')) {
spawn('npm', ['run', 'example:rtmbot:glitch']);
}
/* eslint-disable-next-line */
console.log(`Example app listening on port ${port}!`);
});
} else {
module.exports = createUIServer;
}