|
- package controller
-
- import (
- "context"
- "encoding/json"
- "net/http"
-
- "github.com/AFASystems/presence/internal/pkg/api/response"
- "github.com/AFASystems/presence/internal/pkg/model"
- "github.com/AFASystems/presence/internal/pkg/validation"
- "github.com/gorilla/mux"
- "gorm.io/gorm"
- )
-
- func TrackerZoneAddController(db *gorm.DB, context context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var tz model.TrackerZones
- if err := json.NewDecoder(r.Body).Decode(&tz); err != nil {
- response.BadRequest(w, "invalid request body")
- return
- }
- if err := validation.Struct(&tz); err != nil {
- response.BadRequest(w, err.Error())
- return
- }
- if err := db.WithContext(context).Create(&tz).Error; err != nil {
- response.InternalError(w, "failed to create tracker zone", err)
- return
- }
-
- response.JSON(w, http.StatusCreated, map[string]string{"status": "created"})
- }
- }
-
- func TrackerZoneListController(db *gorm.DB, context context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var list []model.TrackerZones
- if err := db.WithContext(context).Find(&list).Error; err != nil {
- response.InternalError(w, "failed to list tracker zones", err)
- return
- }
- response.JSON(w, http.StatusOK, list)
- }
- }
-
- func TrackerZoneUpdateController(db *gorm.DB, context context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- var tz model.TrackerZones
- if err := json.NewDecoder(r.Body).Decode(&tz); err != nil {
- response.BadRequest(w, "invalid request body")
- return
- }
- if err := validation.Struct(&tz); err != nil {
- response.BadRequest(w, err.Error())
- return
- }
-
- id := tz.ID
- if err := db.WithContext(context).First(&model.TrackerZones{}, "id = ?", id).Error; err != nil {
- response.NotFound(w, "tracker zone not found")
- return
- }
-
- if err := db.WithContext(context).Save(&tz).Error; err != nil {
- response.InternalError(w, "failed to update tracker zone", err)
- return
- }
-
- response.JSON(w, http.StatusOK, map[string]string{"status": "updated"})
- }
- }
-
- func TrackerZoneDeleteController(db *gorm.DB, context context.Context) http.HandlerFunc {
- return func(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- res := db.WithContext(context).Delete(&model.TrackerZones{}, "id = ?", id)
- if res.RowsAffected == 0 {
- response.NotFound(w, "tracker zone not found")
- return
- }
- if res.Error != nil {
- response.InternalError(w, "failed to delete tracker zone", res.Error)
- return
- }
-
- response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"})
- }
- }
|