get_deployment.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 GetDeploymentHandler struct {
  17. handlers.PorterHandlerReadWriter
  18. }
  19. func NewGetDeploymentHandler(
  20. config *config.Config,
  21. decoderValidator shared.RequestDecoderValidator,
  22. writer shared.ResultWriter,
  23. ) *GetDeploymentHandler {
  24. return &GetDeploymentHandler{
  25. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  26. }
  27. }
  28. func (c *GetDeploymentHandler) 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. owner, name, ok := commonutils.GetOwnerAndNameParams(c, w, r)
  33. if !ok {
  34. return
  35. }
  36. request := &types.GetDeploymentRequest{}
  37. if ok := c.DecodeAndValidate(w, r, request); !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. depl, err := c.Repo().Environment().ReadDeployment(env.ID, request.Namespace)
  53. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  54. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  55. fmt.Errorf("deployment not found"),
  56. http.StatusNotFound,
  57. ))
  58. return
  59. } else if err != nil {
  60. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  61. return
  62. }
  63. c.WriteResult(w, r, depl.ToDeploymentType())
  64. }