Created
March 29, 2018 16:26
-
-
Save furkan3ayraktar/183940f443777789cca501b4082cf030 to your computer and use it in GitHub Desktop.
Function for fetching index.html of SPA and adding metaData to it. This function also prepares a response for CloudFront to cache.
This file contains hidden or 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
const fetchIndexHtmlAndCreateCloudFrontResponse = (url, metaTags, metaHeaders, callback) => { | |
downloadContent(url, (isOk, result, headers) => { | |
if (!isOk) { | |
console.log('Error fetching content:', result); | |
callback(false); | |
} else { | |
// We have <title>House of Radon</title> inside the actual index.html. We use that part to replace with actual metadata. | |
const finalBody = result.replace('<title>House of Radon</title>', metaTags); | |
const buffer = zlib.gzipSync(finalBody); | |
const base64EncodedBody = buffer.toString('base64'); | |
const responseHeaders = { | |
'content-type': [{key:'Content-Type', value: 'text/html'}], | |
'content-encoding' : [{key:'Content-Encoding', value: 'gzip'}], | |
'accept-ranges': [{key:'Accept-Ranges', value: 'bytes'}] | |
}; | |
let eTag = ''; | |
// We update eTag of the response with combining eTag of the metadata and index.html. | |
// This will let us notifiy CloudFront and client if anything is changed on backend or frontend. | |
if (metaHeaders) { | |
const metaEtag = metaHeaders['etag']; | |
if (metaEtag) { | |
eTag = metaEtag.replace(/"/g, ''); | |
} | |
} | |
// Prepare other relevant headers. | |
if (headers) { | |
const lastModified = headers['last-modified']; | |
const cacheControl = headers['cache-control']; | |
const contentETag = headers['etag']; | |
if (lastModified) { | |
responseHeaders['last-modified'] = [{key:'Last-Modified', value: lastModified}] | |
} | |
if (lastModified) { | |
responseHeaders['cache-control'] = [{key:'Cache-Control', value: cacheControl}] | |
} | |
if (contentETag) { | |
eTag += contentETag.replace(/"/g, '');; | |
} | |
} | |
if (eTag !== '') { | |
responseHeaders['etag'] = [{key:'ETag', value: eTag}] | |
} | |
const newResponse = { | |
status: '200', | |
statusDescription: 'OK', | |
headers: responseHeaders, | |
body: base64EncodedBody, | |
bodyEncoding: 'base64', | |
}; | |
callback(true, newResponse); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment