-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
59 lines (47 loc) · 1.62 KB
/
context.go
File metadata and controls
59 lines (47 loc) · 1.62 KB
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
package gg
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"hppr.dev/gg/mdl"
"reflect"
)
type DefaultMap = map[string]interface{}
type ModelSchemaMap map[reflect.Type]schema.Schema
// GetSchema get the given gorm model schema from the schema map
func (m ModelSchemaMap) GetSchema(model interface{}) schema.Schema {
return m[reflect.TypeOf(model)]
}
// utility function that retrieves the gorm schema from the gin.Context
func GetModelSchema(ctx *gin.Context) schema.Schema {
return getContextVar("ModelSchema", ctx).(schema.Schema)
}
// utility funciton that retrieves the current model from the gin.Context
func GetModel(ctx *gin.Context) interface{} {
return getContextVar("Model", ctx)
}
// utility function that retreives the gorm.DB instance from the gin.Context
func GetDatabase(ctx *gin.Context) *gorm.DB {
return getContextVar("DB", ctx).(*gorm.DB)
}
// utility function that retreives the marshalling type from the gin.Context
func GetMarshalType(ctx *gin.Context) interface{} {
return getContextVar("MarshalType", ctx)
}
func getSchemaMap(ctx *gin.Context) ModelSchemaMap {
return getContextVar("SchemaMap", ctx).(ModelSchemaMap)
}
func getDefaultOutputFunction(ctx *gin.Context) output {
return getContextVar("DefaultOutput", ctx).(func(*gin.Context) output)(ctx)
}
func getContextVar(key string, ctx *gin.Context) interface{} {
value, _ := ctx.Get(key)
return value
}
func setupSchemaMap(cfg Config, db *gorm.DB) ModelSchemaMap {
var schemaMap = make(ModelSchemaMap)
for _, model := range cfg.Models {
schemaMap[reflect.TypeOf(model)] = mdl.GetDBSchema(model, db)
}
return schemaMap
}