import express from 'express' ; import cors from 'cors' ; import urlJoin from 'url-join' ; import { v4 as uuidv4 } from 'uuid' ; import { takeScreenshot } from './screenshots' ; console . log ( 'dynamic_web_content cold start.' ) ; /**
 * Main express instance that will handle all of our "dynamic" web requests.
 */ export const dynamicWebContentHandler = express ( ) ; dynamicWebContentHandler . use ( cors ( { origin : true } ) ) ; const shareRouter = express . Router ( { mergeParams : true } ) ; dynamicWebContentHandler . use ( '/share/:snapshotId-:shareId/' , shareRouter ) ; /**
 * Handler for share image requests which takes the tail of the URL and uses
 * headless chrome to visit /internal/share-image/<url>/ and captures the
 * screenshot and serves it back as the response.
 */ shareRouter . get ( /\/(.*)\.png/ , ( req , res ) => { const snapshotId = req . params [ 'snapshotId' ] ; let sharePath = req . params [ 0 ] ; if ( sharePath === 'home' ) { sharePath = '' ; } else if ( sharePath . endsWith ( '-image-covid-us-map-cases' ) ) { sharePath = 'map' ; } const baseUrl = req . hostname === 'localhost' ? 'http://localhost:3000/' : 'https://covidactnow.org/' ; const url = urlJoin ( baseUrl , '/internal/share-image/' , sharePath , `?snapshot=${ snapshotId }` ) ; console . log ( `Generating screenshot for ${ url }` ) ; takeScreenshot ( url ) . then ( ( file ) => { console . log ( 'screenshot generated.' ) ; if ( req . query [ 'no-cache' ] === undefined ) { console . log ( 'Setting cache-control header.' ) ; res . header ( 'cache-control' , 'public, max-age=86400' ) ; } res . sendFile ( file ) ; } ) . catch ( error => { const errorId = uuidv4 ( ) ; console . error ( 'Error' , errorId , error ) ; res . status ( 500 ) . send ( `<html>Image temporarily not available. Try again later.<br/>Error Id: ${ errorId }<br />${ error }</html>` ) ; } ) ; } ) ;