Posts optimization
This commit is contained in:
@@ -46,7 +46,6 @@ type User = {
|
|||||||
id: string;
|
id: string;
|
||||||
firstName: string;
|
firstName: string;
|
||||||
lastName: string;
|
lastName: string;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function CommunityPage() {
|
export default function CommunityPage() {
|
||||||
@@ -55,24 +54,30 @@ export default function CommunityPage() {
|
|||||||
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
const [selectedPost, setSelectedPost] = useState<Post | null>(null);
|
||||||
const [communityList, setCommunityList] = useState<Post[]>([]);
|
const [communityList, setCommunityList] = useState<Post[]>([]);
|
||||||
const [search, setSearch] = useState(""); // Search Function
|
const [search, setSearch] = useState(""); // Search Function
|
||||||
const [userInformation, setUserInformation] = useState<Record<string, User>>({});
|
const [userInformation, setUserInformation] = useState<Record<string, User>>(
|
||||||
|
{}
|
||||||
|
);
|
||||||
const [currentUserInfo, setCurrentUserInfo] = useState(null);
|
const [currentUserInfo, setCurrentUserInfo] = useState(null);
|
||||||
const [imageErrorFlags, setImageErrorFlags] = useState<Record<string, boolean>>({});
|
const [imageErrorFlags, setImageErrorFlags] = useState<
|
||||||
|
Record<string, boolean>
|
||||||
|
>({});
|
||||||
|
|
||||||
let accessToken = localStorage.getItem("accessToken");
|
let accessToken = localStorage.getItem("accessToken");
|
||||||
if (!accessToken) {
|
if (!accessToken) {
|
||||||
return (
|
return (
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
navigate("/signin");
|
navigate("/signin");
|
||||||
}, 1000)
|
}, 1000) && (
|
||||||
&&
|
<div className="flex justify-center items-center min-h-screen">
|
||||||
<div className="flex justify-center items-center min-h-screen">
|
<div className="text-center">
|
||||||
<div className="text-center">
|
<p className="text-xl font-bold text-primary-500">
|
||||||
<p className="text-xl font-bold text-primary-500">User is not verified</p>
|
User is not verified
|
||||||
<p className="text-md">Redirecting to sign-in page...</p>
|
</p>
|
||||||
<Spinner color="danger" />
|
<p className="text-md">Redirecting to sign-in page...</p>
|
||||||
|
<Spinner color="danger" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,7 +170,6 @@ export default function CommunityPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
const handlePostClick = (id: string) => {
|
const handlePostClick = (id: string) => {
|
||||||
navigate(`post/${id}`);
|
navigate(`post/${id}`);
|
||||||
};
|
};
|
||||||
@@ -202,17 +206,17 @@ export default function CommunityPage() {
|
|||||||
onClick={() => handlePostClick(post.id)}
|
onClick={() => handlePostClick(post.id)}
|
||||||
>
|
>
|
||||||
<div onClick={(e) => e.stopPropagation()}>
|
<div onClick={(e) => e.stopPropagation()}>
|
||||||
<Avatar
|
<Avatar src={profilePictureUrl} size="lg" />
|
||||||
src={profilePictureUrl}
|
|
||||||
size="lg"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col gap-8 w-full">
|
<div className="flex flex-col gap-8 w-full">
|
||||||
<div className="h-full flex flex-col gap-4">
|
<div className="h-full flex flex-col gap-4">
|
||||||
<div className="flex flex-row justify-between">
|
<div className="flex flex-row justify-between">
|
||||||
<div className="flex flex-col">
|
<div className="flex flex-col">
|
||||||
<p className="text-xl font-bold">{post.title}</p>
|
<p className="text-xl font-bold">{post.title}</p>
|
||||||
<p className="text-md text-neutral-500">{userInformation[post.userId]?.firstName} {userInformation[post.userId]?.lastName}</p>
|
<p className="text-md text-neutral-500">
|
||||||
|
{userInformation[post.userId]?.firstName}{" "}
|
||||||
|
{userInformation[post.userId]?.lastName}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-row-reverse justify-center items-center">
|
<div className="flex flex-row-reverse justify-center items-center">
|
||||||
<Dropdown>
|
<Dropdown>
|
||||||
@@ -252,11 +256,13 @@ export default function CommunityPage() {
|
|||||||
<div>
|
<div>
|
||||||
<p>{post.content}</p>
|
<p>{post.content}</p>
|
||||||
</div>
|
</div>
|
||||||
{!imageErrorFlags[post.id] && post.postImage && post.postImage !== null && (
|
{imageErrorFlags[post.id] ? null : (
|
||||||
<div>
|
<div>
|
||||||
<img src={`${config.serverAddress}/post/post-image/${post.id}`}
|
<img
|
||||||
|
src={`${config.serverAddress}/post/post-image/${post.id}`}
|
||||||
className="w-[300px] h-auto rounded-lg object-cover"
|
className="w-[300px] h-auto rounded-lg object-cover"
|
||||||
onError={() => handleImageError(post.id)} />
|
onError={() => handleImageError(post.id)}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
ModalHeader,
|
ModalHeader,
|
||||||
ModalBody,
|
ModalBody,
|
||||||
ModalFooter,
|
ModalFooter,
|
||||||
|
Image,
|
||||||
} from "@nextui-org/react";
|
} from "@nextui-org/react";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import instance from "../security/http";
|
import instance from "../security/http";
|
||||||
@@ -35,7 +36,7 @@ export default function CommunityPostManagement() {
|
|||||||
{ key: "title", label: "TITLE" },
|
{ key: "title", label: "TITLE" },
|
||||||
{ key: "content", label: "CONTENT" },
|
{ key: "content", label: "CONTENT" },
|
||||||
{ key: "postImage", label: "IMAGE" },
|
{ key: "postImage", label: "IMAGE" },
|
||||||
{ key: "actions", label: "ACTIONS" }
|
{ key: "actions", label: "ACTIONS" },
|
||||||
];
|
];
|
||||||
|
|
||||||
const populateUserInformationList = () => {
|
const populateUserInformationList = () => {
|
||||||
@@ -43,7 +44,7 @@ export default function CommunityPostManagement() {
|
|||||||
.get(`${config.serverAddress}/users/all`)
|
.get(`${config.serverAddress}/users/all`)
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
const users = response.data;
|
const users = response.data;
|
||||||
const usersWithProfilePictures = users.map((user: { id: string; }) => ({
|
const usersWithProfilePictures = users.map((user: { id: string }) => ({
|
||||||
...user,
|
...user,
|
||||||
profilePicture: `${config.serverAddress}/users/profile-image/${user.id}`,
|
profilePicture: `${config.serverAddress}/users/profile-image/${user.id}`,
|
||||||
}));
|
}));
|
||||||
@@ -86,12 +87,12 @@ export default function CommunityPostManagement() {
|
|||||||
userId: user?.id,
|
userId: user?.id,
|
||||||
...post,
|
...post,
|
||||||
...user,
|
...user,
|
||||||
uniqueKey: `${post.id}-${user?.id}`
|
uniqueKey: `${post.id}-${user?.id}`,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
// Remove the duplicate 'id' field from merged data
|
// Remove the duplicate 'id' field from merged data
|
||||||
const removeDuplicateId = mergedData.map(item => {
|
const removeDuplicateId = mergedData.map((item) => {
|
||||||
const { id, ...rest } = item;
|
const { id, ...rest } = item;
|
||||||
return { ...rest };
|
return { ...rest };
|
||||||
});
|
});
|
||||||
@@ -114,7 +115,9 @@ export default function CommunityPostManagement() {
|
|||||||
const handleDeleteConfirm = async () => {
|
const handleDeleteConfirm = async () => {
|
||||||
if (postToDelete) {
|
if (postToDelete) {
|
||||||
try {
|
try {
|
||||||
await instance.delete(`${config.serverAddress}/post/${postToDelete.postId}`);
|
await instance.delete(
|
||||||
|
`${config.serverAddress}/post/${postToDelete.postId}`
|
||||||
|
);
|
||||||
populateCommunityPostList();
|
populateCommunityPostList();
|
||||||
setIsModalOpen(false);
|
setIsModalOpen(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -162,12 +165,13 @@ export default function CommunityPostManagement() {
|
|||||||
"No Image"
|
"No Image"
|
||||||
)
|
)
|
||||||
) : columnKey === "postImage" ? (
|
) : columnKey === "postImage" ? (
|
||||||
value ? (
|
<div className="relative w-48">
|
||||||
<img src={`${config.serverAddress}/post/post-image/${item.postId}`}
|
<Image
|
||||||
className="w-[150px] h-auto rounded-lg object-cover"/>
|
src={`${config.serverAddress}/post/post-image/${item.postId}`}
|
||||||
) : (
|
radius="sm"
|
||||||
"No Image"
|
/>
|
||||||
)
|
<p className="absolute inset-0">No image</p>
|
||||||
|
</div>
|
||||||
) : columnKey === "actions" ? (
|
) : columnKey === "actions" ? (
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Tooltip content="Copy ID">
|
<Tooltip content="Copy ID">
|
||||||
@@ -195,11 +199,8 @@ export default function CommunityPostManagement() {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<p>
|
<p>{value}</p>
|
||||||
{value}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
</TableCell>
|
</TableCell>
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
@@ -210,17 +211,28 @@ export default function CommunityPostManagement() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} isDismissable={false} isKeyboardDismissDisabled={true}>
|
<Modal
|
||||||
|
isOpen={isModalOpen}
|
||||||
|
onClose={() => setIsModalOpen(false)}
|
||||||
|
isDismissable={false}
|
||||||
|
isKeyboardDismissDisabled={true}
|
||||||
|
>
|
||||||
<ModalContent>
|
<ModalContent>
|
||||||
<>
|
<>
|
||||||
<ModalHeader className="flex flex-col text-danger gap-1">
|
<ModalHeader className="flex flex-col text-danger gap-1">
|
||||||
{postToDelete?.title ? `DELETING POST: ${postToDelete.title}` : "Delete Post"}
|
{postToDelete?.title
|
||||||
|
? `DELETING POST: ${postToDelete.title}`
|
||||||
|
: "Delete Post"}
|
||||||
</ModalHeader>
|
</ModalHeader>
|
||||||
<ModalBody>
|
<ModalBody>
|
||||||
<p>Are you sure you want to delete this post?</p>
|
<p>Are you sure you want to delete this post?</p>
|
||||||
</ModalBody>
|
</ModalBody>
|
||||||
<ModalFooter>
|
<ModalFooter>
|
||||||
<Button color="danger" variant="light" onPress={() => setIsModalOpen(false)}>
|
<Button
|
||||||
|
color="danger"
|
||||||
|
variant="light"
|
||||||
|
onPress={() => setIsModalOpen(false)}
|
||||||
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
<Button color="danger" onPress={handleDeleteConfirm}>
|
<Button color="danger" onPress={handleDeleteConfirm}>
|
||||||
|
|||||||
@@ -1,56 +1,74 @@
|
|||||||
const express = require('express');
|
const express = require("express");
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const { Post, Comment, User } = require('../models');
|
const { Post, Comment, User } = require("../models");
|
||||||
const { Op, where } = require("sequelize");
|
const { Op, where } = require("sequelize");
|
||||||
const yup = require("yup");
|
const yup = require("yup");
|
||||||
const multer = require("multer");
|
const multer = require("multer");
|
||||||
const sharp = require("sharp");
|
const sharp = require("sharp");
|
||||||
|
|
||||||
// Profanity function
|
// Profanity function
|
||||||
const Filter = require('bad-words'); // Import the bad-words library
|
const Filter = require("bad-words"); // Import the bad-words library
|
||||||
const filter = new Filter();
|
const filter = new Filter();
|
||||||
|
|
||||||
var newBadWords = ['bloody', 'bitch', 'fucker', 'fuck', 'fk', 'shit', 'bastard', 'dumbass', 'stupid', 'hell'];
|
var newBadWords = [
|
||||||
|
"bloody",
|
||||||
|
"bitch",
|
||||||
|
"fucker",
|
||||||
|
"fuck",
|
||||||
|
"fk",
|
||||||
|
"shit",
|
||||||
|
"bastard",
|
||||||
|
"dumbass",
|
||||||
|
"stupid",
|
||||||
|
"hell",
|
||||||
|
];
|
||||||
filter.addWords(...newBadWords);
|
filter.addWords(...newBadWords);
|
||||||
|
|
||||||
let removeWords = [''];
|
let removeWords = [""];
|
||||||
filter.removeWords(...removeWords);
|
filter.removeWords(...removeWords);
|
||||||
|
|
||||||
const upload = multer({ storage: multer.memoryStorage() });
|
const upload = multer({ storage: multer.memoryStorage() });
|
||||||
|
|
||||||
router.post("/", upload.fields([{ name: 'postImage', maxCount: 1 }]), async (req, res) => {
|
router.post(
|
||||||
|
"/",
|
||||||
|
upload.fields([{ name: "postImage", maxCount: 1 }]),
|
||||||
|
async (req, res) => {
|
||||||
let data = req.body;
|
let data = req.body;
|
||||||
let files = req.files;
|
let files = req.files;
|
||||||
|
|
||||||
// Validate request body
|
// Validate request body
|
||||||
let validationSchema = yup.object({
|
let validationSchema = yup.object({
|
||||||
title: yup.string().trim().min(3).max(200).required(),
|
title: yup.string().trim().min(3).max(200).required(),
|
||||||
content: yup.string().trim().min(3).max(500).required(),
|
content: yup.string().trim().min(3).max(500).required(),
|
||||||
userId: yup.string().required(),
|
userId: yup.string().required(),
|
||||||
postImage: yup.string().trim().max(255),
|
postImage: yup.string().trim().max(255),
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
data = await validationSchema.validate(data, { abortEarly: false });
|
data = await validationSchema.validate(data, { abortEarly: false });
|
||||||
|
|
||||||
// Check for profanity
|
// Check for profanity
|
||||||
if (filter.isProfane(data.title)) {
|
if (filter.isProfane(data.title)) {
|
||||||
return res.status(400).json({ field: 'title', error: 'Profane content detected in title' });
|
return res
|
||||||
}
|
.status(400)
|
||||||
if (filter.isProfane(data.content)) {
|
.json({ field: "title", error: "Profane content detected in title" });
|
||||||
return res.status(400).json({ field: 'content', error: 'Profane content detected in content' });
|
}
|
||||||
}
|
if (filter.isProfane(data.content)) {
|
||||||
|
return res.status(400).json({
|
||||||
|
field: "content",
|
||||||
|
error: "Profane content detected in content",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let postImage = files.postImage ? files.postImage[0].buffer : null;
|
let postImage = files.postImage ? files.postImage[0].buffer : null;
|
||||||
|
|
||||||
// Process valid data
|
// Process valid data
|
||||||
let result = await Post.create({ ...data, postImage });
|
let result = await Post.create({ ...data, postImage });
|
||||||
res.json(result);
|
res.json(result);
|
||||||
|
} catch (err) {
|
||||||
|
res.status(400).json({ errors: err.errors });
|
||||||
}
|
}
|
||||||
catch (err) {
|
}
|
||||||
res.status(400).json({ errors: err.errors });
|
);
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// // sequelize method findAll is used to generate a standard SELECT query which will retrieve all entries from the table
|
// // sequelize method findAll is used to generate a standard SELECT query which will retrieve all entries from the table
|
||||||
// router.get("/", async (req, res) => {
|
// router.get("/", async (req, res) => {
|
||||||
@@ -62,64 +80,69 @@ router.post("/", upload.fields([{ name: 'postImage', maxCount: 1 }]), async (req
|
|||||||
// });
|
// });
|
||||||
|
|
||||||
router.get("/", async (req, res) => {
|
router.get("/", async (req, res) => {
|
||||||
let condition = {
|
let condition = {
|
||||||
where: {},
|
where: {},
|
||||||
order: [['createdAt', 'DESC']]
|
attributes: { exclude: ["postImage"] },
|
||||||
};
|
order: [["createdAt", "DESC"]],
|
||||||
|
};
|
||||||
|
|
||||||
let search = req.query.search;
|
let search = req.query.search;
|
||||||
if (search) {
|
if (search) {
|
||||||
condition.where[Op.or] = [
|
condition.where[Op.or] = [
|
||||||
{ title: { [Op.like]: `%${search}%` } },
|
{ title: { [Op.like]: `%${search}%` } },
|
||||||
{ content: { [Op.like]: `%${search}%` } }
|
{ content: { [Op.like]: `%${search}%` } },
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
// You can add condition for other columns here
|
// You can add condition for other columns here
|
||||||
// e.g. condition.columnName = value;
|
// e.g. condition.columnName = value;
|
||||||
|
|
||||||
let list = await Post.findAll(condition);
|
let list = await Post.findAll(condition);
|
||||||
res.json(list);
|
res.json(list);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get("/:id", async (req, res) => {
|
router.get("/:id", async (req, res) => {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
let post = await Post.findByPk(id);
|
let post = await Post.findByPk(id, {
|
||||||
// Check id not found
|
attributes: { exclude: ["postImage"] },
|
||||||
if (!post) {
|
});
|
||||||
res.sendStatus(404); // If the tutorial is null, return error code 404 for Not Found
|
if (!post) {
|
||||||
return;
|
res.sendStatus(404);
|
||||||
}
|
return;
|
||||||
res.json(post);
|
}
|
||||||
|
res.json(post);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get("/post-image/:id", async (req, res) => {
|
router.get("/post-image/:id", async (req, res) => {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
let post = await Post.findByPk(id);
|
let post = await Post.findByPk(id);
|
||||||
|
|
||||||
if (!post || !post.postImage) {
|
if (!post || !post.postImage) {
|
||||||
res.sendStatus(404);
|
res.sendStatus(404);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
res.set("Content-Type", "image/jpeg"); // Adjust the content type as necessary
|
res.set("Content-Type", "image/jpeg"); // Adjust the content type as necessary
|
||||||
res.send(post.postImage);
|
res.send(post.postImage);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
res
|
res
|
||||||
.status(500)
|
.status(500)
|
||||||
.json({ message: "Error retrieving post image", error: err });
|
.json({ message: "Error retrieving post image", error: err });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.put("/:id", upload.fields([{ name: 'postImage', maxCount: 1 }]), async (req, res) => {
|
router.put(
|
||||||
|
"/:id",
|
||||||
|
upload.fields([{ name: "postImage", maxCount: 1 }]),
|
||||||
|
async (req, res) => {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
let files = req.files;
|
let files = req.files;
|
||||||
|
|
||||||
// Check id not found
|
// Check id not found
|
||||||
let post = await Post.findByPk(id);
|
let post = await Post.findByPk(id);
|
||||||
if (!post) {
|
if (!post) {
|
||||||
res.sendStatus(404);
|
res.sendStatus(404);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = req.body;
|
let data = req.body;
|
||||||
@@ -127,114 +150,119 @@ router.put("/:id", upload.fields([{ name: 'postImage', maxCount: 1 }]), async (r
|
|||||||
|
|
||||||
// Validate request body
|
// Validate request body
|
||||||
let validationSchema = yup.object({
|
let validationSchema = yup.object({
|
||||||
title: yup.string().trim().min(3).max(100),
|
title: yup.string().trim().min(3).max(100),
|
||||||
content: yup.string().trim().min(3).max(500),
|
content: yup.string().trim().min(3).max(500),
|
||||||
postImage: yup.mixed(),
|
postImage: yup.mixed(),
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
data = await validationSchema.validate(data,
|
data = await validationSchema.validate(data, { abortEarly: false });
|
||||||
{ abortEarly: false });
|
|
||||||
|
|
||||||
// Check for profanity
|
// Check for profanity
|
||||||
if (filter.isProfane(data.title)) {
|
if (filter.isProfane(data.title)) {
|
||||||
return res.status(400).json({ field: 'title', error: 'Profane content detected in title' });
|
return res
|
||||||
}
|
.status(400)
|
||||||
if (filter.isProfane(data.content)) {
|
.json({ field: "title", error: "Profane content detected in title" });
|
||||||
return res.status(400).json({ field: 'content', error: 'Profane content detected in content' });
|
}
|
||||||
}
|
if (filter.isProfane(data.content)) {
|
||||||
|
return res.status(400).json({
|
||||||
// Include the postImage if present
|
field: "content",
|
||||||
if (postImage) {
|
error: "Profane content detected in content",
|
||||||
data.postImage = postImage;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Process valid data
|
|
||||||
let post = await Post.update(data, { // update() updates data based on the where condition, and returns the number of rows affected
|
|
||||||
where: { id: id } // If num equals 1, return OK, otherwise return Bad Request
|
|
||||||
});
|
});
|
||||||
if (post) {
|
}
|
||||||
res.json({ message: "Post was updated successfully." });
|
|
||||||
}
|
// Include the postImage if present
|
||||||
else {
|
if (postImage) {
|
||||||
res.status(400).json({
|
data.postImage = postImage;
|
||||||
message: `Cannot update post with id ${id}.`
|
}
|
||||||
});
|
|
||||||
}
|
// Process valid data
|
||||||
|
let post = await Post.update(data, {
|
||||||
|
// update() updates data based on the where condition, and returns the number of rows affected
|
||||||
|
where: { id: id }, // If num equals 1, return OK, otherwise return Bad Request
|
||||||
|
});
|
||||||
|
if (post) {
|
||||||
|
res.json({ message: "Post was updated successfully." });
|
||||||
|
} else {
|
||||||
|
res.status(400).json({
|
||||||
|
message: `Cannot update post with id ${id}.`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
res.status(400).json({ errors: err.errors });
|
||||||
}
|
}
|
||||||
catch (err) {
|
}
|
||||||
res.status(400).json({ errors: err.errors });
|
);
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.delete("/:id", async (req, res) => {
|
router.delete("/:id", async (req, res) => {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
// Check id not found
|
// Check id not found
|
||||||
let post = await Post.findByPk(id);
|
let post = await Post.findByPk(id);
|
||||||
if (!post) {
|
if (!post) {
|
||||||
res.sendStatus(404);
|
res.sendStatus(404);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let num = await Post.destroy({ // destroy() deletes data based on the where condition, and returns the number of rows affected
|
let num = await Post.destroy({
|
||||||
where: { id: id }
|
// destroy() deletes data based on the where condition, and returns the number of rows affected
|
||||||
})
|
where: { id: id },
|
||||||
if (num == 1) { // destry() returns no. of rows affected, that's why if num == 1
|
});
|
||||||
res.json({
|
if (num == 1) {
|
||||||
message: "Post was deleted successfully."
|
// destry() returns no. of rows affected, that's why if num == 1
|
||||||
});
|
res.json({
|
||||||
}
|
message: "Post was deleted successfully.",
|
||||||
else {
|
});
|
||||||
res.status(400).json({
|
} else {
|
||||||
message: `Cannot delete post with id ${id}.`
|
res.status(400).json({
|
||||||
});
|
message: `Cannot delete post with id ${id}.`,
|
||||||
}
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post("/:id/comments", async (req, res) => {
|
router.post("/:id/comments", async (req, res) => {
|
||||||
let data = req.body;
|
let data = req.body;
|
||||||
|
|
||||||
// Validate request body
|
// Validate request body
|
||||||
let validationSchema = yup.object({
|
let validationSchema = yup.object({
|
||||||
content: yup.string().trim().min(3).max(500).required(),
|
content: yup.string().trim().min(3).max(500).required(),
|
||||||
userId: yup.string().required(),
|
userId: yup.string().required(),
|
||||||
postId: yup.string().required()
|
postId: yup.string().required(),
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
console.log("Validating schema...");
|
console.log("Validating schema...");
|
||||||
data = await validationSchema.validate(data, { abortEarly: false });
|
data = await validationSchema.validate(data, { abortEarly: false });
|
||||||
|
|
||||||
console.log("Creating comment...");
|
console.log("Creating comment...");
|
||||||
let result = await Comment.create(data);
|
let result = await Comment.create(data);
|
||||||
|
|
||||||
res.json(result);
|
res.json(result);
|
||||||
console.log("Success!");
|
console.log("Success!");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log("Error caught! Info: " + err);
|
console.log("Error caught! Info: " + err);
|
||||||
res.status(400).json({ errors: err.errors });
|
res.status(400).json({ errors: err.errors });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get("/:id/getComments", async (req, res) => {
|
router.get("/:id/getComments", async (req, res) => {
|
||||||
let id = req.params.id;
|
let id = req.params.id;
|
||||||
|
|
||||||
let condition = {
|
let condition = {
|
||||||
where: { postId: id },
|
where: { postId: id },
|
||||||
include: [
|
include: [
|
||||||
{
|
{
|
||||||
model: User,
|
model: User,
|
||||||
attributes: ['id', 'firstName', 'lastName'] // Specify the attributes you need
|
attributes: ["id", "firstName", "lastName"], // Specify the attributes you need
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
order: [['createdAt', 'DESC']]
|
order: [["createdAt", "DESC"]],
|
||||||
};
|
};
|
||||||
|
|
||||||
// Check id not found
|
// Check id not found
|
||||||
let comments = await Comment.findAll(condition);
|
let comments = await Comment.findAll(condition);
|
||||||
if (!comments) {
|
if (!comments) {
|
||||||
res.sendStatus(404);
|
res.sendStatus(404);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
res.json(comments);
|
res.json(comments);
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = router;
|
module.exports = router;
|
||||||
|
|||||||
Reference in New Issue
Block a user