feat: add validate for user signup
This commit is contained in:
@ -29,6 +29,7 @@ import (
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/usecase/usecase"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/core"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"github.com/asaskevich/govalidator"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@ -66,9 +67,15 @@ func (uc *UserController) Signup(ctx core.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO: check params validity (govalidator)
|
||||
_, err := govalidator.ValidateStruct(params)
|
||||
if err != nil {
|
||||
errno := UserParamsErr
|
||||
errno.Message = err.Error()
|
||||
core.WriteResponse(ctx, errno, nil)
|
||||
return
|
||||
}
|
||||
|
||||
_, err := uc.userUsecase.Create(ctx, ¶ms)
|
||||
_, err = uc.userUsecase.Create(ctx, ¶ms)
|
||||
if err != nil {
|
||||
core.WriteResponse(ctx, err, nil)
|
||||
return
|
||||
|
@ -27,10 +27,10 @@ import "time"
|
||||
// User model
|
||||
type User struct {
|
||||
ID int `json:"id"`
|
||||
Email string `json:"email"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Password string `json:"password"`
|
||||
Email string `json:"email" valid:"email"`
|
||||
FirstName string `json:"first_name" valid:"required"`
|
||||
LastName string `json:"last_name" valid:"required"`
|
||||
Password string `json:"password" valid:"required"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
@ -25,12 +25,21 @@ package usecase
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/model"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/howmuch/usecase/repo"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/errno"
|
||||
"git.vinchent.xyz/vinchent/howmuch/internal/pkg/log"
|
||||
)
|
||||
|
||||
var UserExisted = &errno.Errno{
|
||||
HTTP: http.StatusBadRequest,
|
||||
Code: errno.ErrorCode(errno.FailedOperationCode, "UserExisted"),
|
||||
Message: "email already existed.",
|
||||
}
|
||||
|
||||
type userUsecase struct {
|
||||
userRepo repo.UserRepository
|
||||
dbRepo repo.DBRepository
|
||||
@ -51,12 +60,12 @@ func (uuc *userUsecase) Create(ctx context.Context, u *model.User) (*model.User,
|
||||
data, err := uuc.dbRepo.Transaction(
|
||||
ctx,
|
||||
func(txCtx context.Context, tx interface{}) (interface{}, error) {
|
||||
// TODO: should check if the user exists
|
||||
// DB will return an error since we have set email to UNIQUE.
|
||||
// But we may not want to expose the exact db error.
|
||||
|
||||
u, err := uuc.userRepo.Create(txCtx, tx, u)
|
||||
if err != nil {
|
||||
match, _ := regexp.MatchString("SQLSTATE 23505", err.Error())
|
||||
if match {
|
||||
return nil, UserExisted
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user