added endpoint to get postIds from user

This commit is contained in:
Kai Ritthaler 2025-05-28 18:28:15 +02:00 committed by Rudi Regentonne
parent ece95c7130
commit 78a40c35cb
4 changed files with 93 additions and 19 deletions

View file

@ -14,7 +14,6 @@ export const uploadPost = async (req: Request, res: Response) => {
const user: JwtPayload = req.user!; // Get the user from the request const user: JwtPayload = req.user!; // Get the user from the request
const { description, status, tags } = uploadPostSchema.parse(req.body); const { description, status, tags } = uploadPostSchema.parse(req.body);
const BUCKET = "images"; // Name of the bucket where the images are stored const BUCKET = "images"; // Name of the bucket where the images are stored
console.log(tags);
try { try {
const uploads = await Promise.all( const uploads = await Promise.all(
files.map(async (file) => { files.map(async (file) => {
@ -85,6 +84,16 @@ export const getPost = async (req: Request, res: Response) => {
include: { include: {
user: true, user: true,
media: true, media: true,
postTags: {
include: {
tag: true,
},
},
},
});
const likes: number = await prisma.like.count({
where: {
postId: postId,
}, },
}); });
if (!postObject) { if (!postObject) {
@ -98,7 +107,7 @@ export const getPost = async (req: Request, res: Response) => {
}); });
return; return;
} }
const post = await Promise.all( const images = await Promise.all(
// generate the presigned url for each image // generate the presigned url for each image
postObject?.media.map(async (image) => { postObject?.media.map(async (image) => {
try { try {
@ -117,10 +126,19 @@ export const getPost = async (req: Request, res: Response) => {
return null; return null;
} }
}) ?? [] }) ?? []
); ); // map the images to the presigned urls
res.status(StatusCodes.OK).json({ res.status(StatusCodes.OK).json({
message: "Post found", description: postObject.description,
post: post, 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) { } catch (err: any) {
if (err.code === "NotFound") { 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;
}
};

View file

@ -26,7 +26,13 @@ export const upload = (req: Request, res: Response, next: NextFunction) => {
} }
const files = req.files as Express.Multer.File[]; 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) { for (const file of files) {
//check for correct filetypes //check for correct filetypes
if ( if (

View file

@ -1,12 +1,14 @@
import express from "express"; import express from "express";
import { import {
getPost, getPost,
getUserPosts,
uploadPost as uploadPost, uploadPost as uploadPost,
} from "../controllers/postController"; } from "../controllers/postController";
import { upload } from "../middleware/fileUpload"; import { upload } from "../middleware/fileUpload";
import { authenticateToken } from "../middleware/authenticateToken";
import { validateData } from "../middleware/validationMiddleware"; import { validateData } from "../middleware/validationMiddleware";
import { uploadPostSchema } from "../schemas/postSchemas"; import { uploadPostSchema } from "../schemas/postSchemas";
import { get } from "http";
const router = express.Router(); const router = express.Router();
/** /**
@ -56,16 +58,10 @@ const router = express.Router();
* 200: * 200:
* description: Images uploaded successfully * description: Images uploaded successfully
*/ */
router.post( router.post("/upload", upload, validateData(uploadPostSchema), uploadPost);
"/upload",
authenticateToken(),
upload,
validateData(uploadPostSchema),
uploadPost
);
/** /**
* @swagger * @swagger
* /api/posts/get/{postId}: * /api/posts/getPost/{postId}:
* get: * get:
* summary: Get Post * summary: Get Post
* tags: [posts] * tags: [posts]
@ -84,6 +80,27 @@ router.post(
* 401: * 401:
* description: not authenticated * 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; export default router;

View file

@ -3,7 +3,7 @@ import { Client } from "minio";
import dotenv from "dotenv"; import dotenv from "dotenv";
import userRouter from "./routes/userRoutes"; import userRouter from "./routes/userRoutes";
import postRouter from "./routes/postRoutes"; import postRouter from "./routes/postRoutes";
//import postController from "./controllers/postController"; import { authenticateToken } from "./middleware/authenticateToken";
import bodyParser from "body-parser"; import bodyParser from "body-parser";
dotenv.config(); dotenv.config();
@ -59,7 +59,7 @@ app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(specs));
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use("/api/user", userRouter); app.use("/api/user", userRouter);
app.use("/api/posts", postRouter); app.use("/api/posts", authenticateToken(), postRouter);
app.listen(port, () => { app.listen(port, () => {
console.log(`Server läuft auf http://localhost:${port}`); console.log(`Server läuft auf http://localhost:${port}`);