52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
import { NextFunction, Request, Response } from 'express';
|
|
import { AppDataSource } from '../data-source';
|
|
import { User } from "../entity/User";
|
|
import { Post } from "../entity/Post";
|
|
|
|
const userShouldExist = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
const { username } = req.body;
|
|
const { userId } = req.params;
|
|
let user;
|
|
if (username) {
|
|
user = await AppDataSource.manager.findOneBy(User, {
|
|
username
|
|
});
|
|
} else if (Number.parseInt(userId)) {
|
|
user = await AppDataSource.manager.findOneBy(User, {
|
|
id: Number.parseInt(userId)
|
|
});
|
|
} else {
|
|
res.status(404).send("User does not exist.");
|
|
return;
|
|
}
|
|
if (!user) {
|
|
res.status(404).send("User does not exist.");
|
|
return;
|
|
}
|
|
next();
|
|
}
|
|
|
|
const userShouldNotExist = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
const { username } = req.body;
|
|
|
|
if (await AppDataSource.manager.findOneBy(User, {
|
|
username
|
|
})) {
|
|
res.status(409).send("Such user already exists");
|
|
return;
|
|
}
|
|
next();
|
|
}
|
|
|
|
const postShouldExist = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
const postId = Number.parseInt(req.params.postId);
|
|
|
|
if (!(await AppDataSource.manager.findOneBy(Post, {id: postId}))) {
|
|
res.status(404).send("Post not found");
|
|
return;
|
|
}
|
|
|
|
next();
|
|
}
|
|
|
|
export default { userShouldExist, userShouldNotExist, postShouldExist}; |