feat: add multipart image uploads
Register Fastify multipart support, validate JPEG/PNG/WebP binary signatures, store upload bytes through ImageStorage, persist metadata after storage succeeds, clean up bytes on metadata failure, and document the upload boundary. Verification: npm test passed 68 tests and integration passed 14 tests. No build script is configured.
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import Fastify from 'fastify';
|
||||
import cookie from '@fastify/cookie';
|
||||
import multipart from '@fastify/multipart';
|
||||
|
||||
import { registerAuthRoutes } from '../modules/auth/routes/auth-routes.js';
|
||||
import { registerAdminInventoryRoutes } from '../modules/inventory/routes/admin-inventory-routes.js';
|
||||
@@ -28,6 +29,7 @@ export function buildApp(dependencies) {
|
||||
|
||||
app.get('/health', async () => ({ data: { status: 'ok' } }));
|
||||
app.register(cookie);
|
||||
app.register(multipart, { limits: { fileSize: 10 * 1024 * 1024, files: 1 } });
|
||||
app.register(registerAuthRoutes, {
|
||||
...dependencies,
|
||||
prefix: '/api/v1/auth',
|
||||
|
||||
@@ -18,6 +18,7 @@ import { createInventoryItemRepository } from '../modules/inventory/repositories
|
||||
import { createInventoryItemService } from '../modules/inventory/services/inventory-item-service.js';
|
||||
import { createInventoryImageRepository } from '../modules/inventory/repositories/inventory-image-repository.js';
|
||||
import { createInventoryImageService } from '../modules/inventory/services/inventory-image-service.js';
|
||||
import { createLocalImageStorage } from '../infrastructure/images/local-image-storage.js';
|
||||
import { createConditionRepository } from '../modules/inventory/repositories/condition-repository.js';
|
||||
import { createListingRepository } from '../modules/listings/repositories/listing-repository.js';
|
||||
import { createListingService } from '../modules/listings/services/listing-service.js';
|
||||
@@ -78,7 +79,10 @@ async function startServer() {
|
||||
inventoryItemRepository,
|
||||
productRepository,
|
||||
}),
|
||||
inventoryImageService: createInventoryImageService({ inventoryImageRepository }),
|
||||
inventoryImageService: createInventoryImageService({
|
||||
imageStorage: createLocalImageStorage(process.env.IMAGE_STORAGE_ROOT ?? '.local/image-storage'),
|
||||
inventoryImageRepository,
|
||||
}),
|
||||
listingService: createListingService({ listingRepository, inventoryImageRepository }),
|
||||
productService: createProductService({ productRepository }),
|
||||
});
|
||||
|
||||
@@ -4,6 +4,12 @@ const SUPPORTED_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']);
|
||||
const DEFAULT_MAX_FILE_SIZE = 10 * 1024 * 1024;
|
||||
const DEFAULT_MAX_DIMENSION = 10_000;
|
||||
|
||||
const signatures = {
|
||||
'image/jpeg': (data) => data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff,
|
||||
'image/png': (data) => data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
|
||||
'image/webp': (data) => data.length >= 12 && data.toString('ascii', 0, 4) === 'RIFF' && data.toString('ascii', 8, 12) === 'WEBP',
|
||||
};
|
||||
|
||||
export function validateInventoryImageMetadata(
|
||||
image,
|
||||
{ maxFileSize = DEFAULT_MAX_FILE_SIZE, maxDimension = DEFAULT_MAX_DIMENSION } = {},
|
||||
@@ -27,5 +33,13 @@ export function validateInventoryImageMetadata(
|
||||
throw createApplicationError('IMAGE_DIMENSIONS_INVALID', 'Image dimensions are invalid or too large.', 400);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function validateImageSignature(data, mimeType) {
|
||||
if (!Buffer.isBuffer(data) || !signatures[mimeType]?.(data)) {
|
||||
throw createApplicationError('IMAGE_SIGNATURE_INVALID', 'Image bytes do not match the declared MIME type.', 400);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { toAdminInventoryImageDto } from '@pokemon-inventory/contracts/image';
|
||||
import { createInventoryImageSchema } from '@pokemon-inventory/validation/image';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { createApplicationError } from '../../../shared/errors/application-error.js';
|
||||
|
||||
@@ -32,6 +33,39 @@ export async function registerAdminImageRoutes(app, options) {
|
||||
request.headers['x-csrf-token'],
|
||||
);
|
||||
|
||||
if (request.isMultipart()) {
|
||||
const part = await request.file();
|
||||
if (!part) {
|
||||
throw createApplicationError('IMAGE_FILE_REQUIRED', 'An image file is required.', 400);
|
||||
}
|
||||
|
||||
const data = await part.toBuffer();
|
||||
const fields = part.fields;
|
||||
const originalFilename = part.filename;
|
||||
const result = createInventoryImageSchema.safeParse({
|
||||
storageKey: `inventory/${request.params.id}/${randomUUID()}`,
|
||||
originalFilename,
|
||||
mimeType: part.mimetype,
|
||||
fileSize: data.length,
|
||||
width: Number(fields.width?.value),
|
||||
height: Number(fields.height?.value),
|
||||
altText: fields.altText?.value,
|
||||
sortOrder: fields.sortOrder ? Number(fields.sortOrder.value) : undefined,
|
||||
isPrimary: fields.isPrimary?.value === 'true',
|
||||
});
|
||||
|
||||
if (!result.success) return validationError(reply, result);
|
||||
|
||||
const image = await inventoryImageService.upload({
|
||||
...result.data,
|
||||
data,
|
||||
inventoryItemId: request.params.id,
|
||||
sellerId: admin.sellerId,
|
||||
});
|
||||
|
||||
return reply.code(201).send({ data: toAdminInventoryImageDto(image) });
|
||||
}
|
||||
|
||||
const result = createInventoryImageSchema.safeParse(request.body);
|
||||
if (!result.success) return validationError(reply, result);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createApplicationError } from '../../../shared/errors/application-error.js';
|
||||
import { validateInventoryImageMetadata } from '../domain/inventory-image.js';
|
||||
import { validateImageSignature, validateInventoryImageMetadata } from '../domain/inventory-image.js';
|
||||
|
||||
export function createInventoryImageService({ inventoryImageRepository }) {
|
||||
export function createInventoryImageService({ inventoryImageRepository, imageStorage }) {
|
||||
return {
|
||||
async create(input) {
|
||||
validateInventoryImageMetadata(input);
|
||||
@@ -16,5 +16,20 @@ export function createInventoryImageService({ inventoryImageRepository }) {
|
||||
|
||||
return image;
|
||||
},
|
||||
|
||||
async upload(input) {
|
||||
const { data, ...metadata } = input;
|
||||
validateInventoryImageMetadata(metadata);
|
||||
validateImageSignature(data, metadata.mimeType);
|
||||
|
||||
await imageStorage.put({ key: metadata.storageKey, data });
|
||||
|
||||
try {
|
||||
return await this.create(metadata);
|
||||
} catch (error) {
|
||||
await imageStorage.delete(metadata.storageKey);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user