typesafe post edit with author checking
This commit is contained in:
parent
a3004431fd
commit
7364326918
|
|
@ -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);
|
||||
}
|
||||
};
|
||||
|
|
@ -10,6 +10,15 @@ const exclude = <User, Key extends keyof User>(user: User, ...keys: Key[]): User
|
|||
return user;
|
||||
};
|
||||
|
||||
const getPostById = async (id: number): Promise<PrismaPost | null> => {
|
||||
const post = await prisma.post.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
return post;
|
||||
};
|
||||
|
||||
const getAllPosts = async (): Promise<PrismaPost[]> => {
|
||||
const posts = prisma.post.findMany({
|
||||
include: {
|
||||
|
|
@ -35,4 +44,33 @@ const createPost = async (post: Post): Promise<PrismaPost> => {
|
|||
return newPost;
|
||||
};
|
||||
|
||||
export { getAllPosts, createPost };
|
||||
const editPost = async (post: Post, userId: number): Promise<PrismaPost | null | Error> => {
|
||||
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 };
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
interface Post {
|
||||
id?: number | null;
|
||||
id?: number | undefined;
|
||||
title: string;
|
||||
content?: string | undefined;
|
||||
image?: string | undefined;
|
||||
|
|
|
|||
Loading…
Reference in New Issue