|
| 1 | + |
| 2 | +const chrome = require('chrome-aws-lambda') |
| 3 | +const puppeteer = require('puppeteer') |
| 4 | + |
| 5 | +const getAbsoluteURL = (path: string) => { |
| 6 | + // if (process.env.NODE_ENV === 'development') { |
| 7 | + return `http://localhost:3000/${path}` |
| 8 | + // } |
| 9 | + // https://image.w.kodadot.xyz/ipfs/bafybeiaylihby4c5tqzl6tps35hfha5xjofyzk4ztpsj6nh7z3jhxeth3y/?hash=0xecfac00a67f88d51a47f06e7e73d7a436609e44760926a7712be9b73356061d8 |
| 10 | + // return `https://image.w.kodadot.xyz/ipfs/bafybeiaylihby4c5tqzl6tps35hfha5xjofyzk4ztpsj6nh7z3jhxeth3y/${path}` |
| 11 | +} |
| 12 | + |
| 13 | +export default async (req: any, res: any) => { |
| 14 | + let { |
| 15 | + query: { hash, cid, resolution } |
| 16 | + } = req |
| 17 | + |
| 18 | + if (!hash) return res.status(400).end(`No model provided`) |
| 19 | + |
| 20 | + let browser |
| 21 | + |
| 22 | + if (process.env.NODE_ENV === 'production') { |
| 23 | + browser = await puppeteer.launch({ |
| 24 | + args: chrome.args, |
| 25 | + defaultViewport: chrome.defaultViewport, |
| 26 | + executablePath: await chrome.executablePath, |
| 27 | + headless: chrome.headless, |
| 28 | + ignoreHTTPSErrors: true |
| 29 | + }) |
| 30 | + } else { |
| 31 | + browser = await puppeteer.launch({ |
| 32 | + headless: 'new' |
| 33 | + }) |
| 34 | + } |
| 35 | + |
| 36 | + const page = await browser.newPage() |
| 37 | + |
| 38 | + if (resolution) { |
| 39 | + await page.setViewport({ width: resolution, height: resolution }) |
| 40 | + } else { |
| 41 | + await page.setViewport({ width: 512, height: 512 }) |
| 42 | + } |
| 43 | + |
| 44 | + const url = getAbsoluteURL(`?hash=${hash}`) |
| 45 | + |
| 46 | + console.log('url', url) |
| 47 | + |
| 48 | + await page.goto(url); |
| 49 | + |
| 50 | + const selector = 'canvas'; |
| 51 | + |
| 52 | + await page.waitForSelector(selector); |
| 53 | + |
| 54 | + // const element = page.$(selector) |
| 55 | + |
| 56 | + const data = await page.screenshot({ |
| 57 | + type: 'png' |
| 58 | + }) |
| 59 | + |
| 60 | + await browser.close() |
| 61 | + // Set the s-maxage property which caches the images then on the Vercel edge |
| 62 | + res.setHeader('Cache-Control', 's-maxage=10, stale-while-revalidate') |
| 63 | + res.setHeader('Content-Type', 'image/png') |
| 64 | + // Write the image to the response with the specified Content-Type |
| 65 | + res.end(data) |
| 66 | +} |
0 commit comments