Skip to content

Instantly share code, notes, and snippets.

@theshanergy
Created January 10, 2022 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theshanergy/42fd16010cc968b47f93df1a5413a6f1 to your computer and use it in GitHub Desktop.
Save theshanergy/42fd16010cc968b47f93df1a5413a6f1 to your computer and use it in GitHub Desktop.
const chromium = require('chrome-aws-lambda')
const { builder } = require('@netlify/functions')
async function handler(event, context) {
// Default response.
let response = {
statusCode: 200,
body: 'No image found.',
}
// Get asset from request path.
let pathParts = event.path.split('/').filter((entry) => !!entry)
const asset = pathParts[0]
// Build page url.
const url = process.env.URL + '/' + asset + '/?display=full'
// Load Puppeteer.
let browser = null
try {
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: {
width: 1200,
height: 630,
deviceScaleFactor: 1,
},
executablePath: await chromium.executablePath,
headless: chromium.headless,
ignoreHTTPSErrors: true,
})
let page = await browser.newPage()
// Get page.
const loadpage = await page.goto(url)
if (loadpage.status() == 200) {
// Wait for chart to load.
await page.waitForSelector('.chart-wrapper canvas', { visible: true, timeout: 5000 })
// Add screenshot to response body.
response.body = await page.screenshot({
type: 'png',
encoding: 'base64',
})
response.isBase64Encoded = true
response.headers = {
'content-type': 'image/png',
}
}
} catch (error) {
return response
} finally {
return response
}
}
exports.handler = builder(handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment