forked from valeriangalliat/vercel-custom-log-drain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (71 loc) · 1.97 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
86
87
88
89
90
const fs = require('fs')
const qs = require('querystring')
const fetch = require('node-fetch')
const fastify = require('fastify')
const formBody = require('fastify-formbody')
const config = require('/data/config')
const form = fs.readFileSync('form.html', 'utf8')
async function getToken (code) {
const url = `https://api.vercel.com/v2/oauth/access_token`
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: qs.stringify({
client_id: config.clientId,
client_secret: config.clientSecret,
code,
redirect_uri: config.redirectUri
})
})
if (!res.ok) {
throw new Error(`${url} responded with ${res.status}`)
}
const json = await res.json()
return json
}
async function createLogDrain (data, body) {
const url = `https://api.vercel.com/v1/integrations/log-drains?teamId=${data.team_id}`
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${data.access_token}`
},
body: JSON.stringify(body)
})
if (!res.ok) {
throw new Error(`${url} responded with ${res.status}`)
}
}
const app = fastify({ logger: true })
app.register(formBody)
app.get('/vercel/callback', (req, res) => {
if (!req.query.code || !req.query.next) {
return res.type('text/plain').send('Hello!')
}
res.type('text/html').send(form)
})
app.post('/vercel/callback', async (req, res) => {
if (!req.query.code || !req.query.next || !req.body.type || !req.body.url) {
return res.code(400)
}
const token = await getToken(req.query.code)
await createLogDrain(token, {
name: 'custom-log-drain',
type: req.body.type,
url: req.body.url
})
res.redirect(req.query.next)
})
app.post('/echo', async (req, res) => {
console.log(req.body)
res.code(204)
})
app.listen(process.env.PORT || 8080, '0.0.0.0', err => {
if (err) {
app.log.error(err)
process.exit(1)
}
})