event_handler.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package api
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/url"
  6. "strconv"
  7. "github.com/go-chi/chi"
  8. "github.com/porter-dev/porter/internal/forms"
  9. )
  10. // HandleCreateEvent creates a new event in a project
  11. func (app *App) HandleCreateEvent(w http.ResponseWriter, r *http.Request) {
  12. projID, err := strconv.ParseUint(chi.URLParam(r, "project_id"), 0, 64)
  13. if err != nil || projID == 0 {
  14. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  15. return
  16. }
  17. vals, err := url.ParseQuery(r.URL.RawQuery)
  18. clusterID, err := strconv.ParseUint(vals["cluster_id"][0], 10, 64)
  19. if err != nil {
  20. app.sendExternalError(err, http.StatusInternalServerError, HTTPError{
  21. Code: ErrReleaseReadData,
  22. Errors: []string{"cluster not found"},
  23. }, w)
  24. }
  25. form := &forms.CreateEventForm{}
  26. // decode from JSON to form value
  27. if err := json.NewDecoder(r.Body).Decode(form); err != nil {
  28. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  29. return
  30. }
  31. // validate the form
  32. if err := app.validator.Struct(form); err != nil {
  33. app.handleErrorFormValidation(err, ErrProjectValidateFields, w)
  34. return
  35. }
  36. // convert the form to an invite
  37. event := form.ToEvent(uint(projID), uint(clusterID))
  38. if err != nil {
  39. app.handleErrorFormDecoding(err, ErrProjectDecode, w)
  40. return
  41. }
  42. // handle write to the database
  43. event, err = app.Repo.Event.CreateEvent(event)
  44. if err != nil {
  45. app.handleErrorDataWrite(err, w)
  46. return
  47. }
  48. w.WriteHeader(http.StatusCreated)
  49. }