fix(admin): ensure uploads dir exists before writing (resilient upload)

The upload route only relied on the startup mkdir; if the dir is removed while
the server runs, writes failed with ENOENT. Now mkdir -p before each write.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
AyoubBenziza 2026-06-10 23:43:47 +02:00
parent 62b536cc2b
commit 9c1413744d

View file

@ -2,7 +2,7 @@
// CRUD des questions manuelles écrites en base (source 'manual'). // CRUD des questions manuelles écrites en base (source 'manual').
import { randomUUID } from "node:crypto" import { randomUUID } from "node:crypto"
import { writeFile } from "node:fs/promises" import { mkdir, writeFile } from "node:fs/promises"
import { extname, resolve } from "node:path" import { extname, resolve } from "node:path"
import type { FastifyInstance } from "fastify" import type { FastifyInstance } from "fastify"
import { desc, eq } from "drizzle-orm" import { desc, eq } from "drizzle-orm"
@ -109,6 +109,8 @@ export async function adminRoutes(app: FastifyInstance) {
const safeExt = IMAGE_EXT.includes(ext) ? ext : ".jpg" const safeExt = IMAGE_EXT.includes(ext) ? ext : ".jpg"
const name = `${randomUUID()}${safeExt}` const name = `${randomUUID()}${safeExt}`
const buffer = await file.toBuffer() const buffer = await file.toBuffer()
// Crée le dossier si besoin (résilient s'il a été supprimé après le démarrage).
await mkdir(resolve(env.uploadsDir), { recursive: true })
await writeFile(resolve(env.uploadsDir, name), buffer) await writeFile(resolve(env.uploadsDir, name), buffer)
return { url: `/uploads/${name}` } return { url: `/uploads/${name}` }
}) })