Search code examples
jsonnode.jsrestsails.jssails-mongo

How to Query Friends Posts In Rest API for a specific Route


I am working in SailsJS and I am attempting to build a REST API back-end for my mobile app that allows for a Newsfeed path so that if I query JSON on the front-end I can get it all from www.website.com/user/id/Newsfeed. Where the Controller gets each user's friends and their posts and displays it in JSON chronologically on that route. I am coming from an objective-C background so bear with my newbie-ness.

config/routes.js

module.exports.routes = {

  '/': {
    view: 'homepage'
  },

    'get /user/:id/newsfeed': {
    controller: 'UserController',
    action: 'newsfeed'
  }

};

Model/User.js

var User = module.exports = {
    //User attributes
    attributes: {
        facebookId: 'string',
        accessToken: 'string',
        location: 'string',
        email: 'string',
        first_name: 'string',
        last_name: 'string',
        about: {
            interests: 'string',
            goals: 'strings',
            headline: 'string',
            birthday: 'date'
        },
        friends : {
            type: 'json'
        },
        posts: {
            collection: 'posts',
            via: 'user'
        },
        picture: 'string'
    }   
};

controllers/UserControllers.js

module.exports = {

    newsfeed: function(req, res) {
        var userId = req.session.id.friends;
        sails.log("Searching for user's friends: "+ userId);

        User.find({ where: { userId: { equals: userId}}}).exec(function(err, records) {
            if(records && records.length == 0) {
                sails.log("No friends found for user:" + userId);
                sails.log(err);
                return res.json(404, "No Friends Found :'(, you'll have alot soon!  You're too cool not to.");
            } else {
                var friendsPostsArray = [];
                    for (i = 0; i < records.length; i++) {
                        var friendsPosts =records[i].posts;
                        friendsPostsArray.push(friendsPosts);
                    }
                var uniquePosts = friendsPostsArray.filter(function (item, i , ar) {
                    return ar.indexOf(item) === i;
                });
                uniquePosts.sort();
                sails.log(uniquePosts);
                sails.log("Returning" + records.length + "friends found for user:" + userId);
                return res.json(200, {friends: records, posts: uniquePosts});

            }
        });
    }
 };

Solution

  • Seems as though you should be storing friends as a collection of Users in the model:

    friends: {
      collection: 'user',
      via: 'id'
    }
    

    And in your controller, populate your query with their friends and posts like so:

    newsfeed: function (req, res) {
      var userId = req.param('id');
      sails.log("Searching for user's friends: " + userId);
    
      User.find({ userId: userId })
        .populate('friends')
        .populate('posts')
        .exec(function (err, found) {
          /* Now we have a list of friends, we can find their posts */
          User.find({ userId: found.friends })
            .populate('posts')
            .exec(function (err, found) {
              /* Process friends posts here */
            });
        });
    }
    

    EDIT: Added the code needed to populate friends posts too.