Skip to content

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

  1. 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 limit and skip.
      • Returns a JSON response with user data, total pages, current page, and total user count.
  2. 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 NotFoundError if the user is not found.
      • Returns user data in JSON format.
  3. updateUser(req, res):

    • Purpose: Updates user information.
    • Parameters:
      • req.params.id: User ID.
      • req.body: Contains updated user data.
    • Implementation:
      • Validates input data against editUserSchema using jsonschema.
      • Uses UserModel.findOneAndUpdate() for updating user data.
      • Throws NotFoundError if the user doesn’t exist.
      • Excludes password from the response.
      • Returns updated user data.
  4. deleteUser(req, res):

    • Purpose: Deletes a user by ID.
    • Parameters:
      • req.params.id: User ID.
    • Implementation:
      • Uses UserModel.findByIdAndDelete() to remove the user.
      • Throws NotFoundError if the user is not found.
      • Returns a success message upon deletion.

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.