|
| 1 | +import { BadRequestException } from '@nestjs/common'; |
| 2 | +import { FileUpload } from 'graphql-upload-minimal'; |
| 3 | +import path from 'path'; |
| 4 | + |
| 5 | +/** Maximum allowed file size (5MB) */ |
| 6 | +const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB |
| 7 | + |
| 8 | +/** Allowed image MIME types */ |
| 9 | +const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp']; |
| 10 | + |
| 11 | +/** Allowed file extensions */ |
| 12 | +const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp']; |
| 13 | + |
| 14 | +/** |
| 15 | + * Validates a file upload (size, type) and returns a Buffer. |
| 16 | + * @param file - FileUpload object from GraphQL |
| 17 | + * @returns Promise<Buffer> - The file data in buffer format |
| 18 | + * @throws BadRequestException - If validation fails |
| 19 | + */ |
| 20 | +export async function validateAndBufferFile( |
| 21 | + file: FileUpload, |
| 22 | +): Promise<{ buffer: Buffer; mimetype: string }> { |
| 23 | + const { filename, createReadStream, mimetype } = await file; |
| 24 | + |
| 25 | + // Extract the file extension |
| 26 | + const extension = path.extname(filename).toLowerCase(); |
| 27 | + |
| 28 | + // Validate MIME type |
| 29 | + if (!ALLOWED_MIME_TYPES.includes(mimetype)) { |
| 30 | + throw new BadRequestException( |
| 31 | + `Invalid file type: ${mimetype}. Only JPEG, PNG, and WebP are allowed.`, |
| 32 | + ); |
| 33 | + } |
| 34 | + |
| 35 | + // Validate file extension |
| 36 | + if (!ALLOWED_EXTENSIONS.includes(extension)) { |
| 37 | + throw new BadRequestException( |
| 38 | + `Invalid file extension: ${extension}. Only .jpg, .jpeg, .png, and .webp are allowed.`, |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + const chunks: Buffer[] = []; |
| 43 | + let fileSize = 0; |
| 44 | + |
| 45 | + // Read file stream and check size |
| 46 | + for await (const chunk of createReadStream()) { |
| 47 | + fileSize += chunk.length; |
| 48 | + if (fileSize > MAX_FILE_SIZE) { |
| 49 | + throw new BadRequestException( |
| 50 | + 'File size exceeds the maximum allowed limit (5MB).', |
| 51 | + ); |
| 52 | + } |
| 53 | + chunks.push(chunk); |
| 54 | + } |
| 55 | + |
| 56 | + return { buffer: Buffer.concat(chunks), mimetype }; |
| 57 | +} |
0 commit comments