You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

80 rivejä
2.2 KiB

  1. package controller
  2. import (
  3. "context"
  4. "encoding/json"
  5. "net/http"
  6. "github.com/AFASystems/presence/internal/pkg/api/response"
  7. "github.com/AFASystems/presence/internal/pkg/model"
  8. "github.com/gorilla/mux"
  9. "gorm.io/gorm"
  10. )
  11. func ZoneAddController(db *gorm.DB, context context.Context) http.HandlerFunc {
  12. return func(w http.ResponseWriter, r *http.Request) {
  13. var zone model.Zone
  14. if err := json.NewDecoder(r.Body).Decode(&zone); err != nil {
  15. response.BadRequest(w, "invalid request body")
  16. return
  17. }
  18. if err := db.WithContext(context).Create(&zone).Error; err != nil {
  19. response.InternalError(w, "failed to create zone", err)
  20. return
  21. }
  22. response.JSON(w, http.StatusCreated, map[string]string{"status": "created"})
  23. }
  24. }
  25. func ZoneListController(db *gorm.DB, context context.Context) http.HandlerFunc {
  26. return func(w http.ResponseWriter, r *http.Request) {
  27. var zones []model.Zone
  28. if err := db.WithContext(context).Find(&zones).Error; err != nil {
  29. response.InternalError(w, "failed to list zones", err)
  30. return
  31. }
  32. response.JSON(w, http.StatusOK, zones)
  33. }
  34. }
  35. func ZoneUpdateController(db *gorm.DB, context context.Context) http.HandlerFunc {
  36. return func(w http.ResponseWriter, r *http.Request) {
  37. var zone model.Zone
  38. if err := json.NewDecoder(r.Body).Decode(&zone); err != nil {
  39. response.BadRequest(w, "invalid request body")
  40. return
  41. }
  42. id := zone.ID
  43. if err := db.WithContext(context).First(&model.Zone{}, "id = ?", id).Error; err != nil {
  44. response.NotFound(w, "zone not found")
  45. return
  46. }
  47. if err := db.WithContext(context).Save(&zone).Error; err != nil {
  48. response.InternalError(w, "failed to update zone", err)
  49. return
  50. }
  51. response.JSON(w, http.StatusOK, map[string]string{"status": "updated"})
  52. }
  53. }
  54. func ZoneDeleteController(db *gorm.DB, context context.Context) http.HandlerFunc {
  55. return func(w http.ResponseWriter, r *http.Request) {
  56. id := mux.Vars(r)["id"]
  57. res := db.WithContext(context).Delete(&model.Zone{}, "id = ?", id)
  58. if res.RowsAffected == 0 {
  59. response.NotFound(w, "zone not found")
  60. return
  61. }
  62. if res.Error != nil {
  63. response.InternalError(w, "failed to delete zone", res.Error)
  64. return
  65. }
  66. response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"})
  67. }
  68. }