Reputation: 1064
I'm usign buffalo to build a simple backend to store values.
I have a Target
struct defined as follow:
type Target struct {
ID uuid.UUID `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Description string `json:"description" db:"description"`
Observations []Observation `json:"values,omitempty" has_many:"observations" order_by:"updated_at desc"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
// ...
func (t *Target) Validate(tx *pop.Connection) (*validate.Errors, error) {
return validate.Validate(
&validators.StringIsPresent{Field: t.Name, Name: "Name"},
&validators.StringLengthInRange{Field: t.Name, Name: "Name", Min: 2, Max: 15},
), nil
}
func (t *Target) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) {
return t.Validate(tx)
}
func (t *Target) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
return t.Validate(tx)
}
A new Target
is created using the following action:
func TargetAdd(c buffalo.Context) error {
body, err := io.ReadAll(c.Request().Body)
if err != nil {
log.Get().Error("Error reading body: %v", err)
return err
}
target := &models.Target{}
json.Unmarshal([]byte(body), target)
vErr, err := models.DB.ValidateAndCreate(target)
if err != nil {
log.Get().Error("entity not valid: %s", err)
return response.SendGeneralError(c, err)
}
if vErr.HasAny() {
log.Get().Error("entity not valid: %s", vErr)
return response.SendGeneralError(c, err)
}
return response.SendOKResponse(c, target)
}
The problem is that the ValidateAndCreate function does not call any of the validation functions defined for the Target
model, even if it should be so (link to documentation).
Debugging the issue, I found that in the validation.go
file, in this function
func (m *Model) validateCreate(c *Connection) (*validate.Errors, error) {
return m.iterateAndValidate(func(model *Model) (*validate.Errors, error) {
verrs, err := model.validate(c)
if err != nil {
return verrs, err
}
if x, ok := model.Value.(validateCreateable); ok {
vs, err := x.ValidateCreate(c)
if vs != nil {
verrs.Append(vs)
}
if err != nil {
return verrs, err
}
}
return verrs, err
})
}
the call to model.Value.(validateCreateable)
seems to return ok
to false
.
Can someone please explain me where's the problem and how it's possibile to validate a model? Thanks.
EDIT: Changing the import from
"github.com/gobuffalo/validate"
"github.com/gobuffalo/validate/validators"
to
"github.com/gobuffalo/validate/v3"
"github.com/gobuffalo/validate/v3/validators"
seems to fix the problem I have
Upvotes: 1
Views: 88