Skip to content

Commit

Permalink
refactor: add validate to command/query level
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan-maqing committed Aug 30, 2023
1 parent 747477b commit 71e09a4
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package commands

import (
validation "github.com/go-ozzo/ozzo-validation"
"time"

"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/utils/validator"
uuid "github.com/satori/go.uuid"
)

Expand Down Expand Up @@ -32,10 +32,19 @@ func NewCreateProduct(
Price: price,
CreatedAt: createdAt,
}
err := validator.Validate(command)
err := command.Validate()
if err != nil {
return nil, err
}

return command, nil
}

func (p *CreateProduct) Validate() error {
return validation.ValidateStruct(p, validation.Field(&p.Id, validation.Required),
validation.Field(&p.ProductId, validation.Required),
validation.Field(&p.Name, validation.Required, validation.Length(3, 250)),
validation.Field(&p.Description, validation.Required, validation.Length(3, 500)),
validation.Field(&p.Price, validation.Required),
validation.Field(&p.CreatedAt, validation.Required))
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ type GetProductById struct {
Id uuid.UUID `validate:"required"`
}

// TODO
// this function seems doesn't validate if the id is empty, should I refactor this func and handle the error where NewGetProductByID called?
func NewGetProductById(id uuid.UUID) *GetProductById {
return &GetProductById{Id: id}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ func (ep *searchProductsEndpoint) handler() echo.HandlerFunc {
ListQuery: request.ListQuery,
}

if err := ep.Validator.StructCtx(ctx, query); err != nil {
// Am I right? this one is a validator.StructCtx with ctx, can I just make it to query.Validate?
//if err := ep.Validator.StructCtx(ctx, query); err != nil {
if err := query.Validate(); err != nil {
validationErr := customErrors.NewValidationErrorWrap(
err,
"[searchProductsEndpoint_handler.StructCtx] query validation failed",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
package queries

import "github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/utils"
import (
validation "github.com/go-ozzo/ozzo-validation"
"github.com/mehdihadeli/go-ecommerce-microservices/internal/pkg/utils"
)

type SearchProducts struct {
SearchText string `validate:"required"`
*utils.ListQuery
}

func (s *SearchProducts) Validate() error {
return validation.ValidateStruct(s, validation.Field(&s.SearchText, validation.Required))
}

0 comments on commit 71e09a4

Please sign in to comment.