55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package util
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
"math/rand"
|
|
"time"
|
|
|
|
"management/internal/erpserver/model/view"
|
|
"management/internal/pkg/redis"
|
|
)
|
|
|
|
func GetCacheExpire() time.Duration {
|
|
return time.Hour*6 + time.Duration(rand.Intn(600))*time.Second // 6小时±10分钟
|
|
}
|
|
|
|
func GetOrSetCache(ctx context.Context, redis redis.Cache, key string, expire time.Duration, getData func() (any, error), result any) error {
|
|
if data, err := redis.GetBytes(ctx, key); err == nil {
|
|
return json.Unmarshal(data, result)
|
|
}
|
|
|
|
data, err := getData()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
bytes, err := json.Marshal(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := redis.Set(ctx, key, bytes, expire); err != nil {
|
|
log.Printf("Failed to set cache: %v", err)
|
|
}
|
|
|
|
return json.Unmarshal(bytes, result)
|
|
}
|
|
|
|
func BuildTree[T any](
|
|
parentID int32,
|
|
data []*T,
|
|
idFunc func(*T) int32,
|
|
childrenFunc func(*T, []*view.LayuiTree) *view.LayuiTree,
|
|
) []*view.LayuiTree {
|
|
var res []*view.LayuiTree
|
|
for _, item := range data {
|
|
if idFunc(item) == parentID {
|
|
childNodes := BuildTree[T](idFunc(item), data, idFunc, childrenFunc)
|
|
res = append(res, childrenFunc(item, childNodes))
|
|
}
|
|
}
|
|
return res
|
|
}
|