notifications_handler.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package api
  2. import (
  3. "encoding/json"
  4. "github.com/go-chi/chi"
  5. "github.com/porter-dev/porter/internal/models"
  6. "net/http"
  7. )
  8. type HandleUpdateNotificationConfigForm struct {
  9. Payload struct {
  10. Enabled bool `json:"enabled"`
  11. Deploy bool `json:"deploy"`
  12. Success bool `json:"success"`
  13. Failure bool `json:"failure"`
  14. } `json:"payload"`
  15. Namespace string `json:"namespace"`
  16. ClusterID uint `json:"cluster_id"`
  17. }
  18. // HandleUpdateNotificationConfig updates notification settings for a given release
  19. func (app *App) HandleUpdateNotificationConfig(w http.ResponseWriter, r *http.Request) {
  20. name := chi.URLParam(r, "name")
  21. form := &HandleUpdateNotificationConfigForm{}
  22. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  23. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  24. return
  25. }
  26. release, err := app.Repo.Release.ReadRelease(form.ClusterID, name, form.Namespace)
  27. if err != nil {
  28. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  29. Code: ErrReleaseReadData,
  30. Errors: []string{"release not found"},
  31. }, w)
  32. }
  33. // either create a new notification config or update the current one
  34. newConfig := &models.NotificationConfig{
  35. Enabled: form.Payload.Enabled,
  36. Deploy: form.Payload.Deploy,
  37. Success: form.Payload.Success,
  38. Failure: form.Payload.Failure,
  39. }
  40. if release.NotificationConfig == 0 {
  41. newConfig, err = app.Repo.NotificationConfig.CreateNotificationConfig(newConfig)
  42. if err != nil {
  43. app.handleErrorInternal(err, w)
  44. return
  45. }
  46. release.NotificationConfig = newConfig.ID
  47. release, err = app.Repo.Release.UpdateRelease(release)
  48. } else {
  49. newConfig.ID = release.NotificationConfig
  50. newConfig, err = app.Repo.NotificationConfig.UpdateNotificationConfig(newConfig)
  51. }
  52. if err != nil {
  53. app.handleErrorInternal(err, w)
  54. return
  55. }
  56. w.WriteHeader(http.StatusOK)
  57. }