Re_Backend/src/controllers/userPreference.controller.ts

109 lines
3.2 KiB
TypeScript

import { Request, Response } from 'express';
import { UserModel } from '../models/mongoose/User.schema';
import { updateNotificationPreferencesSchema } from '@validators/userPreference.validator';
import logger from '@utils/logger';
/**
* Get current user's notification preferences
*/
export const getNotificationPreferences = async (req: Request, res: Response): Promise<void> => {
try {
const userId = req.user!.userId;
const user = await UserModel.findOne({ userId });
if (!user) {
res.status(404).json({
success: false,
message: 'User not found'
});
return;
}
logger.info(`[UserPreference] Retrieved notification preferences for user ${userId}`);
res.json({
success: true,
data: {
emailNotificationsEnabled: user.notifications?.email ?? true,
pushNotificationsEnabled: user.notifications?.push ?? true,
inAppNotificationsEnabled: user.notifications?.inApp ?? true
}
});
} catch (error: any) {
logger.error('[UserPreference] Failed to get notification preferences:', error);
res.status(500).json({
success: false,
message: 'Failed to retrieve notification preferences',
error: error.message
});
}
};
/**
* Update current user's notification preferences
*/
export const updateNotificationPreferences = async (req: Request, res: Response): Promise<void> => {
try {
const userId = req.user!.userId;
// Validate request body
const validated = updateNotificationPreferencesSchema.parse(req.body);
const user = await UserModel.findOne({ userId });
if (!user) {
res.status(404).json({
success: false,
message: 'User not found'
});
return;
}
// Update only provided fields in nested notifications object
if (!user.notifications) {
user.notifications = { email: true, push: true, inApp: true };
}
if (validated.emailNotificationsEnabled !== undefined) {
user.notifications.email = validated.emailNotificationsEnabled;
}
if (validated.pushNotificationsEnabled !== undefined) {
user.notifications.push = validated.pushNotificationsEnabled;
}
if (validated.inAppNotificationsEnabled !== undefined) {
user.notifications.inApp = validated.inAppNotificationsEnabled;
}
await user.save();
logger.info(`[UserPreference] Updated notification preferences for user ${userId}`);
res.json({
success: true,
message: 'Notification preferences updated successfully',
data: {
emailNotificationsEnabled: user.notifications.email,
pushNotificationsEnabled: user.notifications.push,
inAppNotificationsEnabled: user.notifications.inApp
}
});
} catch (error: any) {
if (error.name === 'ZodError') {
res.status(400).json({
success: false,
message: 'Validation failed',
error: error.errors.map((e: any) => e.message).join(', ')
});
return;
}
logger.error('[UserPreference] Failed to update notification preferences:', error);
res.status(500).json({
success: false,
message: 'Failed to update notification preferences',
error: error.message
});
}
};