80 lines
1.9 KiB
JavaScript
80 lines
1.9 KiB
JavaScript
|
import User from '../models/User.js'
|
||
|
import asyncHandler from '../middleware/async.js'
|
||
|
import ErrorResponse from '../utils/errorResponse.js'
|
||
|
|
||
|
// @desc Get all users
|
||
|
// @route GET /api/admin/users
|
||
|
// @access Private/Admin
|
||
|
export const getUsers = asyncHandler(async (req, res, next) => {
|
||
|
res.status(200).json({
|
||
|
success: true,
|
||
|
data: res.advancedResults,
|
||
|
})
|
||
|
})
|
||
|
|
||
|
// @desc Get single user
|
||
|
// @route GET /api/admin/users/:id
|
||
|
// @access Private/Admin
|
||
|
export const getUser = asyncHandler(async (req, res, next) => {
|
||
|
console.log('reached route.')
|
||
|
const user = await User.findById(req.params.id)
|
||
|
|
||
|
res.status(200).json({
|
||
|
success: true,
|
||
|
data: user,
|
||
|
})
|
||
|
})
|
||
|
|
||
|
// @desc Create user
|
||
|
// @route POST /api/admin/users
|
||
|
// @access Private/Admin
|
||
|
export const createUser = asyncHandler(async (req, res, next) => {
|
||
|
const user = await User.create(req.body)
|
||
|
|
||
|
res.status(201).json({
|
||
|
success: true,
|
||
|
data: user,
|
||
|
})
|
||
|
})
|
||
|
|
||
|
// @desc Update user
|
||
|
// @route PUT /api/admin/users/:id
|
||
|
// @access Private/Admin
|
||
|
export const updateUser = asyncHandler(async (req, res, next) => {
|
||
|
const { password, ...updateFields } = req.body
|
||
|
|
||
|
let user = await User.findById(req.params.id).select('+password')
|
||
|
|
||
|
if (!user)
|
||
|
return next(new ErrorResponse('User does not exist in database', 404))
|
||
|
|
||
|
await user.updateOne(updateFields, {
|
||
|
runValidators: true,
|
||
|
})
|
||
|
|
||
|
if (password) {
|
||
|
user.password = password
|
||
|
await user.save()
|
||
|
user = await User.findById(req.params.id).select('+password')
|
||
|
} else {
|
||
|
user = await User.findById(req.params.id)
|
||
|
}
|
||
|
|
||
|
res.status(200).json({
|
||
|
success: true,
|
||
|
data: user,
|
||
|
})
|
||
|
})
|
||
|
|
||
|
// @desc Delete user
|
||
|
// @route DELETE /api/admin/users/:id
|
||
|
// @access Private/Admin
|
||
|
export const deleteUser = asyncHandler(async (req, res, next) => {
|
||
|
await User.findByIdAndDelete(req.params.id)
|
||
|
|
||
|
res.status(200).json({
|
||
|
success: true,
|
||
|
data: {},
|
||
|
})
|
||
|
})
|