customer/internal/interface/controller/rest/currency/currency.go

88 lines
2.1 KiB
Go
Raw Normal View History

2023-06-22 09:36:43 +00:00
package currency
import (
"context"
"fmt"
"log"
"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/pkg/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 {
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)>")
}
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),
)
return errors.HTTP(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 errors.HTTP(ctx, errors.New(
fmt.Errorf("failed to parse body: %w", bindErr),
errors.ErrInvalidArgs,
))
}
currenciesCopy := *currencies
if len(currenciesCopy) < 1 {
currenciesCopy = make([]string, 0)
}
updatedCurrencies, err := receiver.currencyService.PutCurrencies(ctx.Request().Context(), currenciesCopy)
if err != nil {
receiver.logger.Error(
"failed to put currencies on <PutCurrencies> of <CurrencyController>",
zap.Error(err),
)
return errors.HTTP(ctx, err)
}
return ctx.JSON(http.StatusOK, updatedCurrencies)
}