2
0

update_notifications.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package release
  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/server/shared/requestutils"
  9. "github.com/porter-dev/porter/api/types"
  10. "github.com/porter-dev/porter/internal/models"
  11. "gorm.io/gorm"
  12. )
  13. type UpdateNotificationHandler struct {
  14. handlers.PorterHandlerReadWriter
  15. }
  16. func NewUpdateNotificationHandler(
  17. config *config.Config,
  18. decoderValidator shared.RequestDecoderValidator,
  19. writer shared.ResultWriter,
  20. ) *UpdateNotificationHandler {
  21. return &UpdateNotificationHandler{
  22. PorterHandlerReadWriter: handlers.NewDefaultPorterHandler(config, decoderValidator, writer),
  23. }
  24. }
  25. func (c *UpdateNotificationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  26. cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
  27. name, _ := requestutils.GetURLParamString(r, types.URLParamReleaseName)
  28. namespace := r.Context().Value(types.NamespaceScope).(string)
  29. request := &types.UpdateNotificationConfigRequest{}
  30. if ok := c.DecodeAndValidate(w, r, request); !ok {
  31. return
  32. }
  33. release, err := c.Repo().Release().ReadRelease(cluster.ID, name, namespace)
  34. if err != nil {
  35. if err == gorm.ErrRecordNotFound {
  36. w.WriteHeader(http.StatusNotFound)
  37. return
  38. }
  39. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  40. }
  41. // either create a new notification config or update the current one
  42. newConfig := &models.NotificationConfig{
  43. Enabled: request.Payload.Enabled,
  44. Success: request.Payload.Success,
  45. Failure: request.Payload.Failure,
  46. }
  47. if release.NotificationConfig == 0 {
  48. newConfig, err = c.Repo().NotificationConfig().CreateNotificationConfig(newConfig)
  49. if err != nil {
  50. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  51. return
  52. }
  53. release.NotificationConfig = newConfig.ID
  54. release, err = c.Repo().Release().UpdateRelease(release)
  55. } else {
  56. newConfig.ID = release.NotificationConfig
  57. newConfig, err = c.Repo().NotificationConfig().UpdateNotificationConfig(newConfig)
  58. }
  59. if err != nil {
  60. c.HandleAPIError(w, r, apierrors.NewErrInternal(err))
  61. return
  62. }
  63. }