-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathhook.js
66 lines (54 loc) · 1.59 KB
/
hook.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
'use strict'
const assert = require('assert')
const request = require('request')
const express = require('express')
const bodyParser = require('body-parser')
assert(process.env.GITHUB_TOKEN, 'GITHUB_TOKEN must be set')
assert(process.env.GIT_REPO, 'GIT_REPO must be set')
const API_TOKEN = process.env.GITHUB_TOKEN
const REPO = process.env.GIT_REPO
const PORT = process.env.PORT || 9000
const app = express()
const travis = request.defaults({
baseUrl: 'https://api.travis-ci.org',
json: true
})
app.use(bodyParser.json())
app.get('/', (req, res, next) => {
res.status(200).json({status: 'OK'})
})
app.get('/build', (req, res, next) => {
authorize((err, token) => {
if (err) next(err)
else triggerBuild(token, (err, data) => {
if (err) next(err)
else res.status(200).json(data)
})
})
})
function authorize(cb) {
console.log('authorizing')
travis.post('/auth/github', {
body: {github_token: API_TOKEN},
headers: {'User-Agent': 'Travis/1.0'}
}, (err, _res) => {
if (err) cb(err)
else cb(null, _res.body.access_token)
})
}
function triggerBuild(token, cb) {
console.log('starting build')
let path = 'repo/' + encodeURIComponent(REPO) + '/requests'
let body = {branch: 'master', message: 'API request'}
let headers = {
'User-Agent': 'Travis/1.0',
'Travis-API-Version': '3',
'Authorization': `token ${token}`
}
travis.post(path, {body, headers}, (err, res) => {
if (err) cb(null, err)
else if (!/^2/.test(res.statusCode.toString())) cb(res.body)
else cb(null, res.body)
})
}
app.listen(PORT, _ => console.log(':' + PORT))