/
crudmgr.go
354 lines (290 loc) · 8.85 KB
/
crudmgr.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package crudmgr
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"runtime/debug"
"github.com/digitalcircle-com-br/foundation/lib/ctxmgr"
"github.com/digitalcircle-com-br/foundation/lib/fmodel"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
)
const (
OP_C = "C"
OP_R = "R"
OP_U = "U"
OP_D = "D"
OP_AA = "AA"
OP_AD = "AD"
)
// func findAll[T any](db *gorm.DB) ([]T, error) {
// var ret = make([]T, 0)
// err := db.Find(&ret).Error
// return ret, err
// }
// func findByID[T any](db *gorm.DB, id string) (T, error) {
// ret := new(T)
// err := db.Where("id = ?", id).First(ret).Error
// return *ret, err
// }
// func create[T any](db *gorm.DB, t T) error {
// return db.Create(t).Error
// }
// func update[T any](db *gorm.DB, t T) error {
// return db.Updates(&t).Error
// }
// func delete[T any](db *gorm.DB, id string) error {
// return db.Where("id = ?", id).Delete(new(T)).Error
// }
// func Setup[T any](db *gorm.DB, nr *mux.Router, path string, t T) {
// logrus.Infof("Setting up route %s", path)
// nr.Methods(http.MethodGet).Path(path + "/{id}").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// ret, err := findByID[T](db, mux.Vars(request)["id"])
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// json.NewEncoder(writer).Encode(ret)
// })
// nr.Methods(http.MethodDelete).Path(path + "/{id}").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// err := delete[T](db, mux.Vars(request)["id"])
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// json.NewEncoder(writer).Encode("ok")
// })
// nr.Methods(http.MethodGet).Path(path).HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// ret, err := findAll[T](db)
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// json.NewEncoder(writer).Encode(ret)
// })
// nr.Methods(http.MethodPost).Path(path).HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// at := new(T)
// err := json.NewDecoder(request.Body).Decode(at)
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// err = create(db, at)
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// json.NewEncoder(writer).Encode(at)
// })
// nr.Methods(http.MethodPut).Path(path).HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// at := new(T)
// err := json.NewDecoder(request.Body).Decode(at)
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// err = update(db, at)
// if err != nil {
// http.Error(writer, err.Error(), http.StatusInternalServerError)
// return
// }
// json.NewEncoder(writer).Encode(at)
// })
// }
type CrudOpts struct {
Op string `json:"op"` // OP - can be C R U OR D
Db string `json:"db"` // REsolved by server, nevermind
Tb string `json:"tb"` // Table name
Where []interface{} `json:"where"` // Where clause - []interface{}{"id =?" , my_var_id}
ID interface{} `json:"id"` // When dealing w ID required ops, this is mandatory (update, delete)
Data interface{} `json:"data"` // Object with data to be managed
Cols []interface{} `json:"cols"` // Define cols returned by select
Associations []string `json:"associations"` // See gorm docs - https://gorm.io/docs/
PageSize int `json:"pagesize"` // Offset for selected records
Page int `json:"page"`
AssociationTable string `json:"association_table"`
AssociationFieldA string `json:"association_field_a"`
AssociationFieldB string `json:"association_field_b"`
AssociationIDA uint `json:"association_id_a"`
AssociationIDB uint `json:"association_id_b"`
Debug bool `json:"debug"`
AutoPreload bool `json:"auto_preload"`
//dataObj fmodel.VO
}
type CrudResponse struct {
Data interface{} `json:"data"`
RowsAffected int64 `json:"rowsaffected"`
}
func retrieve[T any](db *gorm.DB, opts *CrudOpts) (interface{}, error) {
if opts.PageSize == 0 || opts.PageSize > 1000 {
opts.PageSize = 1000
}
if opts.Page < 1 {
opts.Page = 1
}
offset := (opts.Page - 1) * opts.PageSize
var ret []T //:= make([]T, 0) //reflect.MakeSlice(reflect.SliceOf(tp), 0, opts.PageSize).Interface()
//ret := make([]T, 0)
model := new(T)
tx := db.Model(model)
if opts.Debug {
tx = tx.Debug()
}
switch {
case opts.Where != nil && len(opts.Where) == 1:
tx = tx.Where(opts.Where)
case opts.Where != nil && len(opts.Where) > 1:
tx = tx.Where(opts.Where[0], opts.Where[1:]...)
}
switch {
case opts.AutoPreload:
tx = tx.Set("gorm:auto_preload", true)
default:
for _, assoc := range opts.Associations {
logrus.Debugf("Loading association: [%s]", assoc)
tx = tx.Preload(assoc)
}
}
err := tx.Limit(opts.PageSize).Offset(offset).Find(&ret).Error
return CrudResponse{Data: ret}, err
}
func create(db *gorm.DB, opts *CrudOpts) (interface{}, error) {
if opts.Debug {
db = db.Debug()
}
err := db.Table(opts.Tb).Create(opts.Data).Error
return CrudResponse{Data: []interface{}{opts.Data}}, err
}
func update(db *gorm.DB, opts *CrudOpts) (interface{}, error) {
if opts.Debug {
db = db.Debug()
}
tx := db.Table(opts.Tb).Where("id = ?", opts.ID).Updates(opts.Data)
ret := CrudResponse{
Data: nil,
RowsAffected: tx.RowsAffected,
}
return ret, tx.Error
}
func delete(db *gorm.DB, opts *CrudOpts) (interface{}, error) {
if opts.Debug {
db = db.Debug()
}
tx := db.Exec(fmt.Sprintf("delete from %s where id = ?", opts.Tb), opts.ID)
ret := CrudResponse{
Data: nil,
RowsAffected: tx.RowsAffected,
}
return ret, tx.Error
}
func associationAssociate(db *gorm.DB, opts *CrudOpts) (interface{}, error) {
err := db.Exec(fmt.Sprintf("insert into \"%s\"(\"%s\",\"%s\") values (?,?)",
opts.AssociationTable,
opts.AssociationFieldA,
opts.AssociationFieldB), opts.AssociationIDA, opts.AssociationIDB).Error
return nil, err
}
func associationDissociate(db *gorm.DB, opts *CrudOpts) (interface{}, error) {
err := db.Exec(fmt.Sprintf("delete from \"%s\" where \"%s\" = ? and \"%s\" = ?",
opts.AssociationTable,
opts.AssociationFieldA,
opts.AssociationFieldB), opts.AssociationIDA, opts.AssociationIDB).Error
return nil, err
}
func MustHandle[T any](r *mux.Router, db *gorm.DB, a T) {
err := Handle(r, db, a)
if err != nil {
panic(err)
}
}
var defaultTenant = ""
func SetDefaultTenant(t string) {
defaultTenant = t
}
func handle[T any](db *gorm.DB, tb string, w http.ResponseWriter, r *http.Request) error {
defer func() {
r.Body.Close()
r := recover()
if r != nil {
msg := fmt.Sprintf("Recovering from: %v\n%s ", r, string(debug.Stack()))
logrus.Warnf(msg)
http.Error(w, msg, http.StatusInternalServerError)
}
}()
sess := ctxmgr.Session(r.Context())
if sess == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return nil
}
opts := new(CrudOpts)
buf := &bytes.Buffer{}
io.Copy(buf, r.Body)
err := json.Unmarshal(buf.Bytes(), opts)
if err != nil {
return err
}
_, ok := sess.Perms[fmodel.PermDef("crud."+tb+"."+opts.Op)]
if !ok {
_, ok = sess.Perms[fmodel.PERM_ROOT]
}
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return nil
}
//typeData := reflect.New(tp).Interface()
typeData := new(T)
bs, _ := json.Marshal(opts.Data)
json.Unmarshal(bs, typeData)
opts.Data = typeData
//no := reflect.New(tp).Interface()
if defaultTenant == "" {
opts.Db = sess.Tenant
} else {
opts.Db = defaultTenant
}
log.Printf("using tb: %s", tb)
opts.Tb = tb
var ret interface{}
switch opts.Op {
case OP_C:
ret, err = create(db, opts)
case OP_R:
ret, err = retrieve[T](db, opts)
case OP_U:
ret, err = update(db, opts)
case OP_D:
ret, err = delete(db, opts)
case OP_AA:
ret, err = associationAssociate(db, opts)
case OP_AD:
ret, err = associationDissociate(db, opts)
default:
http.Error(w, "Unknown op: "+opts.Op, http.StatusBadRequest)
return nil
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
json.NewEncoder(w).Encode(ret)
return nil
}
func Handle[T any](r *mux.Router, db *gorm.DB, a T) error {
stmt := &gorm.Statement{DB: db}
stmt.Parse(a)
tb := stmt.Schema.Table
logrus.Infof("Registering route %s for CRUD %T", tb, a)
r.Name("crud_" + tb).Methods(http.MethodPost).Path("/" + tb).HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
err := handle[T](db, tb, w, r)
if err != nil {
logrus.Error(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
return nil
}