1- using Microsoft . AspNetCore . Mvc ;
1+ using exercise . wwwapi . DTOs ;
2+ using exercise . wwwapi . Enums ;
3+ using exercise . wwwapi . Models ;
4+ using exercise . wwwapi . Repository ;
5+ using Microsoft . AspNetCore . Mvc ;
6+ using Microsoft . EntityFrameworkCore ;
7+ using Npgsql ;
28
39namespace exercise . wwwapi . Endpoints ;
410
@@ -9,9 +15,57 @@ public static void ConfigureCohortEndpoints(this WebApplication app)
915 var cohorts = app . MapGroup ( "cohorts" ) ;
1016 cohorts . MapPost ( "/" , CreateCohort ) . WithSummary ( "Create a cohort" ) ;
1117 }
12- [ ProducesResponseType ( StatusCodes . Status200OK ) ]
13- public static async Task < IResult > CreateCohort ( )
18+ [ ProducesResponseType ( StatusCodes . Status201Created ) ]
19+ [ ProducesResponseType ( StatusCodes . Status400BadRequest ) ]
20+ [ ProducesResponseType ( StatusCodes . Status500InternalServerError ) ]
21+ public static async Task < IResult > CreateCohort ( IRepository < Cohort > cohortRepo , CohortPostDTO ? postCohort )
1422 {
15- return TypedResults . Ok ( ) ;
23+ if ( postCohort == null || postCohort . StartDate == DateTime . MinValue || postCohort . EndDate == DateTime . MinValue )
24+ {
25+ return TypedResults . BadRequest ( "Missing cohort data" ) ;
26+ }
27+
28+ bool success = false ;
29+ int attempts = 0 ;
30+ int newCohortNumber = 0 ;
31+
32+ while ( ! success && attempts < 5 )
33+ {
34+ try
35+ {
36+ var maxCohortNumber = ( int ? ) await cohortRepo . GetMaxValueAsync ( c => c . CohortNumber ) ;
37+ if ( maxCohortNumber == null )
38+ {
39+ maxCohortNumber = 0 ;
40+ }
41+ if ( postCohort . CohortName == null )
42+ {
43+ postCohort . CohortName = $ "Cohort { maxCohortNumber + 1 } ";
44+ }
45+
46+ newCohortNumber = ( int ) ( maxCohortNumber + 1 ) ;
47+ Cohort newCohort = new Cohort { CohortNumber = newCohortNumber , CohortName = postCohort . CohortName , StartDate = postCohort . StartDate , EndDate = postCohort . EndDate } ;
48+
49+ cohortRepo . Insert ( newCohort ) ;
50+ await cohortRepo . SaveAsync ( ) ;
51+ success = true ;
52+ }
53+ catch ( DbUpdateException ex )
54+ {
55+ if ( ex . InnerException is PostgresException CohortNumberEx &&
56+ CohortNumberEx . SqlState == "23505" ) //23505 = Cohort number value already exists
57+ {
58+ attempts ++ ;
59+ }
60+ else
61+ {
62+ Console . WriteLine ( $ "DB update error: { ex . StackTrace } ") ;
63+ return TypedResults . InternalServerError ( $ "Error while updating the database: { ex . Message } ") ;
64+ }
65+ }
66+ }
67+
68+ return TypedResults . Created ( $ "/cohorts/{ newCohortNumber } ") ;
1669 }
70+
1771}
0 commit comments