Skip to content

Commit

Permalink
fix: add cache-control, remove cache for error responses (#114)
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelcr committed Feb 9, 2023
1 parent 85ce86c commit e03caf8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/api/util/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@ export async function handleTokenCache(request: FastifyRequest, reply: FastifyRe
if (ifNoneMatch && ifNoneMatch.includes(etag)) {
await reply.header('Cache-Control', CACHE_CONTROL_MUST_REVALIDATE).code(304).send();
} else {
void reply.header('ETag', `"${etag}"`);
void reply.headers({ 'Cache-Control': CACHE_CONTROL_MUST_REVALIDATE, ETag: `"${etag}"` });
}
}
}

export function setReplyNonCacheable(reply: FastifyReply) {
reply.removeHeader('Cache-Control');
reply.removeHeader('Etag');
}

/**
* Retrieve the token's last modified date as a UNIX epoch so we can use it as the response ETag.
* @returns Etag string
Expand Down
2 changes: 2 additions & 0 deletions src/api/util/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@ import {
TokenNotFoundError,
TokenNotProcessedError,
} from '../../pg/errors';
import { setReplyNonCacheable } from './cache';

export const TokenErrorResponseSchema = {
404: TokenNotFoundResponse,
422: Type.Union([TokenNotProcessedResponse, TokenLocaleNotFoundResponse]),
};

export async function generateTokenErrorResponse(error: any, reply: FastifyReply) {
setReplyNonCacheable(reply);
if (error instanceof TokenNotFoundError) {
await reply.code(404).send(Value.Create(TokenNotFoundResponse));
} else if (error instanceof TokenNotProcessedError) {
Expand Down

0 comments on commit e03caf8

Please sign in to comment.