Skip to content

Commit

Permalink
compare metadatapart of timestamp (#579)
Browse files Browse the repository at this point in the history
  • Loading branch information
hugo-nl authored Jan 24, 2025
1 parent 4d44bda commit 9fd1cc4
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions src/api/routes/company.read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ import {
} from '../schemas'
import { eTagCache } from '../..'

export const ETAG_CACHE_KEY = 'companies:etag'

function isNumber(n: unknown): n is number {
return Number.isFinite(n)
}
Expand Down Expand Up @@ -140,22 +138,19 @@ export async function companyReadRoutes(app: FastifyInstance) {
const cacheKey = 'companies:etag'

let currentEtag = await eTagCache.get(cacheKey)
const latestMetadata = await prisma.metadata.findFirst({
select: { updatedAt: true },
orderBy: { updatedAt: 'desc' },
})
const latestMetadataUpdatedAt =
latestMetadata?.updatedAt.toISOString() || ''

if (!currentEtag) {
const latestMetadata = await prisma.metadata.findFirst({
select: { updatedAt: true },
orderBy: { updatedAt: 'desc' },
})

const metadataUpdatedAt = latestMetadata?.updatedAt.toISOString() || ''
const currentTimestamp = new Date().toISOString()
currentEtag = `${metadataUpdatedAt}-${currentTimestamp}`
if (!currentEtag || !currentEtag.startsWith(latestMetadataUpdatedAt)) {
currentEtag = `${latestMetadataUpdatedAt}-${new Date().toISOString()}`
eTagCache.set(cacheKey, currentEtag)
}

if (clientEtag === currentEtag) {
return reply.code(304).send()
}
if (clientEtag === currentEtag) return reply.code(304).send()

reply.header('ETag', `${currentEtag}`)

Expand Down

0 comments on commit 9fd1cc4

Please sign in to comment.