1

Ok, there's a bunch of stuff here... But basically, I'm trying to make a MVC type API in Node with Knexjs querying my database.

My goal was to have my requests enter my router, then pass to a controller, and then finally the controller calls the model methods.

The big problem I'm having is getting my data out of the model WITHOUT using a callback. I'm hoping to avoid callbacks nested in callbacks etc. My hope is that the model just fetches data using Knexjs and returns it.

Ok, so the code.

First: my routes/index.js

app.use('/users', users);

Easy enough, it loads the users sub route and inside routes/users/index.js I handle the various REST requests... in the code below getUsers is a method, defined in my users controller.

router.get('/', getUsers);

Controller users controllers/users.js

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

const getUsers = (req, res) => {
  // call the model and get the Users
  Users.getAll((response) => {
    res.status(200).json(response);
  });
};

module.exports = { getUsers };

And the model models/users.js

const knex = require('knex')(require('../../knexfile'));

const getAll = function (callback) {
  knex('users')
    .select('id', 'email')
    .then((users) => {
      callback(users);
    })
    .catch((err) => {
      callback({
        success: false,
        message: 'An error occurred, please try again later.',
        error: err,
      });
    });
};

module.exports = { getAll };

OK, here's the big question... How can I modify this model such that it just returns the users so that inside the controller, instead of passing a callback, I can just receive the users such as:

let users = Users.getAll();
res.status(200).json(users);

Last note, I might be way off on my structure logic here, and I'm open to suggestions. But my goal was to have the model be useable from other controllers so that's why I'm not doing the database call directly from the controller. IE. what if another controller or route needed to fetch all users, having the model allows that code to be managed in one location.

Nathan Leggatt
  • 398
  • 1
  • 6
  • 18

0 Answers0