-
Notifications
You must be signed in to change notification settings - Fork 0
/
collectionHandler.go
66 lines (53 loc) · 1.68 KB
/
collectionHandler.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
package erudito
import (
"net/http"
"reflect"
)
func CollectionHandler(modelZero Model, maestro *maestro) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
AddCORSHeaders(w, "GET")
modelType := reflect.ValueOf(modelZero).Type()
modelNew := reflect.New(modelType).Interface()
modelS := maestro.getModelStructure(modelZero)
/*
* Middleware Initial
*/
metaData := MiddlewareMetaData{}
mwInitial := utilsRunMiddlewaresInitial(maestro.MiddlewaresInitial, w, r, maestro, metaData, MIDDLEWARE_TYPE_COLLECTION)
if mwInitial.Error != nil {
SendError(w, http.StatusForbidden, *mwInitial.Error)
return
}
/*
* DB Connection
*/
db := maestro.dBPoolCallback(r, metaData)
if db == nil {
SendSingleError(w, http.StatusInternalServerError, "Database error!", "DATABASE_ERROR")
return
}
/*
* Search and Criterias
*/
db = getDBWithSearchCriterias(db, r, modelNew, modelType)
modelSlice := reflect.New(reflect.SliceOf(modelType))
if err := db.Find(modelSlice.Interface()).Error; err != nil {
SendSingleError(w, http.StatusForbidden, "There is an error in your query: "+err.Error(), "QUERY_ERROR")
return
}
modelSlice = modelSlice.Elem()
/*
* MiddlewareAfter
*/
rtrSlice := []interface{}{}
for i := 0; i < modelSlice.Len(); i++ {
modelGenerated, _, err := generateReturnModel(w, r, db, modelType, modelS, modelSlice.Index(i), maestro, metaData, MIDDLEWARE_TYPE_COLLECTION, true)
if err != nil {
SendError(w, http.StatusForbidden, *err)
return
}
rtrSlice = append(rtrSlice, modelGenerated)
}
SendData(w, http.StatusOK, MakeArrayDataStruct(modelType, rtrSlice, modelS))
})
}