feat(api): serve local images with cache headers

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-17 15:28:21 +02:00
parent 45275e56a9
commit 1adc0ee021

View File

@@ -0,0 +1,36 @@
import type { RequestHandler } from './$types';
import { error } from '@sveltejs/kit';
import { createReadStream, existsSync, statSync } from 'node:fs';
import { join, basename, extname } from 'node:path';
const IMAGE_DIR = process.env.IMAGE_DIR ?? './data/images';
const MIME: Record<string, string> = {
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.avif': 'image/avif'
};
export const GET: RequestHandler = ({ params }) => {
const filename = basename(params.filename ?? '');
if (!filename || filename.includes('..')) error(400, { message: 'Invalid filename' });
const full = join(IMAGE_DIR, filename);
if (!existsSync(full)) error(404, { message: 'Not found' });
const st = statSync(full);
const ext = extname(filename).toLowerCase();
const mime = MIME[ext] ?? 'application/octet-stream';
const stream = createReadStream(full);
return new Response(stream as unknown as ReadableStream, {
status: 200,
headers: {
'content-type': mime,
'content-length': String(st.size),
'cache-control': 'public, max-age=86400, immutable'
}
});
};