list_deployments.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package environment
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/api/server/handlers"
  7. "github.com/porter-dev/porter/api/server/shared"
  8. "github.com/porter-dev/porter/api/server/shared/apierrors"
  9. "github.com/porter-dev/porter/api/server/shared/commonutils"
  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. "github.com/porter-dev/porter/internal/models/integrations"
  14. "gorm.io/gorm"
  15. )
  16. type ListDeploymentsHandler struct {
  17. handlers.PorterHandlerReadWriter
  18. }
  19. func NewListDeploymentsHandler(
  20. config *config.Config,
  21. decoderValidator shared.RequestDecoderValidator,
  22. writer shared.ResultWriter,
  23. ) *ListDeploymentsHandler {
  24. return &ListDeploymentsHandler{
  25. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  26. }
  27. }
  28. func (c *ListDeploymentsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  30. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  31. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  32. req := &types.ListDeploymentRequest{}
  33. if ok := c.DecodeAndValidate(w, r, req); !ok {
  34. return
  35. }
  36. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  37. if !ok {
  38. return
  39. }
  40. // read the environment to get the environment id
  41. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID), owner, name)
  42. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  43. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  44. fmt.Errorf("environment not found: is the environment enabled for this git installation?"),
  45. http.StatusNotFound,
  46. ))
  47. return
  48. } else if err != nil {
  49. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  50. return
  51. }
  52. depls, err := c.Repo().Environment().ListDeployments(env.ID)
  53. if err != nil {
  54. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  55. return
  56. }
  57. res := make([]*types.Deployment, 0)
  58. for _, depl := range depls {
  59. res = append(res, depl.ToDeploymentType())
  60. }
  61. c.WriteResult(w, r, res)
  62. }