feat(server): add POST /api/admin/gallery/upload endpoint
This commit is contained in:
@@ -1,6 +1,12 @@
|
|||||||
import fs from 'node:fs/promises'
|
import fs from 'node:fs/promises'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { prisma } from '../../lib/prisma.js'
|
import { prisma } from '../../lib/prisma.js'
|
||||||
|
import { persistMultipartImages } from '../../lib/upload-images.js'
|
||||||
|
import {
|
||||||
|
formatFileTooLargeMessage,
|
||||||
|
getProductImageMaxFileBytes,
|
||||||
|
isMultipartFileTooLargeError,
|
||||||
|
} from '../../lib/upload-limits.js'
|
||||||
|
|
||||||
export async function registerAdminGalleryRoutes(fastify) {
|
export async function registerAdminGalleryRoutes(fastify) {
|
||||||
fastify.get(
|
fastify.get(
|
||||||
@@ -14,6 +20,38 @@ export async function registerAdminGalleryRoutes(fastify) {
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
fastify.post(
|
||||||
|
'/api/admin/gallery/upload',
|
||||||
|
{ preHandler: [fastify.verifyAdmin] },
|
||||||
|
async (request, reply) => {
|
||||||
|
try {
|
||||||
|
const urls = await persistMultipartImages(request, {
|
||||||
|
maxFiles: 10,
|
||||||
|
maxFileBytes: getProductImageMaxFileBytes(),
|
||||||
|
subdir: '',
|
||||||
|
eager: false,
|
||||||
|
})
|
||||||
|
for (const url of urls) {
|
||||||
|
await prisma.galleryImage.create({
|
||||||
|
data: { url, isResized: false },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return { urls }
|
||||||
|
} catch (error) {
|
||||||
|
let message = error instanceof Error ? error.message : 'Не удалось загрузить файлы'
|
||||||
|
let statusCode =
|
||||||
|
error && typeof error === 'object' && 'statusCode' in error && Number.isInteger(error.statusCode)
|
||||||
|
? Number(error.statusCode)
|
||||||
|
: 400
|
||||||
|
if (isMultipartFileTooLargeError(error)) {
|
||||||
|
message = formatFileTooLargeMessage(getProductImageMaxFileBytes())
|
||||||
|
statusCode = 413
|
||||||
|
}
|
||||||
|
return reply.code(statusCode).send({ error: message })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
fastify.delete(
|
fastify.delete(
|
||||||
'/api/admin/gallery/:id',
|
'/api/admin/gallery/:id',
|
||||||
{ preHandler: [fastify.verifyAdmin] },
|
{ preHandler: [fastify.verifyAdmin] },
|
||||||
|
|||||||
Reference in New Issue
Block a user