Skip to content

Commit

Permalink
upd
Browse files Browse the repository at this point in the history
  • Loading branch information
Satont committed Dec 16, 2024
1 parent 7926c6a commit d752b05
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 34 deletions.
2 changes: 2 additions & 0 deletions apps/api-gql/internal/delivery/http-public/public/badges.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ type badgeWithUsers struct {
Users []string `json:"users"`
}

// TODO: use some gin middleware for cache response

func (p *Public) HandleBadgesGet(c *gin.Context) {
entities, err := p.badgesWithUsersService.GetMany(
c.Request.Context(),
Expand Down
34 changes: 0 additions & 34 deletions apps/api-gql/internal/services/badges-users/badges-users.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ package badges_users

import (
"context"
"time"

"github.com/goccy/go-json"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/twirapp/twir/apps/api-gql/internal/entity"
badges_users "github.com/twirapp/twir/libs/repositories/badges-users"
"github.com/twirapp/twir/libs/repositories/badges-users/model"
Expand All @@ -17,19 +14,16 @@ type Opts struct {
fx.In

BadgesUsersRepository badges_users.Repository
Redis *redis.Client
}

func New(opts Opts) *Service {
return &Service{
badgesUsersRepository: opts.BadgesUsersRepository,
redis: opts.Redis,
}
}

type Service struct {
badgesUsersRepository badges_users.Repository
redis *redis.Client
}

type GetManyInput struct {
Expand All @@ -45,19 +39,7 @@ func modelToEntity(b model.BadgeUser) entity.BadgeUser {
}
}

const badgeUsersCacheKey = "cache:twir:badges_users:"

func (c *Service) GetMany(ctx context.Context, input GetManyInput) ([]entity.BadgeUser, error) {
cachedUsers, _ := c.redis.Get(ctx, badgeUsersCacheKey+input.BadgeID.String()).Bytes()
if len(cachedUsers) > 0 {
var result []entity.BadgeUser
if err := json.Unmarshal(cachedUsers, &result); err != nil {
return nil, err
}

return result, nil
}

selectedBadgeUsers, err := c.badgesUsersRepository.GetMany(
ctx,
badges_users.GetManyInput{
Expand All @@ -73,21 +55,5 @@ func (c *Service) GetMany(ctx context.Context, input GetManyInput) ([]entity.Bad
result = append(result, modelToEntity(b))
}

if len(result) > 0 {
cacheBytes, err := json.Marshal(result)
if err != nil {
return nil, err
}

if err := c.redis.Set(
ctx,
badgeUsersCacheKey+input.BadgeID.String(),
cacheBytes,
1*time.Minute,
).Err(); err != nil {
return nil, err
}
}

return result, nil
}

0 comments on commit d752b05

Please sign in to comment.