add deletePost route
This commit is contained in:
parent
65b5409b0b
commit
9e5dc4a740
|
|
@ -0,0 +1,16 @@
|
||||||
|
import { deletePost } from '@/controller/PostController';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
|
||||||
|
export default async (req: Request, res: Response) => {
|
||||||
|
try {
|
||||||
|
const id = parseInt(req.params.id);
|
||||||
|
const userId = 1; // hardcoded for now, use userId from token
|
||||||
|
const deletedPost = await deletePost(id, userId);
|
||||||
|
if (deletedPost instanceof Error) {
|
||||||
|
return res.status(403).send(deletedPost.message);
|
||||||
|
}
|
||||||
|
return res.status(200).send({ message: 'Post deleted' });
|
||||||
|
} catch (error) {
|
||||||
|
return res.status(500).send(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
|
import { Router } from 'express';
|
||||||
import getPosts from './getPosts';
|
import getPosts from './getPosts';
|
||||||
import postPost from './newPost';
|
import postPost from './newPost';
|
||||||
import putPost from './editPost';
|
import putPost from './editPost';
|
||||||
import { Router } from 'express';
|
import deletePost from './deletePost';
|
||||||
|
|
||||||
const posts = Router();
|
const posts = Router();
|
||||||
|
|
||||||
posts.get('/', getPosts);
|
posts.get('/', getPosts);
|
||||||
posts.post('/new', postPost);
|
posts.post('/new', postPost);
|
||||||
posts.put('/edit/:id', putPost);
|
posts.put('/edit/:id', putPost);
|
||||||
|
posts.delete('/delete/:id', deletePost);
|
||||||
|
|
||||||
export default posts;
|
export default posts;
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { PrismaClient, Post as PrismaPost } from '@prisma/client';
|
import { PrismaClient, Post as PrismaPost, User } from '@prisma/client';
|
||||||
import { Post } from '@/models/PostModel';
|
import { Post } from '@/models/PostModel';
|
||||||
|
|
||||||
const prisma = new PrismaClient();
|
const prisma = new PrismaClient();
|
||||||
|
|
@ -71,4 +71,23 @@ const editPost = async (post: Post): Promise<PrismaPost | null | Error> => {
|
||||||
return editedPost;
|
return editedPost;
|
||||||
};
|
};
|
||||||
|
|
||||||
export { getAllPosts, createPost, editPost, getPostById };
|
const deletePost = async (id: number, userId: number): Promise<PrismaPost | Error> => {
|
||||||
|
const post = await prisma.post.findUnique({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (post === null) {
|
||||||
|
return new Error('Post not found');
|
||||||
|
}
|
||||||
|
if (post.authorId !== userId) {
|
||||||
|
return new Error('User is not the author of this post');
|
||||||
|
}
|
||||||
|
return prisma.post.delete({
|
||||||
|
where: {
|
||||||
|
id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export { getAllPosts, createPost, editPost, getPostById, deletePost };
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue