58 lines
1.5 KiB
Go
58 lines
1.5 KiB
Go
package http
|
|
|
|
import (
|
|
"github.com/aykhans/oh-my-chat/internal/core/domain"
|
|
"github.com/aykhans/oh-my-chat/internal/core/port"
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
type UserHandler struct {
|
|
userService port.UserService
|
|
validator *validator.Validate
|
|
}
|
|
|
|
func NewUserHandler(svc port.UserService, validator *validator.Validate) *UserHandler {
|
|
return &UserHandler{svc, validator}
|
|
}
|
|
|
|
type registerRequest struct {
|
|
Username string `json:"username" validate:"required,max=50"`
|
|
Email string `json:"email" validate:"email"`
|
|
Password string `json:"password" validate:"min=8,max=72"`
|
|
}
|
|
|
|
func (userHandler *UserHandler) Register(ctx *fiber.Ctx) error {
|
|
registerBody := new(registerRequest)
|
|
if err := ctx.BodyParser(registerBody); err != nil {
|
|
return invalidRequestBodyResponse(ctx)
|
|
}
|
|
|
|
if err := userHandler.validator.Struct(registerBody); err != nil {
|
|
return validationErrorResponse(ctx, err)
|
|
}
|
|
|
|
user := domain.User{
|
|
Username: registerBody.Username,
|
|
Email: registerBody.Email,
|
|
Password: registerBody.Password,
|
|
}
|
|
|
|
serviceCtx := ctx.Context()
|
|
_, err := userHandler.userService.Register(serviceCtx, &user)
|
|
if err != nil {
|
|
if err == domain.ErrUsernameExists || err == domain.ErrEmailExists {
|
|
return notFoundResponse(ctx, err)
|
|
}
|
|
return fiber.ErrInternalServerError
|
|
}
|
|
|
|
return ctx.Status(fiber.StatusCreated).JSON(
|
|
fiber.Map{
|
|
"ID": user.ID,
|
|
"Username": user.Username,
|
|
"Email": user.Email,
|
|
},
|
|
)
|
|
}
|