list.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package api_contract
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "github.com/go-chi/chi/v5"
  7. "github.com/porter-dev/porter/api/server/handlers"
  8. "github.com/porter-dev/porter/api/server/shared"
  9. "github.com/porter-dev/porter/api/server/shared/apierrors"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/api/types"
  12. "github.com/porter-dev/porter/internal/models"
  13. )
  14. type APIContractRevisionListHandler struct {
  15. handlers.PorterHandlerReadWriter
  16. }
  17. func NewAPIContractRevisionListHandler(
  18. config *config.Config,
  19. decoderValidator shared.RequestDecoderValidator,
  20. writer shared.ResultWriter,
  21. ) *APIContractRevisionListHandler {
  22. return &APIContractRevisionListHandler{
  23. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  24. }
  25. }
  26. // ServeHTTP returns a list of Porter API contract revisions for a given project.
  27. // If clusterID is also given, it will list by project_id, cluster_id
  28. func (c *APIContractRevisionListHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. proj, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  30. clusterID := 0
  31. clusterIDParam := chi.URLParam(r, "cluster_id")
  32. if clusterIDParam != "" {
  33. i, err := strconv.Atoi(clusterIDParam)
  34. if err != nil {
  35. e := fmt.Errorf("invalid cluster_id query param given: %w", err)
  36. c.HandleAPIError(w, r, apierrors.NewErrInternal(e))
  37. return
  38. }
  39. clusterID = i
  40. }
  41. ctx := r.Context()
  42. revisions, err := c.Config().Repo.APIContractRevisioner().List(ctx, proj.ID, uint(clusterID))
  43. if err != nil {
  44. e := fmt.Errorf("error listing api contract revision: %w", err)
  45. c.HandleAPIError(w, r, apierrors.NewErrInternal(e))
  46. return
  47. }
  48. w.WriteHeader(http.StatusOK)
  49. c.WriteResult(w, r, revisions)
  50. }