User Controller
Documentation: User Controller Module
Overview
This User Controller module handles operations related to users in the application. It includes functions to list all users, retrieve a single user, update a user, and delete a user.
Functions
-
getAllUsers(req, res):
- Purpose: Retrieves a paginated list of users based on query parameters.
- Parameters:
req.query: Contains query parameters for pagination and filters.
- Implementation:
- Uses
UserModel.find()with filters derived from query parameters. - Supports pagination through
limitandskip. - Returns a JSON response with user data, total pages, current page, and total user count.
- Uses
-
getOneUser(req, res):
- Purpose: Fetches details of a specific user by ID.
- Parameters:
req.params.id: User ID.
- Implementation:
- Uses
UserModel.findOne()to retrieve user data. - Throws
NotFoundErrorif the user is not found. - Returns user data in JSON format.
- Uses
-
updateUser(req, res):
- Purpose: Updates user information.
- Parameters:
req.params.id: User ID.req.body: Contains updated user data.
- Implementation:
- Validates input data against
editUserSchemausingjsonschema. - Uses
UserModel.findOneAndUpdate()for updating user data. - Throws
NotFoundErrorif the user doesn’t exist. - Excludes password from the response.
- Returns updated user data.
- Validates input data against
-
deleteUser(req, res):
- Purpose: Deletes a user by ID.
- Parameters:
req.params.id: User ID.
- Implementation:
- Uses
UserModel.findByIdAndDelete()to remove the user. - Throws
NotFoundErrorif the user is not found. - Returns a success message upon deletion.
- Uses
Error Handling
- The module handles errors such as user not found, bad requests (validation errors), and internal server errors.
- Appropriate HTTP status codes and error messages are returned in the response.
Security Considerations
- The functions include validation of input data to prevent issues like injection attacks.
- Passwords are excluded from responses to enhance security.
Usage
- This module is used in the application’s routing system to handle user-related endpoints.
- The functions are invoked in response to corresponding API requests.