您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

80 行
2.3 KiB

  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "github.com/AFASystems/presence/internal/pkg/api/response"
  8. "github.com/AFASystems/presence/internal/pkg/service"
  9. "github.com/AFASystems/presence/internal/pkg/validation"
  10. "github.com/gorilla/mux"
  11. "gorm.io/gorm"
  12. )
  13. func AlertsListController(db *gorm.DB, ctx context.Context) http.HandlerFunc {
  14. return func(w http.ResponseWriter, r *http.Request) {
  15. alerts, err := service.GetAllAlerts(db, ctx)
  16. if err != nil {
  17. response.InternalError(w, "failed to list alerts", err)
  18. return
  19. }
  20. response.JSON(w, http.StatusOK, alerts)
  21. }
  22. }
  23. func ListAlertsByTrackerIDController(db *gorm.DB, ctx context.Context) http.HandlerFunc {
  24. return func(w http.ResponseWriter, r *http.Request) {
  25. id := mux.Vars(r)["id"]
  26. alert, err := service.GetAlertById(id, db, ctx)
  27. if err != nil {
  28. if errors.Is(err, gorm.ErrRecordNotFound) {
  29. response.NotFound(w, "alert not found")
  30. return
  31. }
  32. response.InternalError(w, "failed to get alert", err)
  33. return
  34. }
  35. response.JSON(w, http.StatusOK, alert)
  36. }
  37. }
  38. func AlertDeleteController(db *gorm.DB, ctx context.Context) http.HandlerFunc {
  39. return func(w http.ResponseWriter, r *http.Request) {
  40. id := mux.Vars(r)["id"]
  41. if err := service.DeleteAlertByTrackerID(id, db, ctx); err != nil {
  42. response.InternalError(w, "failed to delete alert", err)
  43. return
  44. }
  45. response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"})
  46. }
  47. }
  48. // AlertUpdateStatusController updates an alert's status by id. Body: {"status": "resolved"} (or other status string).
  49. func AlertUpdateStatusController(db *gorm.DB, ctx context.Context) http.HandlerFunc {
  50. return func(w http.ResponseWriter, r *http.Request) {
  51. id := mux.Vars(r)["id"]
  52. var body struct {
  53. Status string `json:"status"`
  54. }
  55. if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
  56. response.BadRequest(w, "invalid request body")
  57. return
  58. }
  59. if err := validation.Var(body.Status, "required"); err != nil {
  60. response.BadRequest(w, err.Error())
  61. return
  62. }
  63. if err := service.UpdateAlertStatus(id, body.Status, db, ctx); err != nil {
  64. if errors.Is(err, gorm.ErrRecordNotFound) {
  65. response.NotFound(w, "alert not found")
  66. return
  67. }
  68. response.InternalError(w, "failed to update alert status", err)
  69. return
  70. }
  71. response.JSON(w, http.StatusOK, map[string]string{"status": "updated"})
  72. }
  73. }