diff --git a/src/api/posts/edit.ts b/src/api/posts/edit.ts new file mode 100644 index 0000000..65d8a83 --- /dev/null +++ b/src/api/posts/edit.ts @@ -0,0 +1,22 @@ +import { Post } from '@/models/PostModel'; +import { editPost } from '@/controller/PostController'; +import { Post as PrismaPost } from '@prisma/client'; +import { Request, Response } from 'express'; + +export default async (req: Request, res: Response) => { + try { + const post: Post = Post.parse(req.body); + const userId = 1; // hardcoded for now, use userId from token + const editedPost: PrismaPost | null | Error = await editPost(post, userId); + if (editedPost === null) { + return res.status(404).send('Post not found'); + } + if (editedPost instanceof Error) { + return res.status(403).send(editedPost.message); + } + + return res.status(200).send(editedPost); + } catch (error) { + return res.status(500).send(error); + } +}; diff --git a/src/controller/PostController.ts b/src/controller/PostController.ts index 7ac847c..6c1591f 100644 --- a/src/controller/PostController.ts +++ b/src/controller/PostController.ts @@ -10,6 +10,15 @@ const exclude = (user: User, ...keys: Key[]): User return user; }; +const getPostById = async (id: number): Promise => { + const post = await prisma.post.findUnique({ + where: { + id, + }, + }); + return post; +}; + const getAllPosts = async (): Promise => { const posts = prisma.post.findMany({ include: { @@ -35,4 +44,33 @@ const createPost = async (post: Post): Promise => { return newPost; }; -export { getAllPosts, createPost }; +const editPost = async (post: Post, userId: number): Promise => { + if (post.id === undefined) { + return new Error('Post id is undefined'); + } + const originalPost = await getPostById(post.id); + if (originalPost === null) { + return null; + } + if (originalPost.authorId !== userId) { + return new Error('User is not the author of this post'); + } + const editedPost = await prisma.post.update({ + where: { + id: post.id, + }, + data: { + title: post.title, + content: post.content, + image: post.image, + }, + }); + + if (!editedPost) { + return null; + } + + return editedPost; +}; + +export { getAllPosts, createPost, editPost }; diff --git a/src/models/PostModel.ts b/src/models/PostModel.ts index 441ec35..b68cd0b 100644 --- a/src/models/PostModel.ts +++ b/src/models/PostModel.ts @@ -1,7 +1,7 @@ import { z } from 'zod'; interface Post { - id?: number | null; + id?: number | undefined; title: string; content?: string | undefined; image?: string | undefined;