include author in posts and exclude password with typesafe function
This commit is contained in:
parent
5dd34edbe1
commit
f66befd0c7
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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, Key extends keyof User>(user: User, ...keys: Key[]): User {
|
||||
for (let key of keys) {
|
||||
delete user[key];
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
const createPost = async (post: Post) => {
|
||||
const getAllPosts = async (): Promise<PrismaPost[]> => {
|
||||
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<PrismaPost> => {
|
||||
const newPost = await prisma.post.create({
|
||||
data: {
|
||||
title: post.title,
|
||||
|
|
|
|||
Loading…
Reference in New Issue