refactor: Extract shared multer/upload config from routes
Create src/config/upload.js with createUpload() factory and shared ALLOWED_FILE_TYPES constant. Replace duplicated multer configs in 5 route files with calls to the shared factory. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
62
src/config/upload.js
Normal file
62
src/config/upload.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import multer from 'multer';
|
||||
import path from 'path';
|
||||
import fs from 'fs';
|
||||
|
||||
export const ALLOWED_FILE_TYPES = [
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-powerpoint',
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'image/jpeg',
|
||||
'image/png',
|
||||
'image/gif',
|
||||
'image/webp',
|
||||
'text/plain',
|
||||
'text/csv',
|
||||
];
|
||||
|
||||
function createFileFilter(allowedTypes, errorMessage) {
|
||||
return (req, file, cb) => {
|
||||
if (allowedTypes.includes(file.mimetype)) {
|
||||
cb(null, true);
|
||||
} else {
|
||||
cb(new Error(errorMessage));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createDiskStorage(uploadsDir) {
|
||||
if (!fs.existsSync(uploadsDir)) {
|
||||
fs.mkdirSync(uploadsDir, { recursive: true });
|
||||
}
|
||||
|
||||
return multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, uploadsDir);
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
const sanitized = path.basename(file.originalname).replace(/[^a-zA-Z0-9._-]/g, '_');
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
cb(null, uniqueSuffix + '-' + sanitized);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function createUpload({ maxSizeMB = 20, allowedTypes, errorMessage, diskPath } = {}) {
|
||||
const opts = {
|
||||
storage: diskPath ? createDiskStorage(diskPath) : multer.memoryStorage(),
|
||||
limits: { fileSize: maxSizeMB * 1024 * 1024 },
|
||||
};
|
||||
|
||||
if (allowedTypes) {
|
||||
opts.fileFilter = createFileFilter(
|
||||
allowedTypes,
|
||||
errorMessage || 'Nepovolený typ súboru.',
|
||||
);
|
||||
}
|
||||
|
||||
return multer(opts);
|
||||
}
|
||||
Reference in New Issue
Block a user