first commit

This commit is contained in:
bobban committed 2026-10-22 21:00:25 +02:00
commit b7b0f253ce
85 files changed
+7560

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
import { randomUUID } from "node:crypto";
import { mkdir, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads");
export const MAX_UPLOAD_BYTES = 15 * 1024 * 1024;
const EXTENSIONS: Record<string, string> = {
"image/png": "png",
"image/jpeg": "jpg",
"image/webp": "webp",
"image/gif": "gif",
};
export const CONTENT_TYPES: Record<string, string> = {
png: "image/png",
jpg: "image/jpeg",
webp: "image/webp",
gif: "image/gif",
};
export const FILE_NAME_PATTERN = /^[a-f0-9-]{36}\.(png|jpg|webp|gif)$/;
export function isUpload(value: FormDataEntryValue | null): value is File {
return typeof value === "object" && value !== null && value.size > 0;
}
/** Sparar en uppladdad bild och returnerar filnamnet. Kastar vid fel typ eller storlek. */
export async function saveImage(file: File): Promise<string> {
const ext = EXTENSIONS[file.type];
if (!ext) throw new Error("Unsupported image type");
if (file.size > MAX_UPLOAD_BYTES) throw new Error("Image is too large");
await mkdir(UPLOAD_DIR, { recursive: true });
const name = `${randomUUID()}.${ext}`;
await writeFile(path.join(UPLOAD_DIR, name), Buffer.from(await file.arrayBuffer()));
return name;
}
export async function deleteImage(name: string | null | undefined) {
if (!name || !FILE_NAME_PATTERN.test(name)) return;
try {
await unlink(path.join(UPLOAD_DIR, name));
} catch {
// filen kan redan vara borta
}
}
export function fileUrl(name: string | null | undefined): string | null {
return name ? `/api/files/${name}` : null;
}