Skip to content

Instantly share code, notes, and snippets.

@Swahjak
Last active March 6, 2024 17:59
Show Gist options
  • Save Swahjak/501e9c58551cd5433707d4bd2b737f4e to your computer and use it in GitHub Desktop.
Save Swahjak/501e9c58551cd5433707d4bd2b737f4e to your computer and use it in GitHub Desktop.
const someQuestion: CollectionConfig = {
slug: 'some-collection',
custom: {
cacheControl: 'public, max-age=300, stale-while-revalidate=300, stale-if-error=86400',
},
}
import { NextFunction, Request, Response } from 'express'
import { PayloadRequest } from 'payload/types'
type Middleware = (req: Request, res: Response, next: NextFunction) => void
let globalsMap = new Map<string, number>()
let initialGlobals = false
export const useCache: Middleware = (req: PayloadRequest, res, next) => {
if (req?.payloadAPI !== 'REST') {
req.payload.logger.info(`Not using cache for ${req?.payloadAPI} API`)
next()
return
}
if (req.collection && req.collection.config.custom?.cacheControl) {
const cacheControl = req.collection.config.custom.cacheControl
req.payload.logger.info(`Cache-Control: ${cacheControl}`)
res.set('Cache-Control', cacheControl)
next()
return
}
if (!req.url.startsWith('/globals')) {
next()
return
}
if (!initialGlobals) {
req.payload.logger.info('Initializing globals cache')
initialGlobals = true
req.payload.globals.config.forEach((global, index) => {
globalsMap.set(global.slug, index)
})
}
const slug = req.url.split('/').pop()
if (globalsMap.has(slug) && req.payload.globals.config[globalsMap.get(slug)].custom?.cacheControl) {
const cacheControl = req.payload.globals.config[globalsMap.get(slug)].custom.cacheControl
req.payload.logger.info(`Cache-Control: ${cacheControl}`)
res.set('Cache-Control', cacheControl)
}
next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment