controller.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package usercache
  2. import (
  3. "context"
  4. "github.com/ente-io/museum/ente/cache"
  5. bonus "github.com/ente-io/museum/ente/storagebonus"
  6. "github.com/ente-io/museum/pkg/repo"
  7. "github.com/ente-io/museum/pkg/repo/storagebonus"
  8. "github.com/ente-io/stacktrace"
  9. )
  10. // Controller is the controller for the data cache.
  11. // It contains all the repositories that are used by the controller.
  12. // Avoid adding any direct dependencies to the other controller.
  13. type Controller struct {
  14. FileRepo *repo.FileRepository
  15. StoreBonusRepo *storagebonus.Repository
  16. UserCache *cache.UserCache
  17. }
  18. func (c *Controller) GetActiveStorageBonus(ctx context.Context, userID int64) (*bonus.ActiveStorageBonus, error) {
  19. // Check if the value is present in the cache
  20. if bonus, ok := c.UserCache.GetBonus(userID); ok {
  21. // Cache hit, update the cache asynchronously
  22. go func() {
  23. _, _ = c.getAndCacheActiveStorageBonus(ctx, userID)
  24. }()
  25. return bonus, nil
  26. }
  27. return c.getAndCacheActiveStorageBonus(ctx, userID)
  28. }
  29. func (c *Controller) getAndCacheActiveStorageBonus(ctx context.Context, userID int64) (*bonus.ActiveStorageBonus, error) {
  30. bonus, err := c.StoreBonusRepo.GetActiveStorageBonuses(ctx, userID)
  31. if err != nil {
  32. return nil, stacktrace.Propagate(err, "")
  33. }
  34. c.UserCache.SetBonus(userID, bonus)
  35. return bonus, nil
  36. }