-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.js
93 lines (77 loc) · 2.04 KB
/
export.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
91
92
93
const fs = require('fs')
const path = require('path')
const generate = require('nanoid/generate')
const set = require('lodash.set')
module.exports = ({
PORT,
puppeteer,
browserWSEndpoint,
}) => async function (req, res) {
let type
const {
options = {},
exportOptions = {},
format = 'png',
} = req.body
set(options, 'exporting.fallbackToExportServer', false)
const rid = generate('1234567890abcdef', 10)
if (format === 'png') {
type = 'image/png'
} else if (format === 'jpeg') {
type = 'image/jpeg'
} else if (format === 'pdf') {
type = 'application/pdf'
} else if (format === 'svg') {
type = 'image/svg+xml'
} else {
type = 'image/png'
}
const browser = await puppeteer.connect({ browserWSEndpoint })
const page = await browser.newPage()
await page.goto(`http://localhost:${PORT}/headless/index.html`, {
waitUntil: 'domcontentloaded',
})
await page._client.send('Page.setDownloadBehavior', {
behavior: 'allow',
downloadPath: path.resolve(__dirname, 'public'),
})
try {
await page.evaluate(async ({ options, exportOptions, type, rid }) => {
const chart = Highcharts.chart('container', options)
chart.exportChartLocal({
filename: rid,
type,
...exportOptions
})
}, {
options,
exportOptions,
type,
rid,
})
const downloadUrl = await new Promise(async resolve => {
const filename = rid + '.' + format
const filepath = path.resolve(__dirname, 'public', filename)
const timerId = setInterval(async function () {
if (!fs.existsSync(filepath)) return
await page.close()
await browser.disconnect()
clearInterval(timerId)
resolve('/' + filename)
}, 10)
})
const result = {
downloadUrl,
}
console.log('done', result)
res.json({ result })
} catch(ex) {
console.log('failed', ex)
await page.close()
await browser.disconnect()
const err = {
message: 'failed to export'
}
res.json({ err })
}
}