从服务器控制器访问 MEANjs 中的 API 端点 [英] Access API endpoints in MEANjs from server controller

查看:28
本文介绍了从服务器控制器访问 MEANjs 中的 API 端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到了这个问题,我正在我的应用程序中处理'following' 功能.重要的是,我有两个模型:

so i have this problem i am working on 'following' feature in my application. What's important, i have two models:

FollowsNotifications

当我点击前端的关注按钮时,我从 follow.client.controller.js 运行函数,该函数 POST 到 API 端点 /api/follows 对应于 follow.server.controller.js 然后在 Follows 模型上执行更新操作 - 很简单.AFAIK 这就是它的工作原理(它对我有用).

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).

但是在 follows.server.controller.js 中,我还想在 /api/notifications 处调用 API 端点,它对应于 notifications.server.controller.js 但我找不到合适的方法来做到这一点.任何帮助将不胜感激.

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.

推荐答案

您可以在服务器路由中添加中间件.

You can add middleware in your server route.

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

现在在您的控制器中添加 2 个方法.首先调用 db 并将一些结果的数据添加到请求对象中,该对象将被转发到第二个方法.

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) {
    //...
};

或者您可以在一个 api 方法中进行几次数据库调用,并使用 Promise 加入此调用.示例:

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

这篇关于从服务器控制器访问 MEANjs 中的 API 端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