blob: 9c319b21465099bde8f052b1bb296a19101f1c54 (
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
|
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/domain"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/middleware"
)
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(http.StatusFound, "/")
mux.HandleFunc("GET /sparkles", c.Index)
mux.Handle("POST /sparkles", requireUser(http.HandlerFunc(c.Create)))
}
func (c *Controller) Index(w http.ResponseWriter, r *http.Request) {
serde.ToHTTP(w, r, c.db.All())
}
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
}
}
|