-
Notifications
You must be signed in to change notification settings - Fork 9
/
webapp.js
80 lines (79 loc) · 2.22 KB
/
webapp.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
var BSON = require('bson')
, utils = require('./lib/utils')
module.exports = {
config: [{
id: String,
// TODO do we want configurable triggers? Currently we only support job.done
trigger: {type: String, default: 'job.done'},
url: String,
secret: String,
format: String
}],
// global events
listen: function (io, context) {
io.on('plugin.webhooks.fire', function (url, secret, payload) {
utils.fire(url, secret, payload)
})
},
// prefixed by /:repo/:name/api/:pluginname
// req.pluginConfig() -> get the config for this plugin
// req.pluginConfig(config, cb(err)) -> set the config for this plugin
routes: function (app) {
app.post('/', function (req, res) {
var id = (new BSON()).toString()
, hooks = req.pluginConfig()
hooks.push({
id: id,
trigger: req.body.trigger || 'job.done',
url: req.body.url,
secret: req.body.secret,
format: req.body.format
})
req.pluginConfig(hooks, function (err) {
if (err) return res.send({error: 'Failed to add webhook', more: err})
res.send({success: true, id: id})
})
})
app.put('/:id', function (req, res) {
var hooks = req.project.plugins.webhooks
, found = -1
for (var i=0; i<hooks.length; i++) {
if (hooks[i].id === req.params.id) {
found = i
break;
}
}
if (found === -1) {
res.status(404)
return res.send('Webhook not found')
}
hooks[i] = req.body
})
app.get('/', function (req, res) {
res.send({hooks: req.project.plugins.webhooks})
})
app.delete('/:id', function (req, res) {
var hooks = req.project.plugins.webhooks
, found = -1
for (var i=0; i<hooks.length; i++) {
if (hooks[i].id === req.params.id) {
found = i
break;
}
}
if (found === -1) {
res.status(404)
return res.send('Webhook not found')
}
hooks.splice(found, 1)
req.user.save(function (err) {
if (err) {
res.status(500)
return res.send({error: 'failed to save', info: err})
}
res.status(200)
res.send({success: true})
})
})
}
}