added endpoint for retrieving users' posts, updated userShouldExist middleware to account userId param.
This commit is contained in:
parent
a1890acad0
commit
84f02d3f0d
|
@ -4,6 +4,7 @@ import jwt from 'jsonwebtoken';
|
||||||
|
|
||||||
import { AppDataSource } from '../data-source';
|
import { AppDataSource } from '../data-source';
|
||||||
import { User } from "../entity/User";
|
import { User } from "../entity/User";
|
||||||
|
import { Post } from "../entity/Post";
|
||||||
|
|
||||||
class UserController {
|
class UserController {
|
||||||
async register(req: Request, res: Response): Promise<void> {
|
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.cookie("jwt", jwt.sign({ username, id: savedUser.id }, process.env.JWT_SECRET));
|
||||||
res.status(200).redirect("/");
|
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();
|
export default new UserController();
|
|
@ -5,9 +5,12 @@ import { Post } from "../entity/Post";
|
||||||
|
|
||||||
const userShouldExist = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
const userShouldExist = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
||||||
const { username } = req.body;
|
const { username } = req.body;
|
||||||
|
const { userId } = req.params;
|
||||||
|
|
||||||
if (!(await AppDataSource.manager.findOneBy(User, {
|
if (!(await AppDataSource.manager.findOneBy(User, {
|
||||||
username
|
username
|
||||||
|
})) || !(await AppDataSource.manager.findOneBy(User, {
|
||||||
|
id: Number.parseInt(userId)
|
||||||
}))) {
|
}))) {
|
||||||
res.status(404).send("User does not exist.");
|
res.status(404).send("User does not exist.");
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -7,5 +7,6 @@ const UserRouter = Router();
|
||||||
|
|
||||||
UserRouter.post('/register', existance.userShouldNotExist, UserController.register);
|
UserRouter.post('/register', existance.userShouldNotExist, UserController.register);
|
||||||
UserRouter.post('/login', existance.userShouldExist, UserController.login);
|
UserRouter.post('/login', existance.userShouldExist, UserController.login);
|
||||||
|
UserRouter.get('/posts/:userId', existance.userShouldExist, UserController.getPosts);
|
||||||
|
|
||||||
export default UserRouter;
|
export default UserRouter;
|
Loading…
Reference in New Issue