Improve browser caching with cache control header
Not only does the header need to be added, but the signed URL needs to have it's expiry rounded so that the return url is the same for a given window, say 10minutes I followed this https://advancedweb.hu/cacheable-s3-signed-urls/ basically what this means is that because we're caching the assets themselves, if as user asks for a part that already exists we'll return a url for the existing part instead of regenerating it, however if it was them that generated the part less than 10 minutes ago, they'll still have to download the asset again. This way it will save us costs and will be quicker for them. Resolves #334
This commit is contained in:
@@ -64,12 +64,24 @@ async function checkIfAlreadyExists(params, s3) {
|
||||
}
|
||||
}
|
||||
|
||||
function getObjectUrl(params, s3) {
|
||||
function getObjectUrl(params, s3, tk) {
|
||||
const getTruncatedTime = () => {
|
||||
const currentTime = new Date()
|
||||
const d = new Date(currentTime)
|
||||
|
||||
d.setMinutes(Math.floor(d.getMinutes() / 10) * 10)
|
||||
d.setSeconds(0)
|
||||
d.setMilliseconds(0)
|
||||
|
||||
return d
|
||||
}
|
||||
const HALF_HOUR = 1800
|
||||
return s3.getSignedUrl('getObject', {
|
||||
...params,
|
||||
Expires: HALF_HOUR,
|
||||
})
|
||||
return tk.withFreeze(getTruncatedTime(), () =>
|
||||
s3.getSignedUrl('getObject', {
|
||||
...params,
|
||||
Expires: HALF_HOUR,
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function loggerWrap(handler) {
|
||||
@@ -90,6 +102,7 @@ async function storeAssetAndReturnUrl({
|
||||
key,
|
||||
s3,
|
||||
params,
|
||||
tk,
|
||||
}) {
|
||||
if (error) {
|
||||
const response = {
|
||||
@@ -114,16 +127,18 @@ async function storeAssetAndReturnUrl({
|
||||
callback(null, response)
|
||||
return
|
||||
}
|
||||
const FiveDays = 432000
|
||||
const storedRender = await s3
|
||||
.putObject({
|
||||
Bucket: process.env.BUCKET,
|
||||
Key: key,
|
||||
Body: buffer,
|
||||
CacheControl: `max-age=${FiveDays}`, // browser caching to stop downloads of the same part
|
||||
Metadata: putConsoleMessageInMetadata(consoleMessage),
|
||||
})
|
||||
.promise()
|
||||
console.log('stored object', storedRender)
|
||||
const url = getObjectUrl(params, s3)
|
||||
const url = getObjectUrl(params, s3, tk)
|
||||
console.log('url', url)
|
||||
const response = {
|
||||
statusCode: 200,
|
||||
|
||||
Reference in New Issue
Block a user