Add cache headers to avatars (#737)

* Set cache headers on newly uploaded avatars

* Go fix up all the old avatars to have cache headers
This commit is contained in:
Marshall Polaris 2022-08-10 11:03:55 -07:00 committed by GitHub
parent b5b77be188
commit 8c537537a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 1 deletions

View File

@ -0,0 +1,27 @@
import { initAdmin } from './script-init'
import { log } from '../utils'
const app = initAdmin()
const ONE_YEAR_SECS = 60 * 60 * 24 * 365
const AVATAR_EXTENSION_RE = /\.(gif|tiff|jpe?g|png|webp)$/i
const processAvatars = async () => {
const storage = app.storage()
const bucket = storage.bucket(`${app.options.projectId}.appspot.com`)
const [files] = await bucket.getFiles({ prefix: 'user-images' })
log(`${files.length} avatar images to process.`)
for (const file of files) {
if (AVATAR_EXTENSION_RE.test(file.name)) {
log(`Updating metadata for ${file.name}.`)
await file.setMetadata({
cacheControl: `public, max-age=${ONE_YEAR_SECS}`,
})
} else {
log(`Skipping ${file.name} because it probably isn't an avatar.`)
}
}
}
if (require.main === module) {
processAvatars().catch((e) => console.error(e))
}

View File

@ -3,6 +3,8 @@ import imageCompression from 'browser-image-compression'
import { nanoid } from 'nanoid' import { nanoid } from 'nanoid'
import { storage } from './init' import { storage } from './init'
const ONE_YEAR_SECS = 60 * 60 * 24 * 365
export const uploadImage = async ( export const uploadImage = async (
username: string, username: string,
file: File, file: File,
@ -24,7 +26,9 @@ export const uploadImage = async (
}) })
} }
const uploadTask = uploadBytesResumable(storageRef, file) const uploadTask = uploadBytesResumable(storageRef, file, {
cacheControl: `public, max-age=${ONE_YEAR_SECS}`,
})
let resolvePromise: (url: string) => void let resolvePromise: (url: string) => void
let rejectPromise: (reason?: any) => void let rejectPromise: (reason?: any) => void