Last active
February 7, 2022 09:10
-
-
Save 1ay1/8df33e20f9568224ceeaaf3d53a5d532 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// user_id -> int ; post_ids -> [] | |
function get_posts(user_id, post_ids) { | |
//usually we will just use an ORM here | |
let post_ids_str = "("; | |
//serialize the post_ids for the query | |
post_ids.map(val => { | |
post_ids_str += `${val.toString()}, `; | |
}) | |
post_ids_str += ")"; | |
let posts = await getFromDB("SELECT * FROM post WHERE id IN " + post_ids_str); | |
let posts_obj = {}; | |
//we have the posts now | |
//get the user_id list | |
let user_ids = posts.map(val => { | |
posts_obj[val.id] = { | |
...val | |
}; | |
return val.user_id; | |
}); | |
//serialize the user_ids for the query | |
let user_ids_str = "("; | |
user_ids.map(val => { | |
user_ids_str += `${val.toString()}, `; | |
}) | |
user_ids_str += ")"; | |
let users = await getFromDB("SELECT * FROM user WHERE id IN " + user_ids_str); | |
let users_obj = {}; | |
users.map(val => { | |
let follows = await getFromDB(`SELECT * FROM follow WHERE follower_id=${user_id} AND following_id=${val.user_id}`); | |
users_obj[val.id] = { | |
id: val.id, | |
username: val.username, | |
full_name: val.full_name, | |
profile_picture: val.profile_picture, | |
followed: follows ? true : false, | |
} | |
}) | |
//we have the users now | |
//build up the return object | |
let response = post_ids.map(val => { | |
if(!posts_obj[val]) { | |
//Procedure should place null values for non-existing posts in the resulting list. | |
return null; | |
} else { | |
let liked = await getFromDB(`SELECT * FROM like WHERE post_id=${val} AND user_id=${posts_obj[val].user_id}`); | |
return { | |
id: val, | |
description: posts_obj[val].description, | |
owner: users_obj[posts_obj[val].user_id], | |
image: posts_obj[val].image, | |
created_at: posts_obj[val].created_at, | |
liked: liked ? true : false, | |
} | |
} | |
}); | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment