From 78a40c35cb0c0f35747a04275e0b275e2154ea23 Mon Sep 17 00:00:00 2001 From: Kai Ritthaler Date: Wed, 28 May 2025 18:28:15 +0200 Subject: [PATCH] added endpoint to get postIds from user --- .../backend/src/controllers/postController.ts | 61 +++++++++++++++++-- code/backend/src/middleware/fileUpload.ts | 8 ++- code/backend/src/routes/postRoutes.ts | 39 ++++++++---- code/backend/src/server.ts | 4 +- 4 files changed, 93 insertions(+), 19 deletions(-) diff --git a/code/backend/src/controllers/postController.ts b/code/backend/src/controllers/postController.ts index c03e674..4cd7c19 100644 --- a/code/backend/src/controllers/postController.ts +++ b/code/backend/src/controllers/postController.ts @@ -14,7 +14,6 @@ export const uploadPost = async (req: Request, res: Response) => { const user: JwtPayload = req.user!; // Get the user from the request const { description, status, tags } = uploadPostSchema.parse(req.body); const BUCKET = "images"; // Name of the bucket where the images are stored - console.log(tags); try { const uploads = await Promise.all( files.map(async (file) => { @@ -85,6 +84,16 @@ export const getPost = async (req: Request, res: Response) => { include: { user: true, media: true, + postTags: { + include: { + tag: true, + }, + }, + }, + }); + const likes: number = await prisma.like.count({ + where: { + postId: postId, }, }); if (!postObject) { @@ -98,7 +107,7 @@ export const getPost = async (req: Request, res: Response) => { }); return; } - const post = await Promise.all( + const images = await Promise.all( // generate the presigned url for each image postObject?.media.map(async (image) => { try { @@ -117,10 +126,19 @@ export const getPost = async (req: Request, res: Response) => { return null; } }) ?? [] - ); + ); // map the images to the presigned urls res.status(StatusCodes.OK).json({ - message: "Post found", - post: post, + description: postObject.description, + status: postObject.status, + likes: likes, + tags: postObject.postTags.map((tag) => tag.tag.name), + user: { + id: postObject.user.id, + name: postObject.user.username, + }, + createdAt: postObject.createdAt, + updatedAt: postObject.updatedAt, + images: images.filter((image) => image !== null), // filter out the null images }); } catch (err: any) { if (err.code === "NotFound") { @@ -141,3 +159,36 @@ export const getPost = async (req: Request, res: Response) => { }); } }; + +// get all posts from a user +export const getUserPosts = async (req: Request, res: Response) => { + try { + const userId: string = req.query.userId as string; // Get the userId from the request + const posts = await prisma.post.findMany({ + where: { + userId: userId, + }, + }); + if (!posts || posts.length === 0) { + res.status(StatusCodes.NOT_FOUND).json({ + error: "No posts found", + details: [ + { + message: `The user does not have any posts`, + }, + ], + }); + return; + } + res.status(StatusCodes.OK).json({ + posts: posts, + }); + } catch (err: any) { + console.error(err); + res.status(StatusCodes.INTERNAL_SERVER_ERROR).json({ + error: "Failed to retrieve posts", + details: [{ message: "Server error" }], + }); + return; + } +}; diff --git a/code/backend/src/middleware/fileUpload.ts b/code/backend/src/middleware/fileUpload.ts index bc47f5f..1e5cabd 100644 --- a/code/backend/src/middleware/fileUpload.ts +++ b/code/backend/src/middleware/fileUpload.ts @@ -26,7 +26,13 @@ export const upload = (req: Request, res: Response, next: NextFunction) => { } const files = req.files as Express.Multer.File[]; - + if (files.length > 15) { + //check if user uploaded more than 15 files + return res.status(StatusCodes.BAD_REQUEST).json({ + error: "Too many files", + details: [{ message: "You can upload a maximum of 15 files" }], + }); + } for (const file of files) { //check for correct filetypes if ( diff --git a/code/backend/src/routes/postRoutes.ts b/code/backend/src/routes/postRoutes.ts index 50a000a..344ff89 100644 --- a/code/backend/src/routes/postRoutes.ts +++ b/code/backend/src/routes/postRoutes.ts @@ -1,12 +1,14 @@ import express from "express"; import { getPost, + getUserPosts, uploadPost as uploadPost, } from "../controllers/postController"; import { upload } from "../middleware/fileUpload"; -import { authenticateToken } from "../middleware/authenticateToken"; + import { validateData } from "../middleware/validationMiddleware"; import { uploadPostSchema } from "../schemas/postSchemas"; +import { get } from "http"; const router = express.Router(); /** @@ -56,16 +58,10 @@ const router = express.Router(); * 200: * description: Images uploaded successfully */ -router.post( - "/upload", - authenticateToken(), - upload, - validateData(uploadPostSchema), - uploadPost -); +router.post("/upload", upload, validateData(uploadPostSchema), uploadPost); /** * @swagger - * /api/posts/get/{postId}: + * /api/posts/getPost/{postId}: * get: * summary: Get Post * tags: [posts] @@ -84,6 +80,27 @@ router.post( * 401: * description: not authenticated */ -router.get("/get/:postId", getPost); - +router.get("/getPost/:userId", getPost); +/** + * @swagger + * /api/posts/getUserPosts/{userId}: + * get: + * summary: Get Post + * tags: [posts] + * security: + * - bearerAuth: [] + * parameters: + * - in: query + * name: postId + * required: true + * schema: + * type: string + * description: The user id + * responses: + * 200: + * description: Ok + * 401: + * description: not authenticated + */ +router.get("/getuserposts/:userId", getUserPosts); export default router; diff --git a/code/backend/src/server.ts b/code/backend/src/server.ts index d61c71f..91d4504 100644 --- a/code/backend/src/server.ts +++ b/code/backend/src/server.ts @@ -3,7 +3,7 @@ import { Client } from "minio"; import dotenv from "dotenv"; import userRouter from "./routes/userRoutes"; import postRouter from "./routes/postRoutes"; -//import postController from "./controllers/postController"; +import { authenticateToken } from "./middleware/authenticateToken"; import bodyParser from "body-parser"; dotenv.config(); @@ -59,7 +59,7 @@ app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs)); app.use(bodyParser.json()); app.use("/api/user", userRouter); -app.use("/api/posts", postRouter); +app.use("/api/posts", authenticateToken(), postRouter); app.listen(port, () => { console.log(`Server läuft auf http://localhost:${port}`);