var express = require('express') var router = express.Router() const DB = require("./../mongoDB.js"); const Post = require("./../def/post.js"); const Notifications = require("./../notifications.js") DB.getDB.then((DB)=>{ const getProfileId = (req)=>{ return DB.ObjectID(req.cookies.profile_id || req.query.profile_id || req.body.profile_id); } router.get("/", async (req, res) => { const profileid = getProfileId(req); let posts = await DB.getFeed(profileid); return res.json(posts) }); router.get("/usr/:id", async (req, res) => { const profileId = req.params.id; const posts = await DB.getPosts(profileId); return res.json(posts) }); router.post("/", async (req, res) => { let post = { profileid: getProfileId(req), ...req.body } post.toProfile = post.toProfile ? DB.ObjectID(post.toProfile) : undefined; let postObj = new Post(post); let dbr = await DB.newPost(postObj); post = postObj.toObj(); post._id = dbr.insertedId; if(post.toProfile && post.toProfile != post.profileid){ //send email notification Notifications.youGotANewPost(post.toProfile, post.profileid, post.content) } return res.json({ status: "ok", ...post }) }); router.post("/react", async (req, res) => { let userid = getProfileId(req); let postid = req.body.postid; let reaction = { type: "like", createdAt: new Date() }; r = await DB.newReaction(postid, userid, reaction); return res.json({ status: "ok" }); }) router.post("/unreact", async (req, res) => { let userid = getProfileId(req); let postid = req.body.postid; r = await DB.removeReaction(postid, userid); console.log(r) return res.json({ status: "ok" }) }); router.post("/comment/", async (req, res) => { let profileid = getProfileId(req); let postid = req.body.postid; let content = req.body.content; let comment = { profileid: profileid, content: content, createdAt: new Date(), lastUpdated: new Date(), reactions: {} } Notifications.youGotANewPostComment(postid, profileid, content) r = await DB.newComment(postid, comment); return res.json({ status: "ok", ...comment }) }); router.post("/comment/react", async (req, res) => { let userid = getProfileId(req); let postid = req.body.postid; let commentDate = new Date(req.body.commentDate); let reaction = { type: "like", createdAt: new Date() }; r = await DB.newCommentReaction(postid, commentDate, userid, reaction); return res.json({ status: "ok" }) }); router.get("/:id", async (req, res) => { const postId = req.params.id; const post = await DB.getPost(postId); return res.json({ status: "ok", ... post }); }); }); module.exports = router