Skip to content Skip to sidebar Skip to footer

Access API Endpoints In MEANjs From Server Controller

so i have this problem i am working on 'following' feature in my application. What's important, i have two models: Follows and Notifications When I hit follow button in front-end

Solution 1:

You can add middleware in your server route.

app.route('/api/follows')
    .post(notification.firstFunction, follows.secondFunction);

And now add 2 methods in your contollers. First makes the call to db and add's some result's data to request object which will be forwarded to second method.

exports.firstFunction= function(req, res, next) {

    Notification.doSometing({
        }).exec(function(err, result) {
            if (err) return next(err);
            req.yourValueToPassForward = result
            next(); // <-- important
        });

};

exports.secondFunction= function(req, res) {
    //...
};

Or you can make few database calls in one api method, joining this calls with promises. Example:

var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
promise.then(function (meetups) {
  var ids = meetups.map(function (m) {
    return m._id;
  });
  return People.find({ meetups: { $in: ids }).exec();
}).then(function (people) {
  if (people.length &lt; 10000) {
    throw new Error('Too few people!!!');
  } else {
    throw new Error('Still need more people!!!');
  }
}).then(null, function (err) {
  assert.ok(err instanceof Error);
});

Post a Comment for "Access API Endpoints In MEANjs From Server Controller"