Skip to content

Commit 85da74b

Browse files
committed
enhance: update gonginx and cosy to latest version
1 parent af9395a commit 85da74b

39 files changed

+798
-661
lines changed

api/cosy/cosy.go

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,34 +14,45 @@ func init() {
1414
}
1515

1616
type Ctx[T any] struct {
17-
ctx *gin.Context
18-
rules gin.H
19-
Payload map[string]interface{}
20-
Model T
21-
abort bool
22-
nextHandler *gin.HandlerFunc
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
17+
ctx *gin.Context
18+
rules gin.H
19+
Payload map[string]interface{}
20+
Model T
21+
OriginModel T
22+
table string
23+
tableArgs []interface{}
24+
abort bool
25+
nextHandler *gin.HandlerFunc
26+
skipAssociationsOnCreate bool
27+
beforeDecodeHookFunc []func(ctx *Ctx[T])
28+
beforeExecuteHookFunc []func(ctx *Ctx[T])
29+
executedHookFunc []func(ctx *Ctx[T])
30+
gormScopes []func(tx *gorm.DB) *gorm.DB
31+
preloads []string
32+
scan func(tx *gorm.DB) any
33+
transformer func(*T) any
34+
permanentlyDelete bool
35+
SelectedFields []string
36+
itemKey string
3337
}
3438

3539
func Core[T any](c *gin.Context) *Ctx[T] {
3640
return &Ctx[T]{
37-
ctx: c,
38-
gormScopes: make([]func(tx *gorm.DB) *gorm.DB, 0),
39-
beforeExecuteHookFunc: make([]func(ctx *Ctx[T]), 0),
40-
beforeDecodeHookFunc: make([]func(ctx *Ctx[T]), 0),
41-
itemKey: "`id`",
41+
ctx: c,
42+
gormScopes: make([]func(tx *gorm.DB) *gorm.DB, 0),
43+
beforeExecuteHookFunc: make([]func(ctx *Ctx[T]), 0),
44+
beforeDecodeHookFunc: make([]func(ctx *Ctx[T]), 0),
45+
itemKey: "`id`",
46+
skipAssociationsOnCreate: true,
4247
}
4348
}
4449

