customer/internal/service/cart/cart.go
2023-05-19 12:08:15 +03:00

90 lines
2.4 KiB
Go

package cart
import (
"context"
"fmt"
"log"
"go.uber.org/zap"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
)
type accountRepository interface {
AddItemToCart(ctx context.Context, userID, itemID string) (*models.Account, errors.Error)
RemoveItemFromCart(ctx context.Context, userID, itemID string) (*models.Account, errors.Error)
}
type hubadminClient interface {
GetTariff(ctx context.Context, tariffID string) (*models.Tariff, errors.Error)
}
type Deps struct {
Logger *zap.Logger
Repository accountRepository
HubadminClient hubadminClient
}
type Service struct {
logger *zap.Logger
repository accountRepository
hubadminClient hubadminClient
}
func New(deps *Deps) *Service {
if deps == nil {
log.Panicln("deps is nil on <New (cart service)>")
}
if deps.Logger == nil {
log.Panicln("logger is nil on <New (cart service)>")
}
if deps.Repository == nil {
log.Panicln("repository is nil on <New (cart service)>")
}
if deps.HubadminClient == nil {
log.Panicln("HubadminClient is nil on <New (cart service)>")
}
return &Service{
logger: deps.Logger,
repository: deps.Repository,
hubadminClient: deps.HubadminClient,
}
}
func (receiver *Service) Remove(ctx context.Context, userID, itemID string) ([]string, errors.Error) {
account, err := receiver.repository.RemoveItemFromCart(ctx, userID, itemID)
if err != nil {
receiver.logger.Error("failed to remove item from cart on <Remove> of <CartService>", zap.Error(err))
return []string{}, err
}
return account.Cart, nil
}
func (receiver *Service) Add(ctx context.Context, userID, itemID string) ([]string, errors.Error) {
tariff, err := receiver.hubadminClient.GetTariff(ctx, itemID)
if err != nil {
receiver.logger.Error("failed to get tariff on <Add> of <CartService>", zap.Error(err), zap.String("tariffID", itemID))
return []string{}, err
}
if tariff == nil {
return []string{}, errors.New(
fmt.Errorf("failed to get tariff <%s> on <Add> of <CartService>: tariff not found", itemID),
errors.ErrNotFound,
)
}
account, err := receiver.repository.AddItemToCart(ctx, userID, itemID)
if err != nil {
receiver.logger.Error("failed to add item to cart on <Add> of <CartService>", zap.Error(err))
return []string{}, err
}
return account.Cart, nil
}