Explorar el Código

fix: add tests for redis getter auto type

Yeuoly hace 10 meses
padre
commit
01a9503fc2

+ 35 - 1
internal/utils/cache/redis_auto_type.go

@@ -8,6 +8,21 @@ import (
 	"github.com/redis/go-redis/v9"
 )
 
+// Set the value with key
+func AutoSet[T any](key string, value T, context ...redis.Cmdable) error {
+	if client == nil {
+		return ErrDBNotInit
+	}
+
+	full_type_info := reflect.TypeOf(value)
+	pkg_path := full_type_info.PkgPath()
+	type_name := full_type_info.Name()
+	full_type_name := pkg_path + "." + type_name
+
+	key = serialKey("auto_type", full_type_name, key)
+	return getCmdable(context...).Set(ctx, key, parser.MarshalJson(value), 0).Err()
+}
+
 // Get the value with key
 func AutoGet[T any](key string, context ...redis.Cmdable) (*T, error) {
 	return AutoGetWithGetter(key, func() (*T, error) {
@@ -25,7 +40,9 @@ func AutoGetWithGetter[T any](key string, getter func() (*T, error), context ...
 
 	// fetch full type info
 	full_type_info := reflect.TypeOf(result_tmpl)
-	full_type_name := full_type_info.Name()
+	pkg_path := full_type_info.PkgPath()
+	type_name := full_type_info.Name()
+	full_type_name := pkg_path + "." + type_name
 
 	key = serialKey("auto_type", full_type_name, key)
 	val, err := getCmdable(context...).Get(ctx, key).Result()
@@ -47,3 +64,20 @@ func AutoGetWithGetter[T any](key string, getter func() (*T, error), context ...
 	result, err := parser.UnmarshalJson[T](val)
 	return &result, err
 }
+
+// Delete the value with key
+func AutoDelete[T any](key string, context ...redis.Cmdable) error {
+	if client == nil {
+		return ErrDBNotInit
+	}
+
+	var result_tmpl T
+
+	full_type_info := reflect.TypeOf(result_tmpl)
+	pkg_path := full_type_info.PkgPath()
+	type_name := full_type_info.Name()
+	full_type_name := pkg_path + "." + type_name
+
+	key = serialKey("auto_type", full_type_name, key)
+	return getCmdable(context...).Del(ctx, key).Err()
+}

+ 28 - 0
internal/utils/cache/redis_auto_type_test.go

@@ -0,0 +1,28 @@
+package cache
+
+import "testing"
+
+type TestAutoTypeStruct struct {
+	ID string `json:"id"`
+}
+
+func TestAutoType(t *testing.T) {
+	if err := InitRedisClient("127.0.0.1:6379", "difyai123456"); err != nil {
+		t.Fatal(err)
+	}
+	defer Close()
+
+	err := AutoSet("test", TestAutoTypeStruct{ID: "123"})
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	result, err := AutoGet[TestAutoTypeStruct]("test")
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if result.ID != "123" {
+		t.Fatal("result not correct")
+	}
+}