File size: 1,810 Bytes
a271c58 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | import {
BadRequestException,
Injectable,
PipeTransform,
} from '@nestjs/common';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { fromBuffer } = require('file-type');
const ALLOWED_MIME_TYPES = new Set<string>([
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
'image/avif',
'image/bmp',
'image/tiff',
'video/mp4',
]);
@Injectable()
export class CustomFileValidationPipe implements PipeTransform {
async transform(value: any) {
if (!value || typeof value !== 'object') {
return value;
}
// Skip non-file parameters (org, body, query, etc.)
if (!('buffer' in value) && !('mimetype' in value) && !('fieldname' in value)) {
return value;
}
if (!value.buffer || !Buffer.isBuffer(value.buffer)) {
throw new BadRequestException('Invalid file upload.');
}
const detected = await fromBuffer(value.buffer);
if (!detected || !ALLOWED_MIME_TYPES.has(detected.mime)) {
throw new BadRequestException('Unsupported file type.');
}
const maxSize = getMaxSize(detected.mime);
if (value.size > maxSize) {
throw new BadRequestException(
`File size exceeds the maximum allowed size of ${maxSize} bytes.`
);
}
value.mimetype = detected.mime;
const safeBase = (value.originalname || 'upload')
.replace(/\.[^./\\]*$/, '')
.replace(/[\\/]/g, '_')
.slice(0, 100) || 'upload';
value.originalname = `${safeBase}.${detected.ext}`;
return value;
}
}
export function getMaxSize(mimeType: string): number {
if (mimeType.startsWith('image/')) {
return 10 * 1024 * 1024; // 10 MB
} else if (mimeType.startsWith('video/')) {
return 1024 * 1024 * 1024; // 1 GB
} else {
throw new BadRequestException('Unsupported file type.');
}
}
|