-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.go
More file actions
81 lines (71 loc) · 2.15 KB
/
users.go
File metadata and controls
81 lines (71 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package handler
import (
"context"
"errors"
"log/slog"
"github.com/generate/selfserve/internal/errs"
"github.com/generate/selfserve/internal/httpx"
"github.com/generate/selfserve/internal/models"
"github.com/gofiber/fiber/v2"
)
type UsersRepository interface {
FindUser(ctx context.Context, id string) (*models.User, error)
InsertUser(ctx context.Context, user *models.CreateUser) (*models.User, error)
}
type UsersHandler struct {
repo UsersRepository
}
func NewUsersHandler(repo UsersRepository) *UsersHandler {
return &UsersHandler{repo: repo}
}
// GetUserByID godoc
// @Summary Get user by ID
// @Description Retrieves a user by their unique app ID
// @Tags users
// @Accept json
// @Produce json
// @Param id path string true "User ID"
// @Success 200 {object} models.User
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /users/{id} [get]
func (h *UsersHandler) GetUserByID(c *fiber.Ctx) error {
id := c.Params("id")
if id == "" {
return errs.BadRequest("id is required")
}
user, err := h.repo.FindUser(c.Context(), id)
if err != nil {
if errors.Is(err, errs.ErrNotFoundInDB) {
return errs.NotFound("user", "id", id)
}
slog.Error(err.Error())
return errs.InternalServerError()
}
return c.JSON(user)
}
// CreateUser godoc
// @Summary Creates a user
// @Description Creates a user with the given data
// @Tags users
// @Accept json
// @Produce json
// @Param request body models.CreateUser true "User data"
// @Success 200 {object} models.User
// @Failure 400 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /users [post]
func (h *UsersHandler) CreateUser(c *fiber.Ctx) error {
var CreateUserRequest models.CreateUser
if err := c.BodyParser(&CreateUserRequest); err != nil {
return errs.InvalidJSON()
}
if err := httpx.BindAndValidate(c, &CreateUserRequest); err != nil {
return err
}
res, err := h.repo.InsertUser(c.Context(), &CreateUserRequest)
if err != nil {
return errs.InternalServerError()
}
return c.JSON(res)
}