Files
mtusi2026lab2/service/internal/adapter/repository/cache/outside/chat.go
T
2026-11-06 13:11:04 +03:00

79 lines
1.8 KiB
Go

package outside
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/google/uuid"
"gitea.privcloud.tech/mtusi2026/internal/dto"
"gitea.privcloud.tech/mtusi2026/internal/pkg/apperr"
"gitea.privcloud.tech/mtusi2026/internal/pkg/cache"
)
const (
// chatRedisKey equals "chat:{chat_id}" path
chatRedisKey = "chat:%s"
)
type ChatCache struct {
client *cache.Client
}
func NewChatCache(client *cache.Client) *ChatCache {
return &ChatCache{
client: client,
}
}
type chat struct {
ID uuid.UUID `json:"id"`
Title string `json:"title"`
MemberIDs []uuid.UUID `json:"member_ids"`
CreatedAt time.Time `json:"created_at"`
}
func (r *ChatCache) Create(ctx context.Context, req dto.Chat) error {
data, err := json.Marshal(chat{
ID: req.ID,
Title: req.Title,
MemberIDs: req.MemberIDs,
CreatedAt: req.CreatedAt,
})
if err != nil {
return apperr.Wrap(err, apperr.CodeInternal, "failed to marshal chat cache")
}
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
defer cancel()
err = r.client.Set(ctx, fmt.Sprintf(chatRedisKey, req.ID), data, 0).Err()
if err != nil {
return apperr.WrapRedis(err, "failed to create chat cache")
}
return nil
}
func (r *ChatCache) Get(ctx context.Context, chatID uuid.UUID) (*dto.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, cache.OperationTimeout)
defer cancel()
data, err := r.client.Get(ctx, fmt.Sprintf(chatRedisKey, chatID.String())).Bytes()
if err != nil {
return nil, apperr.WrapRedis(err, "failed to read chat cache")
}
var item chat
if err = json.Unmarshal(data, &item); err != nil {
return nil, apperr.Wrap(err, apperr.CodeInternal, "failed to unmarshal chat cache")
}
return &dto.Chat{
ID: item.ID,
Title: item.Title,
MemberIDs: item.MemberIDs,
CreatedAt: item.CreatedAt,
}, nil
}