create-bodhi-node-boilerplate
Version:
Create a Node.js project with basic folder structure and server setup
84 lines (73 loc) • 2.56 kB
JavaScript
// Example user controller
const User = require('../models/userModel');
const bcrypt = require('bcryptjs');
const userController = {
getProfile: async (req, res) => {
try {
res.json({ message: 'User profile endpoint' });
} catch (error) {
res.status(500).json({ error: error.message });
}
},
// Update user profile
updateProfile: async (req, res) => {
try {
const updates = {
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
username: req.body.username
};
// Remove undefined fields
Object.keys(updates).forEach(key =>
updates[key] === undefined && delete updates[key]
);
// Check if email or username already exists
if (updates.email || updates.username) {
const existingUser = await User.findOne({
$and: [
{ _id: { $ne: req.user._id } },
{
$or: [
{ email: updates.email },
{ username: updates.username }
]
}
]
});
if (existingUser) {
return res.status(400).json({
error: 'Email or username already in use'
});
}
}
// Update password if provided
if (req.body.password) {
const salt = await bcrypt.genSalt(10);
updates.password = await bcrypt.hash(req.body.password, salt);
}
// Update user
const user = await User.findByIdAndUpdate(
req.user._id,
updates,
{ new: true, runValidators: true }
);
res.json({
message: 'Profile updated successfully',
user
});
} catch (error) {
res.status(500).json({ error: error.message });
}
},
// Delete user account
deleteAccount: async (req, res) => {
try {
await User.findByIdAndDelete(req.user._id);
res.json({ message: 'Account deleted successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
}
};
module.exports = userController;