added endpoint for retrieving users' posts, updated userShouldExist middleware to account userId param.

This commit is contained in:
leca 2025-01-26 00:59:05 +03:00
parent a1890acad0
commit 84f02d3f0d
3 changed files with 14 additions and 0 deletions

View File

@ -4,6 +4,7 @@ import jwt from 'jsonwebtoken';
import { AppDataSource } from '../data-source';
import { User } from "../entity/User";
import { Post } from "../entity/Post";
class UserController {
async register(req: Request, res: Response): Promise<void> {
@ -30,6 +31,15 @@ class UserController {
res.cookie("jwt", jwt.sign({ username, id: savedUser.id }, process.env.JWT_SECRET));
res.status(200).redirect("/");
}
async getPosts(req: Request, res: Response): Promise<void> {
const { userId } = req.params;
const posts = await AppDataSource.manager.findBy(Post, {authorId: Number.parseInt(userId)});
console.log(posts);
res.status(200).send(posts);
}
}
export default new UserController();

View File

@ -5,9 +5,12 @@ import { Post } from "../entity/Post";
const userShouldExist = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
const { username } = req.body;
const { userId } = req.params;
if (!(await AppDataSource.manager.findOneBy(User, {
username
})) || !(await AppDataSource.manager.findOneBy(User, {
id: Number.parseInt(userId)
}))) {
res.status(404).send("User does not exist.");
return;

View File

@ -7,5 +7,6 @@ const UserRouter = Router();
UserRouter.post('/register', existance.userShouldNotExist, UserController.register);
UserRouter.post('/login', existance.userShouldExist, UserController.login);
UserRouter.get('/posts/:userId', existance.userShouldExist, UserController.getPosts);
export default UserRouter;