-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdelete.go
99 lines (82 loc) · 2.45 KB
/
delete.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package medium
import (
"errors"
"net/http"
"strconv"
"github.com/factly/kavach-server/model"
"github.com/factly/x/errorx"
"github.com/factly/x/loggerx"
"github.com/factly/x/renderx"
"github.com/go-chi/chi"
)
// delete - Delete medium by id
// @Summary Delete a medium
// @Description Delete medium by ID
// @Tags Medium
// @ID delete-medium-by-id
// @Param X-User header string true "User ID"
// @Param medium_id path string true "Medium ID"
// @Success 200
// @Router /media/{medium_id} [delete]
func delete(w http.ResponseWriter, r *http.Request) {
userID, err := strconv.Atoi(r.Header.Get("X-User"))
if err != nil {
renderx.JSON(w, http.StatusBadRequest, nil)
return
}
mediumID := chi.URLParam(r, "medium_id")
id, err := strconv.Atoi(mediumID)
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.InvalidID()))
return
}
result := &model.Medium{}
result.ID = uint(id)
// check record exists or not
err = model.DB.Where(&model.Medium{
UserID: uint(userID),
}).First(&result).Error
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.RecordNotFound()))
return
}
uintID := uint(id)
// check if medium is associated with user
var totAssociated int64
model.DB.Model(&model.User{}).Where(&model.User{
FeaturedMediumID: &uintID,
}).Count(&totAssociated)
if totAssociated != 0 {
loggerx.Error(errors.New("medium is associated with user"))
errorx.Render(w, errorx.Parser(errorx.CannotDelete("media", "user")))
return
}
// check if medium is associated with organisation
model.DB.Model(&model.Organisation{}).Where(&model.Organisation{
FeaturedMediumID: &uintID,
}).Count(&totAssociated)
if totAssociated != 0 {
loggerx.Error(errors.New("medium is associated with organisation"))
errorx.Render(w, errorx.Parser(errorx.CannotDelete("media", "organisation")))
return
}
// check if medium is associated with applications
model.DB.Model(&model.Application{}).Where(&model.Application{
MediumID: &uintID,
}).Count(&totAssociated)
if totAssociated != 0 {
loggerx.Error(errors.New("medium is associated with application"))
errorx.Render(w, errorx.Parser(errorx.CannotDelete("media", "application")))
return
}
err = model.DB.Model(&model.Space{}).Where(&model.Space{MediumID: &result.ID}).Update("medium_id", nil).Error
if err != nil {
loggerx.Error(err)
errorx.Render(w, errorx.Parser(errorx.DBError()))
return
}
model.DB.Delete(&result)
renderx.JSON(w, http.StatusOK, nil)
}