get_environment.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package environment
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "github.com/porter-dev/porter/internal/telemetry"
  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/server/shared/requestutils"
  12. "github.com/porter-dev/porter/api/types"
  13. "github.com/porter-dev/porter/internal/models"
  14. "gorm.io/gorm"
  15. )
  16. type GetEnvironmentHandler struct {
  17. handlers.PorterHandlerWriter
  18. }
  19. func NewGetEnvironmentHandler(
  20. config *config.Config,
  21. writer shared.ResultWriter,
  22. ) *GetEnvironmentHandler {
  23. return &GetEnvironmentHandler{
  24. PorterHandlerWriter: handlers.NewDefaultPorterHandler(config, nil, writer),
  25. }
  26. }
  27. func (c *GetEnvironmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. ctx, span := telemetry.NewSpan(r.Context(), "serve-get-environment")
  29. defer span.End()
  30. project, _ := ctx.Value(types.ProjectScope).(*models.Project)
  31. cluster, _ := ctx.Value(types.ClusterScope).(*models.Cluster)
  32. telemetry.WithAttributes(span,
  33. telemetry.AttributeKV{Key: "project-id", Value: project.ID},
  34. telemetry.AttributeKV{Key: "cluster-id", Value: cluster.ID},
  35. )
  36. envID, reqErr := requestutils.GetURLParamUint(r, "environment_id")
  37. if reqErr != nil {
  38. _ = telemetry.Error(ctx, span, reqErr, "could not get environment id from url")
  39. c.HandleAPIError(w, r, reqErr)
  40. return
  41. }
  42. telemetry.WithAttributes(span, telemetry.AttributeKV{Key: "environment-id", Value: envID})
  43. env, err := c.Repo().Environment().ReadEnvironmentByID(project.ID, cluster.ID, envID)
  44. if err != nil {
  45. _ = telemetry.Error(ctx, span, err, "could not read environment by id")
  46. if errors.Is(err, gorm.ErrRecordNotFound) {
  47. c.HandleAPIError(w, r, apierrors.NewErrNotFound(fmt.Errorf("no such environment with ID: %d", envID)))
  48. return
  49. }
  50. c.HandleAPIError(w, r, apierrors.NewErrInternal(fmt.Errorf("error reading environment with ID: %d. Error: %w", envID, err)))
  51. return
  52. }
  53. c.WriteResult(w, r, env.ToEnvironmentType())
  54. }