Files
dh-inspeccion-v2/api-v3/src/inspection-closing/inspection-signature-file.ts
T

50 lines
1.4 KiB
TypeScript

import { BadRequestException } from '@nestjs/common';
export const MAX_INSPECTION_SIGNATURE_BYTES = 1024 * 1024;
export interface UploadedInspectionSignatureFile {
originalname: string;
mimetype: string;
size: number;
buffer: Buffer;
}
export interface InspectedInspectionSignatureFile {
originalName: string;
mimeType: 'image/png';
extension: '.png';
}
export function inspectInspectionSignatureFile(
file: UploadedInspectionSignatureFile | undefined,
): InspectedInspectionSignatureFile {
if (!file?.buffer?.length) {
throw new BadRequestException({
code: 'INSPECTION_SIGNATURE_FILE_REQUIRED',
message: 'La firma manuscrita en formato PNG es obligatoria',
});
}
if (file.buffer.length > MAX_INSPECTION_SIGNATURE_BYTES) {
throw new BadRequestException({
code: 'INSPECTION_SIGNATURE_FILE_TOO_LARGE',
message: 'La firma no puede superar 1 MB',
});
}
const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
if (
file.mimetype !== 'image/png'
|| file.buffer.length < pngSignature.length
|| !file.buffer.subarray(0, pngSignature.length).equals(pngSignature)
) {
throw new BadRequestException({
code: 'INSPECTION_SIGNATURE_PNG_REQUIRED',
message: 'La firma debe ser una imagen PNG válida',
});
}
return {
originalName: (file.originalname || 'firma.png').slice(0, 255),
mimeType: 'image/png',
extension: '.png',
};
}