Capstone-backup / src /utils /profileImage.js
MisbahKhan0009
feat: add reminders service for managing medication reminders and occurrences
4d27410
Raw
History Blame Contribute Delete
1.34 kB
const HttpError = require('./httpError');
const MAX_PROFILE_IMAGE_BYTES = 2 * 1024 * 1024;
const PROFILE_IMAGE_PATTERN =
/^data:image\/(png|jpe?g|webp);base64,([A-Za-z0-9+/=]+)$/i;
function normalizeProfileImageDataUrl(rawValue) {
if (rawValue === undefined) {
return undefined;
}
if (rawValue === null || String(rawValue).trim() === '') {
return null;
}
const normalizedValue = String(rawValue).trim();
const match = normalizedValue.match(PROFILE_IMAGE_PATTERN);
if (!match) {
throw new HttpError(
400,
'profileImageUrl must be a valid base64 data URL (png, jpg, jpeg, webp).',
'INVALID_PROFILE_IMAGE',
);
}
const fileFormat = String(match[1] || '').toLowerCase();
const canonicalFormat = fileFormat === 'jpg' ? 'jpeg' : fileFormat;
const imageBuffer = Buffer.from(match[2], 'base64');
if (!imageBuffer.length) {
throw new HttpError(
400,
'profileImageUrl contains empty image data.',
'INVALID_PROFILE_IMAGE',
);
}
if (imageBuffer.length > MAX_PROFILE_IMAGE_BYTES) {
throw new HttpError(
413,
'Profile image must be 2 MB or smaller.',
'PROFILE_IMAGE_TOO_LARGE',
);
}
return `data:image/${canonicalFormat};base64,${imageBuffer.toString('base64')}`;
}
module.exports = {
normalizeProfileImageDataUrl,
};