Skip to content

10. Show Posts in a News Feed

Nick Doiron edited this page Apr 25, 2016 · 1 revision

Before and after users upload their own photos, they're going to want to see posts of users that they followed. They also might want to see especially recent or popular posts. Together these parts make up what Facebook would call the "News Feed".

Getting recent posts

This is secondary in importance on the news feed, but the query is easier. We want to show users a post which was published recently, but not seconds ago (because you have an hour to un-publish). We find all users that published (published is not null) and are sorted descending by publish date, but use the $lt operator to make sure they're older than permDate, which we've calculated to be one hour ago.

async function feed (ctx) {
  var requser = ctx.req.user;
  if (requser) {
    var permDate = new Date((new Date()) - 60 * 60 * 1000);
    var publishers = await User.find({ published: { $ne: null, $lt: permDate } }).sort('-published').limit(6).exec();

    ctx.render('feed', {
      forUser: requser,
      publishers: publishers
    });
  } else {
    ctx.redirect('/');
  }
}

Getting friends' posts

Let's add in friend requests... anyone who I follow, where that follow is not a block.

Clone this wiki locally