contracts/support/list.go

102 lines
1.9 KiB
Go
Raw Normal View History

2024-05-06 13:43:35 +08:00
package support
import (
"encoding/json"
"reflect"
"git.fsdpf.net/go/contracts"
"github.com/samber/lo"
2024-05-06 13:43:35 +08:00
"github.com/spf13/cast"
)
type OperationAccess struct {
typ reflect.Kind // 只能为 reflect.Int 和 reflect.String
data map[string][]any
}
func (this OperationAccess) Get(k string) []any {
items, ok := this.data[k]
if !ok {
return nil
}
return items
}
func (this *OperationAccess) Set(k string, v []any) error {
this.data[k] = []any{}
return this.Push(k, v...)
}
func (this *OperationAccess) Push(k string, input ...any) error {
if _, ok := this.data[k]; !ok {
this.Set(k, []any{})
}
for i := 0; i < len(input); i++ {
if v, err := this.Convert(input[i]); err != nil {
return err
} else if !lo.Contains(this.data[k], v) {
2024-05-06 13:43:35 +08:00
this.data[k] = append(this.data[k], v)
}
}
return nil
}
func (this OperationAccess) Merge(item OperationAccess) error {
for k, v := range item.data {
this.Push(k, v...)
}
return nil
}
2024-05-06 13:43:35 +08:00
func (this OperationAccess) Convert(v any) (any, error) {
if this.typ == reflect.Int {
return cast.ToIntE(v)
}
return cast.ToStringE(v)
}
func (this OperationAccess) Exist(k string, v any) bool {
items, ok := this.data[k]
if !ok {
return false
}
flag, err := this.Convert(v)
if err != nil {
return false
}
return lo.Contains(items, flag)
2024-05-06 13:43:35 +08:00
}
func (this OperationAccess) MarshalJSON() ([]byte, error) {
temp := [][2]any{}
for k, v := range this.data {
temp = append(temp, [2]any{k, v})
}
return json.Marshal(temp)
}
func NewOperationAccess(m contracts.Model) OperationAccess {
// 主键类型
tPkType := reflect.String
if tPk, ok := GetStructField(m.GetQueryFieldsStruct(), m.GetPrimaryKey()); ok {
switch tPk.Type.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint32, reflect.Uint64:
tPkType = reflect.Int
}
}
return OperationAccess{typ: tPkType, data: map[string][]any{}}
}