create.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package environment
  2. import (
  3. "net/http"
  4. "github.com/porter-dev/porter/api/server/handlers"
  5. "github.com/porter-dev/porter/api/server/shared"
  6. "github.com/porter-dev/porter/api/server/shared/apierrors"
  7. "github.com/porter-dev/porter/api/server/shared/config"
  8. "github.com/porter-dev/porter/api/types"
  9. "github.com/porter-dev/porter/internal/models"
  10. "github.com/porter-dev/porter/internal/models/integrations"
  11. )
  12. type CreateEnvironmentHandler struct {
  13. handlers.PorterHandlerReadWriter
  14. }
  15. func NewCreateEnvironmentHandler(
  16. config *config.Config,
  17. decoderValidator shared.RequestDecoderValidator,
  18. writer shared.ResultWriter,
  19. ) *CreateEnvironmentHandler {
  20. return &CreateEnvironmentHandler{
  21. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  22. }
  23. }
  24. func (c *CreateEnvironmentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  25. ga, _ := r.Context().Value(types.GitInstallationScope).(*integrations.GithubAppInstallation)
  26. project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
  27. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  28. // create the environment
  29. request := &types.CreateEnvironmentRequest{}
  30. if ok := c.DecodeAndValidate(w, r, request); !ok {
  31. return
  32. }
  33. env, err := c.Repo().Environment().CreateEnvironment(&models.Environment{
  34. ProjectID: project.ID,
  35. ClusterID: cluster.ID,
  36. GitInstallationID: uint(ga.InstallationID),
  37. Name: request.Name,
  38. })
  39. if err != nil {
  40. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  41. return
  42. }
  43. c.WriteResult(w, r, env.ToEnvironmentType())
  44. }