59 lines
1.8 KiB
JavaScript
59 lines
1.8 KiB
JavaScript
const express = require("express");
|
|
const router = express.Router();
|
|
const pool = require("../../db");
|
|
const { strictInput } = require("../../middleware/strict_input");
|
|
const { areFriends } = require("../relations/friend_graph");
|
|
const { likeDataForPosts } = require("./post_graph");
|
|
|
|
async function getPostDetail(req, res) {
|
|
try {
|
|
const { id } = req.params;
|
|
const postId = Number(id);
|
|
if (!Number.isInteger(postId) || postId <= 0) {
|
|
return res.status(400).send("Invalid post id");
|
|
}
|
|
const { rows } = await pool.query(
|
|
`SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at, people.private AS author_private
|
|
FROM posts p
|
|
LEFT JOIN people ON people.id = p.author_id
|
|
WHERE p.id = $1 AND p.active = true`,
|
|
[postId],
|
|
);
|
|
if (rows.length === 0) {
|
|
return res.status(404).send("Post not found");
|
|
}
|
|
const post = rows[0];
|
|
if (
|
|
post.author_private &&
|
|
Number(post.author_id) !== req.user.id &&
|
|
!(await areFriends(req.user.id, post.author_id))
|
|
) {
|
|
return res.status(404).send("Post not found");
|
|
}
|
|
const { author_private, ...publicPost } = post;
|
|
const likeData = (await likeDataForPosts(req.user.id, [post.id])).get(
|
|
Number(post.id),
|
|
) ?? { like_count: 0, liked_by_me: false };
|
|
return res
|
|
.status(200)
|
|
.json({
|
|
...publicPost,
|
|
comments: [],
|
|
like_count: likeData.like_count,
|
|
liked_by_me: likeData.liked_by_me,
|
|
});
|
|
} catch (err) {
|
|
console.error("post detail query failed", {
|
|
message: err.message,
|
|
code: err.code,
|
|
detail: err.detail,
|
|
hint: err.hint,
|
|
});
|
|
return res.status(500).send("Post could not be retrieved, request failed");
|
|
}
|
|
}
|
|
|
|
router.get("/:id", strictInput(), getPostDetail);
|
|
|
|
module.exports = router;
|