From f66befd0c708f2fef49054bae114b3bafce6e20c Mon Sep 17 00:00:00 2001 From: Guillaume Dorce Date: Thu, 25 Aug 2022 15:06:33 +0200 Subject: [PATCH] include author in posts and exclude password with typesafe function --- src/api/posts/index.ts | 8 ++++---- src/api/posts/new.ts | 1 + src/api/posts/posts.ts | 4 ++-- src/controller/PostController.ts | 23 ++++++++++++++++++++--- 4 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/api/posts/index.ts b/src/api/posts/index.ts index 5124ea2..2030f96 100644 --- a/src/api/posts/index.ts +++ b/src/api/posts/index.ts @@ -1,10 +1,10 @@ -import postsRoute from './posts'; -import createPost from './new'; +import getPosts from './posts'; +import postPost from './new'; import { Router } from 'express'; const posts = Router(); -posts.get('/', postsRoute); -posts.post('/new', createPost); +posts.get('/', getPosts); +posts.post('/new', postPost); export default posts; diff --git a/src/api/posts/new.ts b/src/api/posts/new.ts index 3bdd5c7..db27ed5 100644 --- a/src/api/posts/new.ts +++ b/src/api/posts/new.ts @@ -5,6 +5,7 @@ import { Request, Response } from 'express'; export default async (req: Request, res: Response) => { try { + req.body.authorId = 1; // hardcoded for now, use userId from token const post: Post = Post.parse(req.body); const newPost: PrismaPost = await createPost(post); diff --git a/src/api/posts/posts.ts b/src/api/posts/posts.ts index 5460c0c..25f6701 100644 --- a/src/api/posts/posts.ts +++ b/src/api/posts/posts.ts @@ -6,8 +6,8 @@ const posts = Router(); posts.get('/', async (req, res) => { try { - const postList: Post[] = await getAllPosts(); - return res.status(200).send(postList); + const postsList: Post[] = await getAllPosts(); + return res.status(200).send(postsList); } catch (error) { res.status(500).send(error); } diff --git a/src/controller/PostController.ts b/src/controller/PostController.ts index 8df575c..8b5c4da 100644 --- a/src/controller/PostController.ts +++ b/src/controller/PostController.ts @@ -1,11 +1,28 @@ -import { PrismaClient } from '@prisma/client'; +import { PrismaClient, Post as PrismaPost } from '@prisma/client'; import { Post } from '@/models/PostModel'; const prisma = new PrismaClient(); -const getAllPosts = () => prisma.post.findMany(); +function exclude(user: User, ...keys: Key[]): User { + for (let key of keys) { + delete user[key]; + } + return user; +} -const createPost = async (post: Post) => { +const getAllPosts = async (): Promise => { + const posts = prisma.post.findMany({ + include: { + author: true, + }, + }); + return (await posts).map((post) => { + post.author = exclude(post.author, 'password'); + return post; + }); +}; + +const createPost = async (post: Post): Promise => { const newPost = await prisma.post.create({ data: { title: post.title,