summaryrefslogtreecommitdiff
path: root/app/controllers/sparkles/controller.go
blob: 35f207685b09a02c97310cf79f08cd7430ab0cf1 (plain)
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
package sparkles

import (
	"net/http"

	"github.com/xlgmokha/x/pkg/log"
	"github.com/xlgmokha/x/pkg/mapper"
	"github.com/xlgmokha/x/pkg/serde"
	"github.com/xlgmokha/x/pkg/x"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/middleware"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/views"
)

type Controller struct {
	db domain.Repository[*domain.Sparkle]
}

func New(db domain.Repository[*domain.Sparkle]) *Controller {
	return &Controller{db: db}
}

func (c *Controller) MountTo(mux *http.ServeMux) {
	requireUser := middleware.RequireUser()

	mux.HandleFunc("GET /sparkles", c.Index)
	mux.Handle("GET /sparkles/new", requireUser(http.HandlerFunc(c.NewForm)))
	mux.Handle("POST /sparkles", requireUser(http.HandlerFunc(c.Create)))
}

func (c *Controller) Index(w http.ResponseWriter, r *http.Request) {
	if err := serde.ToHTTP(w, r, c.db.All()); err != nil {
		log.WithFields(r.Context(), log.Fields{"error": err})
		w.WriteHeader(http.StatusInternalServerError)
	}
}

func (c *Controller) NewForm(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Header().Add("Content-Type", "text/html")

	dto := &NewSparkleDTO{CurrentUser: cfg.CurrentUser.From(r.Context())}
	if err := views.Render(w, "sparkles/new", dto); err != nil {
		log.WithFields(r.Context(), log.Fields{"error": err})
	}
}

func (c *Controller) Create(w http.ResponseWriter, r *http.Request) {
	sparkle := mapper.MapFrom[*http.Request, *domain.Sparkle](r)

	if x.IsZero(sparkle) {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	if err := c.db.Save(sparkle); err != nil {
		log.WithFields(r.Context(), log.Fields{"error": err})
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusCreated)
	if err := serde.ToHTTP(w, r, sparkle); err != nil {
		log.WithFields(r.Context(), log.Fields{"error": err})
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
}