From 553f327ae13917e0a1d04155e0f64f99e5496d96 Mon Sep 17 00:00:00 2001 From: what Date: Mon, 6 May 2024 13:43:35 +0800 Subject: [PATCH] =?UTF-8?q?[feat]=20=E6=96=B0=E5=A2=9E=20OperationAccess?= =?UTF-8?q?=20=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- support/list.go | 99 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 support/list.go 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{}} +}