|
| 1 | +import { BadRequestException } from '@nestjs/common'; |
| 2 | + |
| 3 | +export const ALLOWED_MIME_TYPES = { |
| 4 | + IMAGE: ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], |
| 5 | + ALL: [] as string[], |
| 6 | +}; |
| 7 | + |
| 8 | +export const FILE_UPLOAD_TYPE = { |
| 9 | + PROFILE_IMAGE: 'profileImg', |
| 10 | +} as const; |
| 11 | + |
| 12 | +export type FileUploadType = keyof typeof FILE_UPLOAD_TYPE; |
| 13 | + |
| 14 | +ALLOWED_MIME_TYPES.ALL = [...ALLOWED_MIME_TYPES.IMAGE]; |
| 15 | + |
| 16 | +export const FILE_SIZE_LIMITS = { |
| 17 | + // MB 단위 |
| 18 | + IMAGE: 5 * 1024 * 1024, |
| 19 | + DEFAULT: 10 * 1024 * 1024, |
| 20 | +}; |
| 21 | + |
| 22 | +export const validateFile = (file: any, uploadType: string) => { |
| 23 | + let allowedTypes: string[] = []; |
| 24 | + if (uploadType === 'PROFILE_IMAGE') { |
| 25 | + allowedTypes = ALLOWED_MIME_TYPES.IMAGE; |
| 26 | + } |
| 27 | + |
| 28 | + validateFileType(file, allowedTypes); |
| 29 | + validateFileSize(file, uploadType); |
| 30 | +}; |
| 31 | + |
| 32 | +const validateFileType = (file: any, allowedTypes?: string[]) => { |
| 33 | + const types = allowedTypes || []; |
| 34 | + |
| 35 | + if (!types.includes(file.mimetype)) { |
| 36 | + throw new BadRequestException( |
| 37 | + `지원하지 않는 파일 형식입니다. 지원 형식: ${types.join(', ')}`, |
| 38 | + ); |
| 39 | + } |
| 40 | +}; |
| 41 | + |
| 42 | +const validateFileSize = (file: any, uploadType: string) => { |
| 43 | + let sizeLimit: number; |
| 44 | + |
| 45 | + if (uploadType === 'PROFILE_IMAGE') { |
| 46 | + sizeLimit = FILE_SIZE_LIMITS.IMAGE; |
| 47 | + } else { |
| 48 | + sizeLimit = FILE_SIZE_LIMITS.DEFAULT; |
| 49 | + } |
| 50 | + |
| 51 | + if (file.size > sizeLimit) { |
| 52 | + throw new BadRequestException( |
| 53 | + `파일 크기가 너무 큽니다. 최대 ${Math.round(sizeLimit / 1024 / 1024)}MB까지 허용됩니다.`, |
| 54 | + ); |
| 55 | + } |
| 56 | +}; |
0 commit comments