该应用有两种型号:用户和帖子。观看用户可以喜欢(upvote)由另一个用户写的帖子。所以,我需要
从较高的层面来说,我无法找到一个特别吸引人的选择来处理这个问题。如果我制作三个单独的api路由,那么当查看用户喜欢帖子时,会对服务器和数据库进行三次单独的调用。
另一方面,如果我只有一条api路线,那么它似乎会做得太多。另外,我相信我会有两个嵌套的数据库调用:
//Pseudocode
User.findById... // update the viewing user
Post.findById... // update the post
User.findById... // update the author user
我使用快递,所以我不相信我可以将这一个连接起来(这是Koa允许你做的吗?)。我只能返回一个响应对象。
我该怎么做?
答案 0 :(得分:1)
我认为这更像是你在寻找的东西。我没有测试过这个。我不完全确定需要rethrowError,但作为预防措施,我将其放入,直到您可以进行一些测试。
export function update(req, res) {
updateUserById(req.params.voterId, res, userUpvoted(req.params.postId))
.then(updatePostById(req.params.postId, res, postLikedBy(req.params.voterId)))
.then(updateUserById(req.params.authorId, res, userRecivedLike(req.params.voterId))
.then(handleEntityNotFound(res))
.then(responseWithResult(res))
.catch(handleError(res));
}
// ************ Update Functions ************
function userUpvoted(postId) {
return function(user) {
// update the user's upVotes
return user;
}
}
function postLikedBy(userId) {
return function(post) {
// update the post's upVotes
return post;
}
}
function userRecivedLike() {
return function(entity) {
// update the post's upVotes with the entity object
return entity;
}
}
// ************ End Update Functions ************
// ************ UpdateBy using using callback Functions ************
function updateUserById(id, res, updateFunction) {
return User.findById(id)
.then(updateFunction(res))
.catch(rethrowError);
}
function updatePostById(id, res, updateFunction) {
return Post.findById(id)
.then(updateFunction(res))
.catch(rethrowError);
}
// ************ end UpdateBy using using callback Functions ************
// ************ Helper Functions ************
function rethrowError(err) {
throw err;
}
// ************ End Helper Functions ************