@@ -68,7 +68,7 @@ func (i *Implementation) GetIncidents(ctx echo.Context, params apiServerDefiniti
68
68
}
69
69
70
70
// CreateIncident handles creation of incidents.
71
- func (i * Implementation ) CreateIncident (ctx echo.Context ) error {
71
+ func (i * Implementation ) CreateIncident (ctx echo.Context ) error { //nolint: funlen
72
72
var request apiServerDefinition.CreateIncidentJSONRequestBody
73
73
74
74
logger := i .logger .With ().Str ("handler" , "CreateIncident" ).Logger ()
@@ -97,11 +97,41 @@ func (i *Implementation) CreateIncident(ctx echo.Context) error {
97
97
98
98
dbSession := i .dbCon .WithContext (ctx .Request ().Context ())
99
99
100
- res := dbSession .Create (incident )
101
- if res .Error != nil {
102
- logger .Error ().Err (res .Error ).Msg ("error creating incident" )
100
+ err = dbSession .Transaction (func (dbTx * gorm.DB ) error {
101
+ var (
102
+ transactionErr error
103
+ dbPhase DbDef.Phase
104
+ )
103
105
104
- return echo .ErrInternalServerError
106
+ // Check phase validity
107
+ if incident .Phase != nil {
108
+ dbPhase .Generation = incident .Phase .Generation
109
+ dbPhase .Order = incident .Phase .Order
110
+
111
+ transactionErr = dbTx .First (& dbPhase ).Error
112
+ if errors .Is (transactionErr , gorm .ErrRecordNotFound ) {
113
+ logger .Warn ().Msg ("invalid phase for incident" )
114
+
115
+ return echo .ErrBadRequest
116
+ } else if transactionErr != nil {
117
+ logger .Error ().Err (transactionErr ).Msg ("error loading phase from database" )
118
+
119
+ return echo .ErrInternalServerError
120
+ }
121
+ }
122
+
123
+ transactionErr = dbTx .Create (incident ).Error
124
+ if transactionErr != nil {
125
+ logger .Error ().Err (transactionErr ).Msg ("error creating incident" )
126
+
127
+ return echo .ErrInternalServerError
128
+ }
129
+
130
+ return nil
131
+ })
132
+ if err != nil {
133
+ // Don't wrap the echo errors.
134
+ return err //nolint:wrapcheck
105
135
}
106
136
107
137
return ctx .JSON (http .StatusCreated , apiServerDefinition.IdResponse { //nolint:wrapcheck
0 commit comments