fix(common): improve error handling in FileTypeValidator

Add warning logs when file-type package fails to load due to ESM
import issues. This helps users debug issues when running tests
with Jest without --experimental-vm-modules flag.

When loading fails and fallbackToMimetype is enabled, the validator
now correctly falls back to mimetype comparison instead of silently
returning false.

Closes #15055
This commit is contained in:
evgeniy.chernomortsev
2025-12-17 10:32:25 +04:00
parent da792d7c2b
commit c97b2ce4fe

View File

@@ -1,7 +1,10 @@
import { Logger } from '../../services/logger.service';
import { FileValidator } from './file-validator.interface';
import { IFile } from './interfaces';
import { loadEsm } from 'load-esm';
const logger = new Logger('FileTypeValidator');
export type FileTypeValidatorOptions = {
fileType: string | RegExp;
@@ -103,7 +106,27 @@ export class FileTypeValidator extends FileValidator<
return !!file.mimetype.match(this.validationOptions.fileType);
}
return false;
} catch {
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
// Check for common ESM loading issues
if (
errorMessage.includes('ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING') ||
errorMessage.includes('Cannot find module') ||
errorMessage.includes('ERR_MODULE_NOT_FOUND')
) {
logger.warn(
`Failed to load "file-type" package for magic number validation. ` +
`If using Jest, run with NODE_OPTIONS="--experimental-vm-modules". ` +
`Error: ${errorMessage}`,
);
}
// Fallback to mimetype if enabled
if (this.validationOptions.fallbackToMimetype) {
return !!file.mimetype.match(this.validationOptions.fileType);
}
return false;
}
}