dashboard_cache.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package repository
  2. import (
  3. "context"
  4. "strings"
  5. "time"
  6. "github.com/Wei-Shaw/sub2api/internal/config"
  7. "github.com/Wei-Shaw/sub2api/internal/service"
  8. "github.com/redis/go-redis/v9"
  9. )
  10. const dashboardStatsCacheKey = "dashboard:stats:v1"
  11. type dashboardCache struct {
  12. rdb *redis.Client
  13. keyPrefix string
  14. }
  15. func NewDashboardCache(rdb *redis.Client, cfg *config.Config) service.DashboardStatsCache {
  16. prefix := "sub2api:"
  17. if cfg != nil {
  18. prefix = strings.TrimSpace(cfg.Dashboard.KeyPrefix)
  19. }
  20. if prefix != "" && !strings.HasSuffix(prefix, ":") {
  21. prefix += ":"
  22. }
  23. return &dashboardCache{
  24. rdb: rdb,
  25. keyPrefix: prefix,
  26. }
  27. }
  28. func (c *dashboardCache) GetDashboardStats(ctx context.Context) (string, error) {
  29. val, err := c.rdb.Get(ctx, c.buildKey()).Result()
  30. if err != nil {
  31. if err == redis.Nil {
  32. return "", service.ErrDashboardStatsCacheMiss
  33. }
  34. return "", err
  35. }
  36. return val, nil
  37. }
  38. func (c *dashboardCache) SetDashboardStats(ctx context.Context, data string, ttl time.Duration) error {
  39. return c.rdb.Set(ctx, c.buildKey(), data, ttl).Err()
  40. }
  41. func (c *dashboardCache) buildKey() string {
  42. if c.keyPrefix == "" {
  43. return dashboardStatsCacheKey
  44. }
  45. return c.keyPrefix + dashboardStatsCacheKey
  46. }
  47. func (c *dashboardCache) DeleteDashboardStats(ctx context.Context) error {
  48. return c.rdb.Del(ctx, c.buildKey()).Err()
  49. }