diff --git a/support/list.go b/support/list.go new file mode 100644 index 0000000..ed7f002 --- /dev/null +++ b/support/list.go @@ -0,0 +1,99 @@ +package support + +import ( + "encoding/json" + "reflect" + + "git.fsdpf.net/go/contracts" + "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 { + this.data[k] = append(this.data[k], v) + } + } + + return nil +} + +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 + } + + for i := 0; i < len(items); i++ { + if items[i] == flag { + return true + } + } + + return false +} + +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{}} +}