gpt4 book ai didi

json - 如何在 Rest API 中查询特定路线的好友帖子

转载 作者:太空宇宙 更新时间:2023-11-03 22:14:26 25 4
gpt4 key购买 nike

我正在 SailsJS 工作,我正在尝试为我的移动应用程序构建一个 REST API 后端,该后端允许新闻源路径,这样如果我在前端查询 JSON,我可以从 www.website 获取所有内容.com/user/id/Newsfeed。 Controller 获取每个用户的 friend 及其帖子,并在该路线上按时间顺序以 JSON 形式显示。我有 Objective-C 背景,所以请容忍我的新手身份。

config/routes.js

module.exports.routes = {

'/': {
view: 'homepage'
},

'get /user/:id/newsfeed': {
controller: 'UserController',
action: 'newsfeed'
}

};

模型/User.js

var User = module.exports = {
//User attributes
attributes: {
facebookId: 'string',
accessToken: 'string',
location: 'string',
email: 'string',
first_name: 'string',
last_name: 'string',
about: {
interests: 'string',
goals: 'strings',
headline: 'string',
birthday: 'date'
},
friends : {
type: 'json'
},
posts: {
collection: 'posts',
via: 'user'
},
picture: 'string'
}
};

controllers/UserControllers.js

module.exports = {

newsfeed: function(req, res) {
var userId = req.session.id.friends;
sails.log("Searching for user's friends: "+ userId);

User.find({ where: { userId: { equals: userId}}}).exec(function(err, records) {
if(records && records.length == 0) {
sails.log("No friends found for user:" + userId);
sails.log(err);
return res.json(404, "No Friends Found :'(, you'll have alot soon! You're too cool not to.");
} else {
var friendsPostsArray = [];
for (i = 0; i < records.length; i++) {
var friendsPosts =records[i].posts;
friendsPostsArray.push(friendsPosts);
}
var uniquePosts = friendsPostsArray.filter(function (item, i , ar) {
return ar.indexOf(item) === i;
});
uniquePosts.sort();
sails.log(uniquePosts);
sails.log("Returning" + records.length + "friends found for user:" + userId);
return res.json(200, {friends: records, posts: uniquePosts});

}
});
}
};

最佳答案

似乎您应该将 friend 存储为模型中的用户集合:

friends: {
collection: 'user',
via: 'id'
}

在您的 Controller 中,用他们的 friend 和帖子填充您的查询,如下所示:

newsfeed: function (req, res) {
var userId = req.param('id');
sails.log("Searching for user's friends: " + userId);

User.find({ userId: userId })
.populate('friends')
.populate('posts')
.exec(function (err, found) {
/* Now we have a list of friends, we can find their posts */
User.find({ userId: found.friends })
.populate('posts')
.exec(function (err, found) {
/* Process friends posts here */
});
});
}

编辑:添加了填充 friend 帖子所需的代码。

关于json - 如何在 Rest API 中查询特定路线的好友帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com