controllers/userController.js

PHOTO EMBED

Fri Apr 14 2023 09:11:10 GMT+0000 (Coordinated Universal Time)

Saved by @mindplumber #javascript #uuid #guid

// controllers/userController.js

const userModel = require('../models/userModel');

// Define route handling functions
function getAllUsers(req, res) {
  const users = userModel.getAllUsers();
  res.json(users);
}

function getUserById(req, res) {
  const id = req.params.id;
  const user = userModel.getUserById(id);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.json(user);
  }
}

function createUser(req, res) {
  const newUser = req.body;
  const user = userModel.createUser(newUser);
  res.status(201).json(user);
}

function updateUser(req, res) {
  const id = req.params.id;
  const updatedUser = req.body;
  const user = userModel.updateUser(id, updatedUser);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.json(user);
  }
}

function deleteUser(req, res) {
  const id = req.params.id;
  const user = userModel.deleteUser(id);
  if (!user) {
    res.status(404).send('User not found');
  } else {
    res.send('User deleted successfully');
  }
}

// Export route handling functions
module.exports = {
  getAllUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser
};
content_copyCOPY

In a typical MVC architecture, the controllers folder contains modules that define the behavior of your application's routes. These modules are responsible for processing requests from the client and generating responses. Here are some guidelines on what typically goes into a controllers folder: 1. **Route handling logic**: Each module in the controllers folder should handle the logic for a specific route or group of related routes. For example, you might have a module called userController.js that handles requests related to user accounts, such as GET /users, GET /users/:id, POST /users, PUT /users/:id, and DELETE /users/:id. 2. **Validation**: Controllers may also contain validation logic to ensure that requests are well-formed and contain the required parameters. For example, the POST /users route might require that the request body contains a username, password, and email address. The userController.js module would be responsible for checking that these fields are present and valid. 3. **Integration with models**: Controllers may also interact with models to retrieve or modify data. For example, the GET /users/:id route might require retrieving user data from a database. The userController.js module would interact with a userModel.js module to perform the necessary database queries. Overall, the controllers folder contains the logic that governs how your application handles incoming requests and generates responses. By separating this logic into separate modules, you can keep your code organized and easier to maintain.