Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

76 linhas
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/AFASystems/presence/internal/pkg/validation"
  9. "github.com/gorilla/mux"
  10. "gorm.io/gorm"
  11. )
  12. func FloorAddController(db *gorm.DB, context context.Context) http.HandlerFunc {
  13. return func(w http.ResponseWriter, r *http.Request) {
  14. var floor model.Floor
  15. if err := json.NewDecoder(r.Body).Decode(&floor); err != nil {
  16. response.BadRequest(w, "invalid request body")
  17. return
  18. }
  19. if err := validation.Struct(&floor); err != nil {
  20. response.BadRequest(w, err.Error())
  21. return
  22. }
  23. if err := db.WithContext(context).Create(&floor).Error; err != nil {
  24. response.InternalError(w, "failed to create floor", err)
  25. return
  26. }
  27. response.JSON(w, http.StatusCreated, map[string]string{"status": "created"})
  28. }
  29. }
  30. func FloorListController(db *gorm.DB, context context.Context) http.HandlerFunc {
  31. return func(w http.ResponseWriter, r *http.Request) {
  32. var floors []model.Floor
  33. if err := db.WithContext(context).Find(&floors).Error; err != nil {
  34. response.InternalError(w, "failed to list floors", err)
  35. return
  36. }
  37. if err := db.WithContext(context).Find(&floors).Error; err != nil {
  38. response.InternalError(w, "failed to list floors", err)
  39. return
  40. }
  41. response.JSON(w, http.StatusOK, floors)
  42. }
  43. }
  44. func FloorUpdateController(db *gorm.DB, context context.Context) http.HandlerFunc {
  45. return func(w http.ResponseWriter, r *http.Request) {
  46. var floor model.Floor
  47. if err := json.NewDecoder(r.Body).Decode(&floor); err != nil {
  48. response.BadRequest(w, "invalid request body")
  49. return
  50. }
  51. }
  52. }
  53. func FloorDeleteController(db *gorm.DB, context context.Context) http.HandlerFunc {
  54. return func(w http.ResponseWriter, r *http.Request) {
  55. id := mux.Vars(r)["id"]
  56. res := db.WithContext(context).Delete(&model.Floor{}, "id = ?", id)
  57. if res.RowsAffected == 0 {
  58. response.NotFound(w, "floor not found")
  59. return
  60. }
  61. if res.Error != nil {
  62. response.InternalError(w, "failed to delete floor", res.Error)
  63. return
  64. }
  65. response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"})
  66. }
  67. }