Files
starr-philproperties/apps/api/middleware/avatar_upload.middleware.js
T

46 lines
1.8 KiB
JavaScript

/***********************************************************************************************************************************************************************
* File Name: avatar_upload.middleware.js
* Type of Program: Middleware
* Description: Multer config for avatar uploads.
* Memory storage — buffer is passed directly to S3.
* Accepts JPEG, PNG, WebP, GIF only. 5 MB limit.
*
* Author: Kenneth Obsequio (@lash0000)
* Date Created: Jun. 18, 2026
***********************************************************************************************************************************************************************/
'use strict';
const multer = require('multer');
const ALLOWED_MIME = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB
fileFilter(req, file, cb) {
if (ALLOWED_MIME.has(file.mimetype)) return cb(null, true);
cb(Object.assign(new Error('Only JPEG, PNG, WebP, or GIF images are allowed.'), { code: 'INVALID_TYPE' }));
},
});
const avatarSingle = upload.single('avatar');
// Wraps multer errors into the project's standard error shape.
const handleAvatarUpload = (req, res, next) => {
avatarSingle(req, res, (err) => {
if (!err) return next();
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(400).json({ status: 'error', message: 'Avatar must be under 5 MB.' });
}
if (err.code === 'INVALID_TYPE') {
return res.status(400).json({ status: 'error', message: err.message });
}
console.error('[MULTER AVATAR]', err);
return res.status(400).json({ status: 'error', message: err.message ?? 'Upload failed.' });
});
};
module.exports = { handleAvatarUpload };