mirror of
https://github.com/kevin-DL/complete-node-bootcamp.git
synced 2026-01-14 04:04:41 +00:00
Initial commit 🚀
This commit is contained in:
86
4-natours/after-section-10/controllers/userController.js
Normal file
86
4-natours/after-section-10/controllers/userController.js
Normal file
@@ -0,0 +1,86 @@
|
||||
const User = require('./../models/userModel');
|
||||
const catchAsync = require('./../utils/catchAsync');
|
||||
const AppError = require('./../utils/appError');
|
||||
|
||||
const filterObj = (obj, ...allowedFields) => {
|
||||
const newObj = {};
|
||||
Object.keys(obj).forEach(el => {
|
||||
if (allowedFields.includes(el)) newObj[el] = obj[el];
|
||||
});
|
||||
return newObj;
|
||||
};
|
||||
|
||||
exports.getAllUsers = catchAsync(async (req, res, next) => {
|
||||
const users = await User.find();
|
||||
|
||||
// SEND RESPONSE
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
results: users.length,
|
||||
data: {
|
||||
users
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
exports.updateMe = catchAsync(async (req, res, next) => {
|
||||
// 1) Create error if user POSTs password data
|
||||
if (req.body.password || req.body.passwordConfirm) {
|
||||
return next(
|
||||
new AppError(
|
||||
'This route is not for password updates. Please use /updateMyPassword.',
|
||||
400
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// 2) Filtered out unwanted fields names that are not allowed to be updated
|
||||
const filteredBody = filterObj(req.body, 'name', 'email');
|
||||
|
||||
// 3) Update user document
|
||||
const updatedUser = await User.findByIdAndUpdate(req.user.id, filteredBody, {
|
||||
new: true,
|
||||
runValidators: true
|
||||
});
|
||||
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
data: {
|
||||
user: updatedUser
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
exports.deleteMe = catchAsync(async (req, res, next) => {
|
||||
await User.findByIdAndUpdate(req.user.id, { active: false });
|
||||
|
||||
res.status(204).json({
|
||||
status: 'success',
|
||||
data: null
|
||||
});
|
||||
});
|
||||
|
||||
exports.getUser = (req, res) => {
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message: 'This route is not yet defined!'
|
||||
});
|
||||
};
|
||||
exports.createUser = (req, res) => {
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message: 'This route is not yet defined!'
|
||||
});
|
||||
};
|
||||
exports.updateUser = (req, res) => {
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message: 'This route is not yet defined!'
|
||||
});
|
||||
};
|
||||
exports.deleteUser = (req, res) => {
|
||||
res.status(500).json({
|
||||
status: 'error',
|
||||
message: 'This route is not yet defined!'
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user