get_deployment.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/config"
  10. "github.com/porter-dev/porter/api/types"
  11. "github.com/porter-dev/porter/internal/models"
  12. "github.com/porter-dev/porter/internal/models/integrations"
  13. "gorm.io/gorm"
  14. )
  15. type GetDeploymentHandler struct {
  16. handlers.PorterHandlerReadWriter
  17. }
  18. func NewGetDeploymentHandler(
  19. config *config.Config,
  20. decoderValidator shared.RequestDecoderValidator,
  21. writer shared.ResultWriter,
  22. ) *GetDeploymentHandler {
  23. return &GetDeploymentHandler{
  24. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  25. }
  26. }
  27. func (c *GetDeploymentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  29. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  30. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  31. request := &types.GetDeploymentRequest{}
  32. if ok := c.DecodeAndValidate(w, r, request); !ok {
  33. return
  34. }
  35. // read the environment to get the environment id
  36. env, err := c.Repo().Environment().ReadEnvironment(project.ID, cluster.ID, uint(ga.InstallationID))
  37. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  38. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  39. fmt.Errorf("environment not found: is the environment enabled for this git installation?"),
  40. http.StatusNotFound,
  41. ))
  42. return
  43. } else if err != nil {
  44. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  45. return
  46. }
  47. depl, err := c.Repo().Environment().ReadDeployment(env.ID, request.Namespace)
  48. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  49. c.HandleAPIError(w, r, apierrors.NewErrPassThroughToClient(
  50. fmt.Errorf("deployment not found"),
  51. http.StatusNotFound,
  52. ))
  53. return
  54. } else if err != nil {
  55. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  56. return
  57. }
  58. c.WriteResult(w, r, depl.ToDeploymentType())
  59. }