Reputation: 2353
The app has two models: users and posts. A viewing user can like (upvote) a post that is written by another user. So, I need to
On a high level, I can't figure out a particularly appealing option to handle this. If I make three separate api routes, then when viewing user likes a post, three separate calls are made to the server and database.
On the other hand, if I have only one api route, it seems like it would be doing way too much. In addition, I believe I would have two nested database calls:
//Pseudocode
User.findById... // update the viewing user
Post.findById... // update the post
User.findById... // update the author user
I'm using express so I don't believe I can chain these one right after another (Is this what Koa allows you to do?). I can only return one response object.
How should I do this?
Upvotes: 0
Views: 192
Reputation: 1693
I think this is more of what you are looking for. I have not tested this. I'm not entirely sure the rethrowError is needed but as a precaution I put it in until you can do some testing.
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 ************
Upvotes: 1