105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package redisx
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// ---------------- 基础方法 ----------------
|
|
|
|
// Set 设置任意 key
|
|
func Set(key string, value interface{}, expire time.Duration) error {
|
|
return Client().Set(context.Background(), key, value, expire).Err()
|
|
}
|
|
|
|
// Get 获取任意 key 的值,返回 string
|
|
func Get(key string) (string, error) {
|
|
val, err := Client().Get(context.Background(), key).Result()
|
|
if errors.Is(err, redis.Nil) {
|
|
return "", nil
|
|
}
|
|
return val, err
|
|
}
|
|
|
|
// Delete 删除任意 key
|
|
func Delete(key string) error {
|
|
return Client().Del(context.Background(), key).Err()
|
|
}
|
|
|
|
// Exists 判断 key 是否存在
|
|
func Exists(key string) (bool, error) {
|
|
cnt, err := Client().Exists(context.Background(), key).Result()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return cnt > 0, nil
|
|
}
|
|
|
|
// ================== Space User / Role ==================
|
|
|
|
const (
|
|
RoleMember int32 = 1
|
|
RoleAdmin int32 = 5
|
|
RoleOwner int32 = 9
|
|
|
|
SpaceUserTTL = 10 * time.Minute
|
|
)
|
|
|
|
// space:user:{spaceId}:{userId}
|
|
func SpaceUserKey(spaceId int64, userId int64) string {
|
|
return fmt.Sprintf("space:user:%d:%d", spaceId, userId)
|
|
}
|
|
|
|
// Set / Create space user role
|
|
func SetSpaceUserRole(spaceId int64, userId int64, role int32) error {
|
|
key := SpaceUserKey(spaceId, userId)
|
|
return Set(key, role, SpaceUserTTL)
|
|
}
|
|
|
|
// Update space user role (same as set, semantic clarity)
|
|
func UpdateSpaceUserRole(spaceId int64, userId int64, role int32) error {
|
|
return SetSpaceUserRole(spaceId, userId, role)
|
|
}
|
|
|
|
// Get space user role
|
|
// return 0 means not exists
|
|
func GetSpaceUserRole(spaceId int64, userId int64) (int32, error) {
|
|
key := SpaceUserKey(spaceId, userId)
|
|
val, err := Get(key)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if val == "" {
|
|
return 0, nil
|
|
}
|
|
|
|
r, err := strconv.ParseInt(val, 10, 32)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return int32(r), nil
|
|
}
|
|
|
|
// Delete space user (kick / dissolve)
|
|
func DeleteSpaceUser(spaceId int64, userId int64) error {
|
|
key := SpaceUserKey(spaceId, userId)
|
|
return Delete(key)
|
|
}
|
|
|
|
// Exists space user
|
|
func ExistsSpaceUser(spaceId int64, userId int64) (bool, error) {
|
|
key := SpaceUserKey(spaceId, userId)
|
|
return Exists(key)
|
|
}
|
|
|
|
// Permission check
|
|
// owner > admin > member
|
|
func HasPermission(userRole int32, needRole int32) bool {
|
|
return userRole >= needRole
|
|
}
|