summaryrefslogtreecommitdiff
path: root/app/controllers/sparkles/controller.go
blob: 86610e1343b9cba3b93ba0760b665bca1182fba5 (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
package sparkles

import (
	"net/http"

	"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/domain"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/middleware"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/authz"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls"
)

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

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

func (c *Controller) MountTo(mux *http.ServeMux) {
	mux.HandleFunc("GET /sparkles", c.Index)
	mux.Handle("POST /sparkles", x.Middleware[http.Handler](
		http.HandlerFunc(c.Create),
		middleware.RequireUser(),
		// middleware.RequirePermission("create", c.check),
	))
}

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

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(r.Context(), sparkle); err != nil {
		pls.LogError(r.Context(), err)
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusCreated)
	if err := serde.ToHTTP(w, r, sparkle); err != nil {
		pls.LogError(r.Context(), err)
		return
	}
}