99using Microsoft . AspNetCore . Authorization ;
1010using Microsoft . AspNetCore . Mvc ;
1111using Microsoft . EntityFrameworkCore ;
12+ using Npgsql ;
1213using System . Security . Claims ;
1314using Post = exercise . wwwapi . Models . Post ;
1415
@@ -49,6 +50,7 @@ private static async Task<IResult> GetCommentsPerPost(IRepository<Comment> comme
4950 [ ProducesResponseType ( StatusCodes . Status200OK ) ]
5051 [ ProducesResponseType ( StatusCodes . Status400BadRequest ) ]
5152 [ ProducesResponseType ( StatusCodes . Status401Unauthorized ) ]
53+ [ ProducesResponseType ( StatusCodes . Status404NotFound ) ]
5254 public static async Task < IResult > CreateComment (
5355 CreateCommentRequestDTO request ,
5456 IRepository < Comment > commentRepository ,
@@ -74,24 +76,31 @@ public static async Task<IResult> CreateComment(
7476 return Results . BadRequest ( failResponse ) ;
7577 }
7678
77- var post = await postRepository . GetByIdAsync ( postId ) ;
78- if ( post == null )
79- {
80- return Results . NotFound ( ) ;
81- }
82-
8379 var comment = new Comment
8480 {
8581 PostId = postId ,
8682 UserId = userIdClaim . Value ,
8783 Body = request . Body ,
88- CreatedAt = DateTime . UtcNow ,
84+ CreatedAt = DateTime . UtcNow
8985 } ;
9086
9187 commentRepository . Insert ( comment ) ;
92- await commentRepository . SaveAsync ( ) ;
88+ try
89+ {
90+ await commentRepository . SaveAsync ( ) ;
91+ }
92+ catch ( DbUpdateException ex )
93+ {
94+ if ( ex . InnerException is PostgresException CohortNumberEx &&
95+ CohortNumberEx . SqlState == "23503" ) //23503 = FK violation (Post Id or User Id did not exist)
96+ {
97+ return TypedResults . NotFound ( $ "Post with id: { postId } was not found") ;
98+ }
99+ }
100+
101+ var commentWithUser = await commentRepository . GetByIdWithIncludes ( c => c . Include ( c => c . User ) , comment . Id ) ;
93102
94- var commentData = new CommentDTO ( comment ) ;
103+ var commentData = new CommentDTO ( commentWithUser ) ;
95104
96105 var response = new ResponseDTO < CommentDTO >
97106 {
@@ -106,6 +115,7 @@ public static async Task<IResult> CreateComment(
106115 [ ProducesResponseType ( StatusCodes . Status200OK ) ]
107116 [ ProducesResponseType ( StatusCodes . Status400BadRequest ) ]
108117 [ ProducesResponseType ( StatusCodes . Status401Unauthorized ) ]
118+ [ ProducesResponseType ( StatusCodes . Status404NotFound ) ]
109119 public static async Task < IResult > UpdateComment (
110120 IRepository < Comment > commentRepository ,
111121 int id ,
@@ -191,7 +201,7 @@ public static async Task<IResult> DeleteComment(
191201 return TypedResults . NotFound ( ) ;
192202 }
193203
194- if ( comment . UserId != userIdClaim )
204+ if ( comment . UserId != userIdClaim && ! claimsPrincipal . IsInRole ( "Teacher" ) )
195205 {
196206 return Results . Unauthorized ( ) ;
197207 }
0 commit comments