This repository has been archived by the owner on Sep 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
85 lines (73 loc) · 1.94 KB
/
index.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
import http from 'http'
import finalhandler from 'finalhandler'
import Router from 'router'
import _ from 'lodash-fp'
import body from 'body/form'
import debug from 'debug'
var error = debug('ephembot:index')
var log = debug('ephembot:index')
// Make logs go to stdout instead of stderr
log.log = console.log.bind(console)
function parseBody (req, res, next) {
body(req, function (err, body) {
if (err) {
error('err:', err)
req.body = null
return next()
}
req.body = body
next()
})
}
// Injected dependencies
exports = module.exports = function (commands) {
var router = Router()
/**
* This route should be given to slack as the endpoint to which to send
* `/ephemeral` data.
*/
router.post('/ephemeral', parseBody, function (req, res) {
log('POST /ephemeral')
// grab the payload.
let payload = req.body || { text: '' }
log('body', payload)
/**
* grab the command function from the commands object
*/
var run = commands[payload.text.split(' ')[0]]
/**
* If the command doesn't exist bail and let the client know
*/
if (!run) {
res.statusCode = 400
return res.end('That command is not implemented')
}
/**
* run the command function passing in the payload from slack
*/
run(payload)
.then(function (resp) {
res.statusCode = 200
res.end(resp)
})
.catch(function (e) {
res.statusCode = 500
res.end(`${e.message}\n${e.stack}`)
})
})
/**
* All other routes respond with a message to the user to use `/ephemeral`
*/
router.all('*', function (req, res) {
log(req.method)
res.end('Send POST requests to /ephemeral please and thanks')
})
/**
* Create the server and pass the req and res through the router
*/
var app = http.createServer(function (req, res) {
router(req, res, finalhandler(req, res))
})
return app
}
exports['@require'] = [ 'commands' ]