customer/internal/controller/currency/currency.go

92 lines
2.2 KiB
Go
Raw Normal View History

2023-05-18 19:43:43 +00:00
package currency
import (
"context"
"fmt"
2023-05-19 04:50:40 +00:00
"log"
2023-05-18 19:43:43 +00:00
"net/http"
"github.com/labstack/echo/v4"
"go.uber.org/zap"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/utils/echotools"
)
type currencyService interface {
GetCurrencies(context.Context) ([]string, errors.Error)
PutCurrencies(context.Context, []string) ([]string, errors.Error)
}
type Deps struct {
Logger *zap.Logger
CurrencyService currencyService
}
type Controller struct {
logger *zap.Logger
currencyService currencyService
}
func New(deps *Deps) *Controller {
2023-05-19 04:50:40 +00:00
if deps == nil {
log.Panicln("deps is nil on <New (account controller)>")
}
if deps.Logger == nil {
log.Panicln("logger is nil on <New (account controller)>")
}
if deps.CurrencyService == nil {
log.Panicln("currency service is nil on <New (account controller)>")
}
2023-05-18 19:43:43 +00:00
return &Controller{
logger: deps.Logger,
currencyService: deps.CurrencyService,
}
}
func (receiver *Controller) GetCurrencies(ctx echo.Context) error {
currencies, err := receiver.currencyService.GetCurrencies(ctx.Request().Context())
if err != nil {
receiver.logger.Error(
"failed to get currencies on <GetCurrencies> of <CurrencyController>",
zap.Error(err.Extract()),
)
return echotools.ResponseError(ctx, err)
}
return ctx.JSON(http.StatusOK, currencies)
}
func (receiver *Controller) PutCurrencies(ctx echo.Context) error {
currencies, bindErr := echotools.Bind[[]string](ctx)
if bindErr != nil {
receiver.logger.Error(
"failed to parse body on <PutCurrencies> of <CurrencyController>",
zap.Error(bindErr),
)
return echotools.ResponseError(ctx, errors.New(
fmt.Errorf("failed to parse body: %w", bindErr),
errors.ErrInternalError,
))
}
2023-05-19 05:21:52 +00:00
currenciesCopy := *currencies
if len(currenciesCopy) < 1 {
currenciesCopy = make([]string, 0)
}
updatedCurrencies, err := receiver.currencyService.PutCurrencies(ctx.Request().Context(), currenciesCopy)
2023-05-18 19:43:43 +00:00
if err != nil {
receiver.logger.Error(
"failed to put currencies on <PutCurrencies> of <CurrencyController>",
zap.Error(err.Extract()),
)
return echotools.ResponseError(ctx, err)
}
return ctx.JSON(http.StatusOK, updatedCurrencies)
}