Created
February 1, 2020 06:21
-
-
Save studds/ff82094c2718ef7226b46f777b0f1c1c to your computer and use it in GitHub Desktop.
A sketch of a lambda to take a screenshot and save it to S3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NB: I'd normally deploy this using CloudFormation | |
/* | |
The lambda needs the following configuration: | |
- A bunch of memory probably 2GB | |
- Better to have a long timeout just in case | |
- Must include the following later: | |
- nodejs10.x (or a newer layer - but haven't tested) | |
- BUCKET_NAME environment variable | |
- Permissions to access BUCKET_NAME | |
*/ | |
const chromium = require('chrome-aws-lambda'); | |
const { Browser } = require ('puppeteer-core'); | |
const puppeteer = chromium.puppeteer; | |
const {S3} = require('aws-sdk'); | |
const s3 = new S3(); | |
exports.handler = async (event) => { | |
console.log(event.url); | |
const buffer = await screenshot(event.url); | |
console.log('got buffer'); | |
await s3 | |
.putObject({ | |
Bucket: process.env.BUCKET_NAME, | |
Key: 'image.png', // todo: determine the key dynamically, based on the provided URL | |
Body: buffer | |
}) | |
.promise(); | |
console.log('wrote to s3'); | |
// TODO implement | |
const response = { | |
statusCode: 200, | |
body: JSON.stringify('Hello from Lambda!'), | |
}; | |
return response; | |
}; | |
"use strict"; | |
async function screenshot(url) { | |
let browser; | |
let buffer; | |
let error; | |
try { | |
browser = await puppeteer.launch({ | |
args: chromium.args, | |
defaultViewport: chromium.defaultViewport, | |
executablePath: await chromium.executablePath, | |
headless: true | |
}); | |
const page = await browser.newPage(); | |
await page.goto(url, { waitUntil: 'networkidle0' }); | |
// await page.waitForSelector('img'); // todo: might want to re-enable this | |
buffer = await page.screenshot({ type: 'png' }); | |
} | |
catch (err) { | |
error = err; | |
} | |
finally { | |
if (browser) { | |
await browser.close(); | |
} | |
} | |
if (error) { | |
throw error; | |
} | |
if (!buffer) { | |
throw new Error('Oh no! Did not get the pdf!'); | |
} | |
return buffer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment