cosy.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package cosy
  2. import (
  3. "github.com/0xJacky/Nginx-UI/internal/logger"
  4. "github.com/gin-gonic/gin"
  5. "github.com/go-playground/validator/v10"
  6. "gorm.io/gorm"
  7. )
  8. var validate *validator.Validate
  9. func init() {
  10. validate = validator.New()
  11. }
  12. type Ctx[T any] struct {
  13. ctx *gin.Context
  14. rules gin.H
  15. Payload map[string]interface{}
  16. Model T
  17. OriginModel T
  18. table string
  19. tableArgs []interface{}
  20. abort bool
  21. nextHandler *gin.HandlerFunc
  22. skipAssociationsOnCreate bool
  23. beforeDecodeHookFunc []func(ctx *Ctx[T])
  24. beforeExecuteHookFunc []func(ctx *Ctx[T])
  25. executedHookFunc []func(ctx *Ctx[T])
  26. gormScopes []func(tx *gorm.DB) *gorm.DB
  27. preloads []string
  28. scan func(tx *gorm.DB) any
  29. transformer func(*T) any
  30. permanentlyDelete bool
  31. SelectedFields []string
  32. itemKey string
  33. }
  34. func Core[T any](c *gin.Context) *Ctx[T] {
  35. return &Ctx[T]{
  36. ctx: c,
  37. gormScopes: make([]func(tx *gorm.DB) *gorm.DB, 0),
  38. beforeExecuteHookFunc: make([]func(ctx *Ctx[T]), 0),
  39. beforeDecodeHookFunc: make([]func(ctx *Ctx[T]), 0),
  40. itemKey: "`id`",
  41. skipAssociationsOnCreate: true,
  42. }
  43. }
  44. func (c *Ctx[T]) SetTable(table string, args ...interface{}) *Ctx[T] {
  45. c.table = table
  46. c.tableArgs = args
  47. return c
  48. }
  49. func (c *Ctx[T]) SetItemKey(key string) *Ctx[T] {
  50. c.itemKey = key
  51. return c
  52. }
  53. func (c *Ctx[T]) SetValidRules(rules gin.H) *Ctx[T] {
  54. c.rules = rules
  55. return c
  56. }
  57. func (c *Ctx[T]) SetPreloads(args ...string) *Ctx[T] {
  58. c.preloads = append(c.preloads, args...)
  59. return c
  60. }
  61. func (c *Ctx[T]) validate() (errs gin.H) {
  62. c.Payload = make(gin.H)
  63. _ = c.ctx.ShouldBindJSON(&c.Payload)
  64. errs = validate.ValidateMap(c.Payload, c.rules)
  65. if len(errs) > 0 {
  66. logger.Debug(errs)
  67. for k := range errs {
  68. errs[k] = c.rules[k]
  69. }
  70. return
  71. }
  72. // Make sure that the key in c.Payload is also the key of rules
  73. validated := make(map[string]interface{})
  74. for k, v := range c.Payload {
  75. if _, ok := c.rules[k]; ok {
  76. validated[k] = v
  77. }
  78. }
  79. c.Payload = validated
  80. return
  81. }
  82. func (c *Ctx[T]) SetScan(scan func(tx *gorm.DB) any) *Ctx[T] {
  83. c.scan = scan
  84. return c
  85. }
  86. func (c *Ctx[T]) SetTransformer(t func(m *T) any) *Ctx[T] {
  87. c.transformer = t
  88. return c
  89. }
  90. func (c *Ctx[T]) AbortWithError(err error) {
  91. c.abort = true
  92. errHandler(c.ctx, err)
  93. }
  94. func (c *Ctx[T]) Abort() {
  95. c.abort = true
  96. }