Skip to content

Commit

Permalink
feat: handleCacheHeaders utility
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Apr 6, 2022
1 parent 498ab9c commit 4a71a3f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { CompatibilityEvent } from '../event'

export interface CacheConditions {
modifiedTime?: Date
maxAge?: number
etag?: string
cacheControls?: string[]
}

/**
* Check request caching headers (`If-Modified-Since`) and add caching headers (Last-Modified, Cache-Control)
* Note: `public` cache control will be added by default
* @returns `true` when cache headers are matching. When `true` is returned, no reponse should be sent anymore
*/
export function handleCacheHeaders (event: CompatibilityEvent, opts: CacheConditions): boolean {
const cacheControls = ['public'].concat(opts.cacheControls || [])
let cacheMatched = false

if (opts.maxAge !== undefined) {
opts.cacheControls?.push(`max-age=${+opts.maxAge}`, `s-maxage=${+opts.maxAge}`)
}

if (opts.modifiedTime) {
const ifModifiedSince = event.req.headers['if-modified-since']
event.res.setHeader('Last-Modified', +opts.modifiedTime + '')
if (ifModifiedSince) {
if (new Date(ifModifiedSince) >= opts.modifiedTime) {
cacheMatched = true
}
}
}

if (opts.etag) {
event.res.setHeader('Etag', opts.etag)
const ifNonMatch = event.req.headers['if-none-match']
if (ifNonMatch === opts.etag) {
cacheMatched = true
}
}

event.res.setHeader('Cache-Control', cacheControls.join(', '))

if (cacheMatched) {
event.res.statusCode = 304
event.res.end('')
return true
}

return false
}
1 change: 1 addition & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './body'
export * from './cache'
export * from './consts'
export * from './cookie'
export * from './request'
Expand Down

0 comments on commit 4a71a3f

Please sign in to comment.