70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"spark-server/internal/pkg/errs"
|
|
)
|
|
|
|
const (
|
|
codeKeyPrefix = "sms:code:"
|
|
codeCDPrefix = "sms:cd:"
|
|
)
|
|
|
|
type RedisStore struct {
|
|
rdb *redis.Client
|
|
}
|
|
|
|
func NewRedisStore(rdb *redis.Client) *RedisStore {
|
|
return &RedisStore{rdb: rdb}
|
|
}
|
|
|
|
func (r *RedisStore) Put(ctx context.Context, key, code string, ttlSeconds int) error {
|
|
if r == nil || r.rdb == nil {
|
|
return errs.ErrAvailable
|
|
}
|
|
k := codeKeyPrefix + key
|
|
if err := r.rdb.Set(ctx, k, code, time.Duration(ttlSeconds)*time.Second).Err(); err != nil {
|
|
return errs.ErrAvailable.WithError("sms-code", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *RedisStore) Get(ctx context.Context, key string) (string, error) {
|
|
if r == nil || r.rdb == nil {
|
|
return "", errs.ErrAvailable
|
|
}
|
|
v, err := r.rdb.Get(ctx, codeKeyPrefix+key).Result()
|
|
if err == redis.Nil {
|
|
return "", nil
|
|
}
|
|
if err != nil {
|
|
return "", errs.ErrAvailable.WithError("sms-code", err)
|
|
}
|
|
return v, nil
|
|
}
|
|
|
|
func (r *RedisStore) Del(ctx context.Context, key string) error {
|
|
if r == nil || r.rdb == nil {
|
|
return errs.ErrAvailable
|
|
}
|
|
if err := r.rdb.Del(ctx, codeKeyPrefix+key, codeCDPrefix+key).Err(); err != nil {
|
|
return errs.ErrAvailable.WithError("sms-code", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *RedisStore) SetCooldown(ctx context.Context, key string, ttlSeconds int) (bool, error) {
|
|
if r == nil || r.rdb == nil {
|
|
return false, errs.ErrAvailable
|
|
}
|
|
ok, err := r.rdb.SetNX(ctx, codeCDPrefix+key, "1", time.Duration(ttlSeconds)*time.Second).Result()
|
|
if err != nil {
|
|
return false, errs.ErrAvailable.WithError("sms-code", err)
|
|
}
|
|
return ok, nil
|
|
}
|