-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathimage.js
59 lines (46 loc) · 1.57 KB
/
image.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
const fetch = require('node-fetch')
const puppeteer = require('puppeteer')
let browser
const generateImage = async (symbol, timeframe, dateString) => {
if (!browser) {
browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
headless: 'new',
})
}
const page = await browser.newPage()
let genUrl = `${process.env.STOCK_CHART_GENERATOR_URL}/chart/${symbol}`
if (timeframe) {
genUrl += `?timeframe=${timeframe}`
}
if (dateString) {
const s = timeframe ? '&' : '?'
genUrl += `${s}date=${dateString}`
}
await page.goto(genUrl)
await page.waitForSelector('img') // Make sure the image is loaded
const imageData = await page.evaluate(
'document.querySelector("img").getAttribute("src")',
)
await page.close()
return convertToImageStream(imageData)
}
const getCachedImage = async (symbol, timeframe, dateString) => {
let imageDataUrl = `${process.env.STOCK_CHART_WORKER_URL}/images/${symbol}`
imageDataUrl += `/${timeframe || 'daily'}`
imageDataUrl += `/${dateString || new Date().toISOString().slice(0, 10)}`
const response = await fetch(imageDataUrl)
if (response.status !== 200) {
throw new Error(
`Chart could not be loaded for ${symbol}, please try later.`,
)
}
const imageData = await response.text()
return convertToImageStream(imageData)
}
const convertToImageStream = (imageData) => {
const image = imageData.split('base64,')[1]
const imageStream = Buffer.alloc(image.length, image, 'base64')
return imageStream
}
module.exports = { generateImage, getCachedImage }