从服务器控制器MEANjs访问API端点 [英] 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:
跟随
和通知
当我打到按照前端按钮,我从运行功能 follow.client.controller.js
哪些职位到API端点 / API /如下
相当于 follow.server.controller.js
,然后更新操作执行
执行模式 - 简单。据我所知,多数民众赞成它是如何工作(和它的作品对我来说)。
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.server.controller.js
,但我不能找到一个妥善的办法做到这一点。任何帮助将AP preciated。
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);
现在在你的contollers添加2种方法。首先会调用数据库,并添加的一些结果的数据请求将被转发到第二个方法的对象。
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的方法使一些数据库调用,参加此呼吁与承诺。例如:
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 < 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屋!