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

87 lines
2.6 KiB
Go
Raw Normal View History

2023-05-23 10:52:27 +00:00
package history
import (
"context"
2023-05-23 15:24:52 +00:00
"fmt"
2023-05-23 10:52:27 +00:00
"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/internal/models"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/swagger"
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/utils/echotools"
)
type historyService interface {
CreateHistory(context.Context, *models.History) (*models.History, errors.Error)
GetHistoryList(context.Context, *models.Pagination) (*models.PaginationResponse[models.History], errors.Error)
}
type Deps struct {
Logger *zap.Logger
HistoryService historyService
}
type Controller struct {
logger *zap.Logger
historyService historyService
}
func New(deps *Deps) *Controller {
if deps == nil {
log.Panicln("deps is nil on <New (history controller)>")
}
if deps.Logger == nil {
log.Panicln("logger is nil on <New (history controller)>")
}
if deps.HistoryService == nil {
log.Panicln("HistoryService is nil on <New (history controller)>")
}
return &Controller{
logger: deps.Logger,
historyService: deps.HistoryService,
}
}
func (receiver *Controller) CreateHistory(ctx echo.Context) error {
2023-05-23 15:24:52 +00:00
request, bindErr := echotools.Bind[swagger.Add2historyJSONRequestBody](ctx)
if bindErr != nil {
receiver.logger.Error("failed to bind body on <CreateHistory> of <HistoryController>", zap.Error(bindErr))
return echotools.ResponseError(ctx, errors.New(
fmt.Errorf("failed to parse body on <CreateHistory> of <HistoryController>: %w", bindErr),
errors.ErrInvalidArgs,
))
}
createdHistory, err := receiver.historyService.CreateHistory(ctx.Request().Context(), &models.History{
2023-05-24 11:20:35 +00:00
UserID: request.UserId,
Type: models.HistoryType(request.Type),
Comment: request.Comment,
RawDetails: request.RawDetails,
2023-05-23 15:24:52 +00:00
})
2023-05-23 10:52:27 +00:00
if err != nil {
receiver.logger.Error("failed to create history on <CreateHistory> of <HistoryController>", zap.Error(err))
return echotools.ResponseError(ctx, err)
}
return ctx.JSON(http.StatusOK, createdHistory)
}
func (receiver *Controller) GetHistoryList(ctx echo.Context, params swagger.GetHistoryParams) error {
histories, err := receiver.historyService.GetHistoryList(ctx.Request().Context(), &models.Pagination{
Page: int64(*params.Page),
Limit: int64(*params.Limit),
})
if err != nil {
receiver.logger.Error("failed to get histories on <GetHistoryList> of <HistoryController>", zap.Error(err))
return echotools.ResponseError(ctx, err)
}
return ctx.JSON(http.StatusOK, histories)
}