forked from badges/shields
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresult-sender.js
54 lines (47 loc) · 1.44 KB
/
result-sender.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
'use strict'
const stream = require('stream')
const log = require('./log')
const svg2img = require('../gh-badges/lib/svg-to-img')
function streamFromString(str) {
const newStream = new stream.Readable()
newStream._read = () => {
newStream.push(str)
newStream.push(null)
}
return newStream
}
function makeSend(format, askres, end) {
if (format === 'svg') {
return res => sendSVG(res, askres, end)
} else if (format === 'json') {
return res => sendJSON(res, askres, end)
} else {
return res => sendOther(format, res, askres, end)
}
}
function sendSVG(res, askres, end) {
askres.setHeader('Content-Type', 'image/svg+xml;charset=utf-8')
end(null, { template: streamFromString(res) })
}
function sendOther(format, res, askres, end) {
askres.setHeader('Content-Type', `image/${format}`)
svg2img(res, format)
// This interacts with callback code and can't use async/await.
// eslint-disable-next-line promise/prefer-await-to-then
.then(data => {
end(null, { template: streamFromString(data) })
})
.catch(err => {
// This emits status code 200, though 500 would be preferable.
log.error('svg2img error', err)
end(null, { template: '500.html' })
})
}
function sendJSON(res, askres, end) {
askres.setHeader('Content-Type', 'application/json')
askres.setHeader('Access-Control-Allow-Origin', '*')
end(null, { template: streamFromString(res) })
}
module.exports = {
makeSend,
}