-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwirebot.js
82 lines (71 loc) · 2.43 KB
/
wirebot.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
require('dotenv').load()
const express = require('express')
const http = require('http')
const helmet = require('helmet')
const { NODE_ENV } = process.env
const isDevMode = NODE_ENV === 'development'
const isTestMode = NODE_ENV === 'test'
const slackIM = require('./modules/slack/interactive_messages')
const logger = require('./logs')
const {
httpRequestLoggingMiddleware,
setHeadersMiddleware,
verifySlackTokenMiddleware,
slackReportMiddleware,
botHomeMiddleware,
errorFourZeroFourMiddleware,
httpErrorMiddleware
} = require('./modules/middlewares')
const app = express()
const server = http.createServer(app)
const slackImMiddleware = slackIM.expressMiddleware()
const PORT = isDevMode ? 5000 : (process.env.PORT || 3000)
/**
* Event listener for HTTP server "listening" event.
*
* @param {Object} server the http server instance
*
* @returns {null} server process is continous here, so no returns
*/
function onListening (server) {
const addr = server.address()
const bind = typeof addr === 'string'
? `pipe ${addr}`
: `port ${addr.port}`
logger.info(`🚧 Wirebot is Listening on ${bind}`)
}
/**
* Event listener for HTTP server "error" event.
* @param {Error} error an error message
* @returns {null} error already logged exits process
*/
function onError (error) {
if (error.syscall !== 'listen') {
return logger.error(error.message)
}
switch (error.code) {
case 'EACCES':
logger.error('port requires elevated privileges')
return isTestMode || process.exit(1)
case 'EADDRINUSE':
logger.error('port is already in use')
return isTestMode || process.exit(1)
default:
return logger.error(error.message)
}
}
app.use(helmet())
app.use(express.urlencoded({ extended: false }))
app.use(httpRequestLoggingMiddleware)
app.options('*', setHeadersMiddleware)
app.get('/', botHomeMiddleware)
app.post('/slack/actions', verifySlackTokenMiddleware, slackImMiddleware)
app.post('/slack/report', verifySlackTokenMiddleware, slackReportMiddleware)
app.use(errorFourZeroFourMiddleware)
app.use(httpErrorMiddleware)
server.on('listening', onListening.bind(null, server)).on('error', onError)
// Only run this section if file is loaded directly (eg `node wirebot.js`)
// module loaded by something else eg. test or cyclic dependency
// Fixes error: "Trying to open unclosed connection."
if (require.main === module) server.listen(PORT)
module.exports = { app, server, onError, onListening, isDevMode }