-
Notifications
You must be signed in to change notification settings - Fork 0
/
putHandler.go
104 lines (85 loc) · 2.56 KB
/
putHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package erudito
import (
"encoding/json"
"net/http"
"reflect"
)
func PutHandler(modelZero Model, maestro *maestro) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
AddCORSHeaders(w, "PUT")
/*
* Getting ID field
*/
ModelIDField, errN := GetNumericRouteField(r, "id")
if errN != nil {
SendSingleError(w, http.StatusUnprocessableEntity, "Entity ID is invalid", "ENTITY_ID_INVALID")
return
}
/*
* Middleware Initial
*/
metaData := MiddlewareMetaData{}
mwInitial := utilsRunMiddlewaresInitial(maestro.MiddlewaresInitial, w, r, maestro, metaData, MIDDLEWARE_TYPE_PUT)
if mwInitial.Error != nil {
SendError(w, http.StatusForbidden, *mwInitial.Error)
return
}
/*
* DB Connection
*/
dbConn := maestro.dBPoolCallback(r, metaData)
if dbConn == nil {
SendSingleError(w, http.StatusInternalServerError, "Database error!", "DATABASE_ERROR")
return
}
db := dbConn.Begin()
/*
* JSON Unmarshal
*/
var modelUnmarshal map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&modelUnmarshal); err != nil {
SendSingleError(w, http.StatusUnprocessableEntity, "Given request body is invalid: "+err.Error(), "")
return
}
modelUnmarshal["id"] = ModelIDField
/*
* Generate model and run PRE Middlewares
*/
modelType := reflect.ValueOf(modelZero).Type()
modelS := maestro.getModelStructure(modelZero)
modelGenerated, metaData, err := generatePostModel(w, r, db, modelType, modelS, modelUnmarshal, maestro, metaData, MIDDLEWARE_TYPE_PUT, false)
if err != nil {
db.Rollback()
SendError(w, http.StatusForbidden, *err)
return
}
/*
* Insert in DB
*/
if err := db.Save(modelGenerated).Error; err != nil {
db.Rollback()
SendSingleError(w, http.StatusForbidden, "Cannot create a new record - "+err.Error(), "ENTITY_CREATE_ERROR")
return
}
/*
* Inserting Multiple relation IDs
*/
modelGenerated, err = insertMultipleRelations(w, r, db, modelType, modelS, modelUnmarshal, reflect.ValueOf(modelGenerated).Elem(), maestro, true)
if err != nil {
db.Rollback()
SendError(w, http.StatusForbidden, *err)
return
}
/*
* Generate return and run POS Middlewares
*/
modelGenerated, _, err = generateReturnModel(w, r, db, modelType, modelS, reflect.ValueOf(modelGenerated), maestro, metaData, MIDDLEWARE_TYPE_PUT, true)
if err != nil {
db.Rollback()
SendError(w, http.StatusForbidden, *err)
return
}
db.Commit()
SendData(w, http.StatusAccepted, MakeSingularDataStruct(modelType, modelGenerated, modelS))
})
}