feat: user creation

This commit is contained in:
Robin Dittmar
2026-07-20 21:57:43 +02:00
parent 49f1497f45
commit 14b82b787b
8 changed files with 178 additions and 13 deletions
+4
View File
@@ -13,6 +13,10 @@ type ListHandler struct {
ListService *domain.ListService
}
func NewListHandler(listService *domain.ListService) *ListHandler {
return &ListHandler{ListService: listService}
}
func (h *ListHandler) CreateList(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
+39
View File
@@ -0,0 +1,39 @@
package handler
import (
"log/slog"
"net/http"
"github.com/robindittmar/dttmr-api/internal/api/request"
"github.com/robindittmar/dttmr-api/internal/api/response"
"github.com/robindittmar/dttmr-api/internal/domain"
)
type UserHandler struct {
UserService *domain.UserService
}
func NewUserHandler(userService *domain.UserService) *UserHandler {
return &UserHandler{UserService: userService}
}
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
payload, err := request.DecodeCreateUser(r)
if err != nil {
slog.ErrorContext(ctx, "failed to decode create user payload", slog.Any("error", err))
response.Error(ctx, w, http.StatusBadRequest, "failed to decode request body")
return
}
user, err := h.UserService.CreateUser(ctx, payload.Email, payload.Name, payload.Password)
if err != nil {
slog.ErrorContext(ctx, "failed to create user", slog.Any("error", err))
response.Error(ctx, w, http.StatusInternalServerError, "failed to create user")
return
}
slog.InfoContext(ctx, "created user successfully", slog.Any("user_id", user.ID))
response.JSON(ctx, w, http.StatusCreated, user)
}
+26
View File
@@ -0,0 +1,26 @@
package request
import (
"encoding/json"
"fmt"
"net/http"
)
type CreateUserPayload struct {
Email string `json:"email"`
Name string `json:"name"`
Password string `json:"password"`
}
func DecodeCreateUser(r *http.Request) (CreateUserPayload, error) {
var payload CreateUserPayload
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&payload); err != nil {
return payload, fmt.Errorf("error decoding create user payload: %w", err)
}
return payload, nil
}
+7 -2
View File
@@ -15,16 +15,21 @@ type Config struct {
}
func NewMux(cfg Config) http.Handler {
userRepo := repository.NewUserRepo(cfg.Database)
userService := domain.NewUserService(userRepo)
userHandler := handler.NewUserHandler(userService)
listRepo := repository.NewListRepo(cfg.Database)
listService := domain.NewListService(listRepo)
listHandler := handler.ListHandler{ListService: listService}
listHandler := handler.NewListHandler(listService)
mux := http.NewServeMux()
mux.HandleFunc("/", handler.DefaultHandler)
mux.HandleFunc("GET /health", handler.HealthHandler)
mux.HandleFunc("POST /users", userHandler.CreateUser)
mux.HandleFunc("POST /lists", listHandler.CreateList)
var httpHandler http.Handler = mux