Home > Mobile >  Two index in same controller
Two index in same controller

Time:07-27

I'm doing a CRUD using NodeJS Express Sequelize. I need to create two GET, one for listing all users (using /users), and other for listing all informations of a specific user (using /users/:id). I've already done the first GET by adding this route:

routes.get('/users', UsersController.index);

And creating the controller:

const Users = require('../models/Users')

module.exports = {
  async index(req, res) {
    const users = await Users.findAll();

    return res.json(users);

  },

Now I need to create the second one. I already created the route:

routes.get('/users/:users_id', UsersController.index);

But I don't know how I can have two index methods in my controller.

Any help?

CodePudding user response:

If you have multiple controller function in the same file, you have to export them under different name, like the example below, the exported functions are called getUsers and getUserByID respectively. Hope this help.

UsersController file

const Users = require('../models/Users') 
module.exports = {
  async getUsers(req, res) {
    const users = await Users.findAll();
    return res.json(users);
  },
  async getUserByID(req, res) {
    const user = await Users.findOne({"_id": req.params.users_id});
    return res.json(user );
  },
}

main file

routes.get('/users', UsersController.getUsers);
routes.get('/users/:users_id', UsersController.getUserByID);
  • Related