Search code examples
javascriptpostgresqlexpresspromisepg-promise

How to return pg-promise's result back to my controller in Express?


As I know in RoR, the MVC concept, my controller should get the result from model and after handeling it and render the view, something like this:

 def index
    @movies = Movie.all
    if params[:title] || params[:director]
      @movies = Movie.search(params)
    end
  end 

Now I have an Express server, and I try to structure it in MVC way, using PostgreSQL(pg-promise) and jade.

Currently, I have a controller file with a code as below:

//Get home page 
var router = express.Router();
 router.get('/', function(req, res, next) { 
  Movies.all(res); 
 }); 

And in my model, I have an all function to handle it:

exports.all = function(res){
  var result = db.query('select * from movies').
    then(function (data) {
    // success;
    res.render('index',{title: 'Rotten Mango', movies: data} );
  })
    .catch(function (error) {
      // error;
      console.log('error !')
    });
};

But what I want to do is to return the Movies.all's database query result back to my controller like we did in RoR usually or typical MVC way. I imagine something would be like this:

//Get home page 
var router = express.Router();
 router.get('/', function(req, res, next) { 
    // This code will return the JSON result and render into the view page
    res.render('index', Movies.all );
 }); 

But because this will return an promise or caused by Async ( I am not sure), so I can't make it happen, how could I do?


Solution

  • I would do it like this and not pass res around as that will make testing hard.

    exports.all = function(){
       return db.query('select * from movies')
    }
    

    And in your controller

     router.get('/', function(req, res, next) { 
      Movies.all()
      .then(function(data) { res.send(data); })
      .catch(function(err) { res.status(500).send(err) }) 
     });