Basic DTO validation
This commit is contained in:
@ -3,15 +3,17 @@ package views
|
||||
import (
|
||||
"fmt"
|
||||
"iris-test/app/lib/auth"
|
||||
"iris-test/app/lib/helpers"
|
||||
"iris-test/app/repository"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/kataras/iris/v12"
|
||||
)
|
||||
|
||||
type editUserJSON struct {
|
||||
FirstName string `json:"first-name"`
|
||||
LastName string `json:"last-name"`
|
||||
Email string `json:"email"`
|
||||
type editUserRequestDto struct {
|
||||
FirstName string `json:"firstName" validate:"required"`
|
||||
LastName string `json:"lastName" validate:"required"`
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
@ -20,6 +22,7 @@ func GetUsersPage(ctx iris.Context) {
|
||||
|
||||
pagination := repository.NewPagination()
|
||||
ordering := []repository.Ordering{
|
||||
repository.NewOrdering("updated_at", repository.ORDERING_DESC),
|
||||
repository.NewOrdering("first_name", repository.ORDERING_ASC),
|
||||
repository.NewOrdering("last_name", repository.ORDERING_ASC),
|
||||
}
|
||||
@ -59,11 +62,27 @@ func EditUserPage(ctx iris.Context) {
|
||||
}
|
||||
|
||||
func SaveUser(ctx iris.Context) {
|
||||
var postData editUserJSON
|
||||
var postData editUserRequestDto
|
||||
err := ctx.ReadJSON(&postData)
|
||||
|
||||
if err != nil {
|
||||
ctx.StopWithError(iris.StatusBadRequest, err)
|
||||
// Handle the error, below you will find the right way to do that...
|
||||
if errs, ok := err.(validator.ValidationErrors); ok {
|
||||
// Wrap the errors with JSON format, the underline library returns the errors as interface.
|
||||
validationErrors := helpers.WrapValidationErrors(errs)
|
||||
|
||||
// Fire an application/json+problem response and stop the handlers chain.
|
||||
ctx.StopWithProblem(
|
||||
iris.StatusBadRequest, iris.NewProblem().
|
||||
Title("Validation error").
|
||||
Detail("One or more fields failed to be validated").
|
||||
Key("errors", validationErrors).
|
||||
Key("success", false),
|
||||
)
|
||||
return
|
||||
}
|
||||
// It's probably an internal JSON error, let's dont give more info here.
|
||||
ctx.StopWithStatus(iris.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user