Implements API validator and uses it in user endpoint
This commit is contained in:
parent
932edb8da7
commit
cfe335ea39
3 changed files with 45 additions and 3 deletions
|
|
@ -27,6 +27,12 @@ func (h *Handler) createUser(c *fiber.Ctx) error {
|
||||||
return defaultUserError
|
return defaultUserError
|
||||||
}
|
}
|
||||||
|
|
||||||
|
validationErr := ValidateModel(user)
|
||||||
|
|
||||||
|
if validationErr != nil {
|
||||||
|
return validationErr
|
||||||
|
}
|
||||||
|
|
||||||
_, insertErr := h.db.Exec("INSERT INTO user (id, first_name, email) VALUES (?, ?, ?)", user.ID, user.FirstName, user.Email)
|
_, insertErr := h.db.Exec("INSERT INTO user (id, first_name, email) VALUES (?, ?, ?)", user.ID, user.FirstName, user.Email)
|
||||||
|
|
||||||
if insertErr != nil {
|
if insertErr != nil {
|
||||||
|
|
|
||||||
36
internal/api/validator.go
Normal file
36
internal/api/validator.go
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"freed/internal/model"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/go-playground/validator/v10"
|
||||||
|
"github.com/gofiber/fiber/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ModelConstraint interface {
|
||||||
|
*model.User // | add other models here
|
||||||
|
}
|
||||||
|
|
||||||
|
type ValidationError struct {
|
||||||
|
FailedField string
|
||||||
|
Tag string
|
||||||
|
Value string
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateModel[T ModelConstraint](s T) *fiber.Error {
|
||||||
|
var errorMessages []string
|
||||||
|
validate := validator.New()
|
||||||
|
err := validate.Struct(s)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
for _, err := range err.(validator.ValidationErrors) {
|
||||||
|
err := fmt.Sprintf("Field %s is invalid, reason: %s", err.StructNamespace(), err.Tag())
|
||||||
|
|
||||||
|
errorMessages = append(errorMessages, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fiber.NewError(fiber.StatusBadRequest, strings.Join(errorMessages, ". "))
|
||||||
|
}
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
package model
|
package model
|
||||||
|
|
||||||
type User struct {
|
type User struct {
|
||||||
ID string `json: id`
|
ID string `json:"id" validate:"required"`
|
||||||
FirstName string `json: "firstName"`
|
FirstName string `json:"firstName" validate:"required"`
|
||||||
Email string `json: "email"`
|
Email string `json:"email" validate:"required,email"`
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue