angularjssails.jswaterlinesails-postgresql

Is there a way to query multiple tables at the same time in Sails?


I've been tasked with adding an Angular Typeahead search field to a site and the data needs to come from multiple tables. It needs to be a "search all the things" kind of query which looks for people, servers, and applications in one spot.

I was thinking the best way to do this would be to have a single API endpoint in Sails which could pull from 3 tables on the same DB and send the results, but I'm not quite sure how to go about it.


Solution

  • Use the built-in bluebird library, specifically Promise.all(). To handle the results, use .spread(). Example controller code (modify to suit your case):

    var Promise = require('bluebird');
    
    module.exports = {
    
        searchForStuff: function(req, res) {
            var params = req.allParams();
            // Replace the 'find' criteria with whatever suitable for your case
            var requests = [
                Person.find({name: params.searchString}),
                Server.find({name: params.searchString}),
                Application.find({name: params.searchString})
            ];
            Promise.all(requests)
            .spread(function(people, servers, applications) {
                return res.json({
                    people: people,
                    servers: servers,
                    applications: applications
                })
            })
        }
    
    }