@@ -15,25 +15,33 @@ function parsePostId(id: string | string[], res: Response): number | null {
1515
1616// GET /feed — all published posts
1717postRouter . get ( '/feed' , async ( _req : Request , res : Response ) => {
18- const posts = await prisma . post . findMany ( {
19- where : { published : true } ,
20- include : { author : true } ,
21- } )
22- res . json ( posts )
18+ try {
19+ const posts = await prisma . post . findMany ( {
20+ where : { published : true } ,
21+ include : { author : true } ,
22+ } )
23+ res . json ( posts )
24+ } catch {
25+ res . status ( 500 ) . json ( { error : 'Internal server error' } )
26+ }
2327} )
2428
2529// GET /post/:id — single post by id
2630postRouter . get ( '/post/:id' , async ( req : Request , res : Response ) => {
2731 const postId = parsePostId ( req . params . id , res )
2832 if ( postId === null ) return
29- const post = await prisma . post . findUnique ( {
30- where : { id : postId } ,
31- } )
32- if ( ! post ) {
33- res . status ( 404 ) . json ( { error : `Post with ID ${ req . params . id } not found` } )
34- return
33+ try {
34+ const post = await prisma . post . findUnique ( {
35+ where : { id : postId } ,
36+ } )
37+ if ( ! post ) {
38+ res . status ( 404 ) . json ( { error : `Post with ID ${ req . params . id } not found` } )
39+ return
40+ }
41+ res . json ( post )
42+ } catch {
43+ res . status ( 500 ) . json ( { error : 'Internal server error' } )
3544 }
36- res . json ( post )
3745} )
3846
3947// POST /post — create post
@@ -43,19 +51,23 @@ postRouter.post('/post', async (req: Request, res: Response) => {
4351 res . status ( 400 ) . json ( { error : 'title and authorEmail are required' } )
4452 return
4553 }
46- const author = await prisma . user . findUnique ( { where : { email : authorEmail } } )
47- if ( ! author ) {
48- res . status ( 404 ) . json ( { error : `No user found for email: ${ authorEmail } ` } )
49- return
54+ try {
55+ const author = await prisma . user . findUnique ( { where : { email : authorEmail } } )
56+ if ( ! author ) {
57+ res . status ( 404 ) . json ( { error : `No user found for email: ${ authorEmail } ` } )
58+ return
59+ }
60+ const post = await prisma . post . create ( {
61+ data : {
62+ title,
63+ content,
64+ author : { connect : { email : authorEmail } } ,
65+ } ,
66+ } )
67+ res . status ( 201 ) . json ( post )
68+ } catch {
69+ res . status ( 500 ) . json ( { error : 'Internal server error' } )
5070 }
51- const post = await prisma . post . create ( {
52- data : {
53- title,
54- content,
55- author : { connect : { email : authorEmail } } ,
56- } ,
57- } )
58- res . status ( 201 ) . json ( post )
5971} )
6072
6173// PUT /publish/:id — publish a post
0 commit comments