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" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/pkg/pls" ) 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("POST /sparkles", requireUser(http.HandlerFunc(c.Create))) // This is a temporary endpoint to restore a backup mux.HandleFunc("POST /sparkles/restore", c.Restore) } 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) w.WriteHeader(http.StatusInternalServerError) return } } // This is a temporary endpoint to restore a backup // of sparkles and can be deleted once we have an actual database func (c *Controller) Restore(w http.ResponseWriter, r *http.Request) { sparkles, _ := serde.FromHTTP[[]*domain.Sparkle](r) log.WithFields(r.Context(), log.Fields{"sparkles": sparkles}) x.Each(sparkles, func(sparkle *domain.Sparkle) { if err := c.db.Save(r.Context(), sparkle); err != nil { pls.LogError(r.Context(), err) } }) }