Access API endpoints in MEANjs from server controller

耗尽温柔 提交于 2019-12-11 17:04:12

问题


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 I run function from follow.client.controller.js which POSTs to API endpoint /api/follows which corresponds to follow.server.controller.js and then update action on Follows model is performed - easy. AFAIK thats how it works (and it works for me).

But in follows.server.controller.js I want also invoke post to API endpoint at /api/notifications which corresponds to notifications.server.controller.js but I can't find a proper way to do that. Any help will be appreciated.

I don't want another call from front-end to add notification because it should be automatic = if user starts following someone, information is saved in both models at once.


回答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);
});


来源:https://stackoverflow.com/questions/28138498/access-api-endpoints-in-meanjs-from-server-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!