76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
db "zardzul/music-index/sqlc"
|
|
|
|
"zardzul/music-index/repository"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
)
|
|
|
|
type UserHandler struct {
|
|
repo repository.UserRepository
|
|
}
|
|
|
|
func NewUserHandler(repo repository.UserRepository) *UserHandler {
|
|
return &UserHandler{repo: repo}
|
|
}
|
|
|
|
type createUserRequest struct {
|
|
UserName string `json:"user_name" binding:"required"`
|
|
UserMail string `json:"user_mail" binding:"required,email"`
|
|
Password string `json:"password" binding:"required,min=8"`
|
|
}
|
|
|
|
func (h *UserHandler) CreateUser(c *gin.Context) {
|
|
var req createUserRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
var pgID pgtype.UUID
|
|
if err := pgID.Scan(uuid.New().String()); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate user id"})
|
|
return
|
|
}
|
|
|
|
id, err := h.repo.CreateUser(c.Request.Context(), db.CreateUserParams{
|
|
ID: pgID,
|
|
UserName: req.UserName,
|
|
UserMail: req.UserMail,
|
|
Password: req.Password, // TODO: hash this before storing
|
|
})
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusCreated, gin.H{
|
|
"message": "user created",
|
|
"id": id.String(),
|
|
})
|
|
}
|
|
|
|
func (h *UserHandler) GetUsernameByID(c *gin.Context) {
|
|
idParam := c.Param("id")
|
|
var pgID pgtype.UUID
|
|
if err := pgID.Scan(idParam); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid user id"})
|
|
return
|
|
}
|
|
|
|
username, err := h.repo.GetUsernameByID(c.Request.Context(), pgID)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"user_name": username,
|
|
})
|
|
}
|