feat: add validate for user signup

This commit is contained in:
Muyao CHEN
2024-10-06 21:54:29 +02:00
parent 344485d082
commit ba8570857d
6 changed files with 31 additions and 12 deletions

View File

@ -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, &params)
_, err = uc.userUsecase.Create(ctx, &params)
if err != nil {
core.WriteResponse(ctx, err, nil)
return

View File

@ -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"`
}

View File

@ -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
}