50+
func (c *Ctx[T]) SetTable(table string, args ...interface{}) *Ctx[T] {
51+
c.table = table
52+
c.tableArgs = args
53+
return c
54+
}
55+
4556
func (c *Ctx[T]) SetItemKey(key string) *Ctx[T] {
4657
c.itemKey = key
4758
return c

api/cosy/create.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
package cosy
22

33
import (
4+
"github.com/gin-gonic/gin"
45
"github.com/0xJacky/Nginx-UI/api/cosy/map2struct"
56
"github.com/0xJacky/Nginx-UI/model"
6-
"github.com/gin-gonic/gin"
77
"gorm.io/gorm/clause"
88
"net/http"
99
)
@@ -41,8 +41,11 @@ func (c *Ctx[T]) Create() {
4141
return
4242
}
4343

44-
// skip all associations
45-
err = db.Omit(clause.Associations).Create(&c.Model).Error
44+
if c.skipAssociationsOnCreate {
45+
err = db.Omit(clause.Associations).Create(&c.Model).Error
46+
} else {
47+
err = db.Create(&c.Model).Error
48+
}
4649

4750
if err != nil {
4851
errHandler(c.ctx, err)
@@ -53,7 +56,7 @@ func (c *Ctx[T]) Create() {
5356
for _, v := range c.preloads {
5457
tx = tx.Preload(v)
5558
}
56-
tx.First(&c.Model)
59+
tx.Table(c.table, c.tableArgs...).First(&c.Model)
5760

5861
if len(c.executedHookFunc) > 0 {
5962
for _, v := range c.executedHookFunc {
@@ -70,3 +73,8 @@ func (c *Ctx[T]) Create() {
7073
c.ctx.JSON(http.StatusOK, c.Model)
7174
}
7275
}
76+
77+
func (c *Ctx[T]) WithAssociations() *Ctx[T] {
78+
c.skipAssociationsOnCreate = false
79+
return c
80+
}

api/cosy/custom.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package cosy
22

33
import (
4-
"github.com/0xJacky/Nginx-UI/api/cosy/map2struct"
54
"github.com/gin-gonic/gin"
5+
"github.com/0xJacky/Nginx-UI/api/cosy/map2struct"
66
"net/http"
77
)
88

api/cosy/delete.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,13 @@ func (c *Ctx[T]) Destroy() {
2727
result = result.Scopes(c.gormScopes...)
2828
}
2929

30-
err := result.Session(&gorm.Session{}).First(&dbModel, id).Error
30+
var err error
31+
session := result.Session(&gorm.Session{})
32+
if c.table != "" {
33+
err = session.Table(c.table, c.tableArgs...).Take(&dbModel, id).Error
34+
} else {
35+
err = session.First(&dbModel, id).Error
36+
}
3137

3238
if err != nil {
3339
errHandler(c.ctx, err)
@@ -73,7 +79,13 @@ func (c *Ctx[T]) Recover() {
7379
result = result.Scopes(c.gormScopes...)
7480
}
7581

76-
err := result.Session(&gorm.Session{}).First(&dbModel, id).Error
82+
var err error
83+
session := result.Session(&gorm.Session{})
84+
if c.table != "" {
85+
err = session.Table(c.table).Take(&dbModel, id).Error
86+
} else {
87+
err = session.First(&dbModel, id).Error
88+
}
7789

7890
if err != nil {
7991
errHandler(c.ctx, err)

api/cosy/error.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ package cosy
22

33
import (
44
"errors"
5-
"github.com/0xJacky/Nginx-UI/internal/logger"
65
"github.com/gin-gonic/gin"
6+
"github.com/0xJacky/Nginx-UI/internal/logger"
77
"go.uber.org/zap"
88
"gorm.io/gorm"
99
"net/http"

api/cosy/filter.go

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ package cosy
22

33
import (
44
"fmt"
5-
"github.com/0xJacky/Nginx-UI/internal/logger"
65
"github.com/gin-gonic/gin"
6+
"github.com/0xJacky/Nginx-UI/internal/logger"
77
"gorm.io/gorm"
8+
"gorm.io/gorm/clause"
89
"strings"
910
)
1011

@@ -63,16 +64,17 @@ func QueryToInSearch(c *gin.Context, db *gorm.DB, keys ...string) *gorm.DB {
6364
if len(queryArray) == 0 {
6465
queryArray = c.QueryArray(v)
6566
}
66-
if len(queryArray) > 0 {
67-
var sb strings.Builder
67+
if len(queryArray) == 1 && queryArray[0] == "" {
68+
continue
69+
}
70+
if len(queryArray) >= 1 {
71+
var builder strings.Builder
72+
stmt := db.Statement
6873

69-
_, err := fmt.Fprintf(&sb, "`%s` IN ?", v)
70-
if err != nil {
71-
logger.Error(err)
72-
continue
73-
}
74+
stmt.QuoteTo(&builder, clause.Column{Table: stmt.Table, Name: v})
75+
builder.WriteString(" IN ?")
7476

75-
db = db.Where(sb.String(), queryArray)
77+
db = db.Where(builder.String(), queryArray)
7678
}
7779
}
7880
return db
@@ -148,7 +150,10 @@ func QueryToOrInSearch(c *gin.Context, db *gorm.DB, keys ...string) *gorm.DB {
148150
if len(queryArray) == 0 {
149151
queryArray = c.QueryArray(v)
150152
}
151-
if len(queryArray) > 0 {
153+
if len(queryArray) == 1 && queryArray[0] == "" {
154+
continue
155+
}
156+
if len(queryArray) >= 1 {
152157
var sb strings.Builder
153158

154159
_, err := fmt.Fprintf(&sb, "`%s` IN ?", v)

api/cosy/list.go

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,11 @@ func GetPagingParams(c *gin.Context) (page, offset, pageSize int) {
2525
}
2626

2727
func (c *Ctx[T]) combineStdSelectorRequest() {
28-
var StdSelectorInitParams struct {
29-
ID []int `json:"id"`
30-
}
28+
StdSelectorInitID := c.ctx.QueryArray("id[]")
3129

32-
_ = c.ctx.ShouldBindJSON(&StdSelectorInitParams)
33-
if len(StdSelectorInitParams.ID) > 0 {
30+
if len(StdSelectorInitID) > 0 {
3431
c.GormScope(func(tx *gorm.DB) *gorm.DB {
35-
return tx.Where(c.itemKey+" IN ?", StdSelectorInitParams.ID)
32+
return tx.Where(c.itemKey+" IN ?", StdSelectorInitID)
3633
})
3734
}
3835
}
@@ -62,6 +59,9 @@ func (c *Ctx[T]) result() (*gorm.DB, bool) {
6259
}
6360

6461
result = result.Model(&dbModel)
62+
if c.table != "" {
63+
result = result.Table(c.table, c.tableArgs...)
64+
}
6565

6666
c.combineStdSelectorRequest()
6767

@@ -72,16 +72,30 @@ func (c *Ctx[T]) result() (*gorm.DB, bool) {
7272
return result, true
7373
}
7474

75-
func (c *Ctx[T]) ListAllData() ([]*T, bool) {
75+
func (c *Ctx[T]) ListAllData() (data any, ok bool) {
7676
result, ok := c.result()
7777
if !ok {
7878
return nil, false
7979
}
8080

8181
result = result.Scopes(c.SortOrder())
82-
models := make([]*T, 0)
83-
result.Find(&models)
84-
return models, true
82+
if c.scan == nil {
83+
models := make([]*T, 0)
84+
result.Find(&models)
85+
86+
if c.transformer != nil {
87+
transformed := make([]any, 0)
88+
for k := range models {
89+
transformed = append(transformed, c.transformer(models[k]))
90+
}
91+
data = transformed
92+
} else {
93+
data = models
94+
}
95+
} else {
96+
data = c.scan(result)
97+
}
98+
return data, true
8599
}
86100

87101
func (c *Ctx[T]) PagingListData() (*model.DataList, bool) {
@@ -90,11 +104,11 @@ func (c *Ctx[T]) PagingListData() (*model.DataList, bool) {
90104
return nil, false
91105
}
92106

93-
result = result.Scopes(c.OrderAndPaginate())
107+
scopesResult := result.Session(&gorm.Session{}).Scopes(c.OrderAndPaginate())
94108
data := &model.DataList{}
95109
if c.scan == nil {
96110
models := make([]*T, 0)
97-
result.Find(&models)
111+
scopesResult.Find(&models)
98112

99113
if c.transformer != nil {
100114
transformed := make([]any, 0)
@@ -106,9 +120,12 @@ func (c *Ctx[T]) PagingListData() (*model.DataList, bool) {
106120
data.Data = models
107121
}
108122
} else {
109-
data.Data = c.scan(result)
123+
data.Data = c.scan(scopesResult)
110124
}
111125

126+
var totalRecords int64
127+
result.Session(&gorm.Session{}).Count(&totalRecords)
128+
112129
page := cast.ToInt(c.ctx.Query("page"))
113130
if page == 0 {
114131
page = 1
@@ -119,9 +136,6 @@ func (c *Ctx[T]) PagingListData() (*model.DataList, bool) {
119136
pageSize = cast.ToInt(reqPageSize)
120137
}
121138

122-
var totalRecords int64
123-
result.Session(&gorm.Session{}).Count(&totalRecords)
124-
125139
data.Pagination = model.Pagination{
126140
Total: totalRecords,
127141
PerPage: pageSize,
@@ -137,3 +151,15 @@ func (c *Ctx[T]) PagingList() {
137151
c.ctx.JSON(http.StatusOK, data)
138152
}
139153
}
154+
155+
// EmptyPagingList return empty list
156+
func (c *Ctx[T]) EmptyPagingList() {
157+
pageSize := settings.ServerSettings.PageSize
158+
if reqPageSize := c.ctx.Query("page_size"); reqPageSize != "" {
159+
pageSize = cast.ToInt(reqPageSize)
160+
}
161+
162+
data := &model.DataList{Data: make([]any, 0)}
163+
data.Pagination.PerPage = pageSize
164+
c.ctx.JSON(http.StatusOK, data)
165+
}

api/cosy/map2struct/hook.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@ import (
44
"github.com/mitchellh/mapstructure"
55
"github.com/shopspring/decimal"
66
"github.com/spf13/cast"
7+
"gopkg.in/guregu/null.v4"
78
"reflect"
89
"time"
910
)
1011

1112
var timeLocation *time.Location
1213

1314
func init() {
14-
timeLocation = time.Local
15+
timeLocation, _ = time.LoadLocation("Asia/Shanghai")
1516
}
1617

1718
func ToTimeHookFunc() mapstructure.DecodeHookFunc {
@@ -54,3 +55,13 @@ func ToDecimalHookFunc() mapstructure.DecodeHookFunc {
5455
return data, nil
5556
}
5657
}
58+
59+
func ToNullableStringHookFunc() mapstructure.DecodeHookFunc {
60+
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
61+
if t == reflect.TypeOf(null.String{}) {
62+
return null.StringFrom(data.(string)), nil
63+
}
64+
65+
return data, nil
66+
}
67+
}

api/cosy/map2struct/map2struct.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ func WeakDecode(input, output interface{}) error {
1010
Result: output,
1111
WeaklyTypedInput: true,
1212
DecodeHook: mapstructure.ComposeDecodeHookFunc(
13-
ToDecimalHookFunc(), ToTimeHookFunc(),
13+
ToDecimalHookFunc(), ToTimeHookFunc(), ToNullableStringHookFunc(),
1414
),
1515
TagName: "json",
1616
}

api/cosy/order.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ func (c *Ctx[T]) UpdateOrder() {
2222

2323
db := model.UseDB()
2424

25+
if c.table != "" {
26+
db = db.Table(c.table, c.tableArgs...)
27+
}
28+
2529
// update target
2630
err := db.Model(&c.Model).Where("id = ?", json.TargetID).Update("order_id", gorm.Expr("order_id + ?", affectedLen*(-json.Direction))).Error
2731

0 commit comments

Comments
 (0)