Files
app-api/internal/cache/brand_cache.go
T

53 lines
1.1 KiB
Go
Raw Normal View History

2026-05-27 18:07:55 +08:00
package cache
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/luxsin/app-api/internal/model"
"github.com/redis/go-redis/v9"
)
const (
brandAllKey = "brand:all"
brandTTL = 30 * time.Minute
)
type BrandCache struct {
rdb *redis.Client
}
func NewBrandCache(rdb *redis.Client) *BrandCache {
return &BrandCache{rdb: rdb}
}
func (c *BrandCache) Exists(ctx context.Context) (bool, error) {
n, err := c.rdb.Exists(ctx, brandAllKey).Result()
if err != nil {
return false, err
}
return n > 0, nil
}
2026-05-27 18:07:55 +08:00
func (c *BrandCache) GetAll(ctx context.Context) ([]model.Brand, error) {
data, err := c.rdb.Get(ctx, brandAllKey).Bytes()
if err != nil {
return nil, err
}
var list []model.Brand
if err := json.Unmarshal(data, &list); err != nil {
return nil, fmt.Errorf("unmarshal brands: %w", err)
}
return list, nil
}
func (c *BrandCache) SetAll(ctx context.Context, list []model.Brand) error {
data, err := json.Marshal(list)
if err != nil {
return fmt.Errorf("marshal brands: %w", err)
}
return c.rdb.Set(ctx, brandAllKey, data, brandTTL).Err()
}