Skip to content

Commit

Permalink
fix: add cache control and etag headers to 304 response
Browse files Browse the repository at this point in the history
  • Loading branch information
codename-niels committed Sep 5, 2024
1 parent 3b2228b commit 6766cf9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 19 deletions.
37 changes: 19 additions & 18 deletions npm/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Handle, MaybePromise } from '@sveltejs/kit';
import type { Handle } from '@sveltejs/kit';
import Redis from 'ioredis';
import { captureException } from '@sentry/sveltekit';

Expand Down Expand Up @@ -65,7 +65,7 @@ export async function createCacheControlResponse(
redisUrl: string,
opt: Partial<HeaderOptions>,
request: Request,
response: Response | (() => MaybePromise<Response>) | null = null
response: Response | (() => Response | Promise<Response>) | null = null
) {
const options = {
...DEFAULT_HEADER_OPTIONS,
Expand All @@ -84,22 +84,6 @@ export async function createCacheControlResponse(
(param) => !new URL(request.url).searchParams.has(param)
)
) {
if (options.etagCacheKey && redis) {
const etag = await redis.get(options.etagCacheKey);

if (etag) {
const requestEtag = request.headers.get('If-None-Match');
if (requestEtag === etag) {
return new Response(null, {
status: 304,
statusText: 'Not Modified',
});
}

headers.ETag = etag;
}
}

const joinParts = (p: (string | null | undefined | boolean)[]) =>
p.filter(Boolean).join(', ');

Expand Down Expand Up @@ -133,6 +117,23 @@ export async function createCacheControlResponse(
else if (options.strategy === CACHE_STRATEGY_NO_CACHE) {
headers['Cache-Control'] = 'no-cache';
}

if (options.etagCacheKey && redis) {
const etag = await redis.get(options.etagCacheKey);

if (etag) {
headers.ETag = etag;

const requestEtag = request.headers.get('If-None-Match');
if (requestEtag === etag) {
return new Response(null, {
status: 304,
statusText: 'Not Modified',
headers,
});
}
}
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion npm/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@born05/sveltekit-cache-control",
"version": "1.3.1",
"version": "1.3.2",
"description": "A simple way to add control caching in your SvelteKit project.",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 6766cf9

Please sign in to comment.