Skip to content

Commit

Permalink
feat: optimized api response code
Browse files Browse the repository at this point in the history
  • Loading branch information
tikazyq committed Nov 13, 2024
1 parent 86669be commit c6ca5cb
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 6 deletions.
14 changes: 12 additions & 2 deletions core/controllers/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ func (ctr *BaseController[T]) DeleteById(c *gin.Context) {

func (ctr *BaseController[T]) DeleteList(c *gin.Context) {
type Payload struct {
Ids []primitive.ObjectID `json:"ids"`
Ids []string `json:"ids"`
}

var payload Payload
Expand All @@ -162,9 +162,19 @@ func (ctr *BaseController[T]) DeleteList(c *gin.Context) {
return
}

var ids []primitive.ObjectID
for _, id := range payload.Ids {
objectId, err := primitive.ObjectIDFromHex(id)
if err != nil {
HandleErrorBadRequest(c, err)
return
}
ids = append(ids, objectId)
}

if err := ctr.modelSvc.DeleteMany(bson.M{
"_id": bson.M{
"$in": payload.Ids,
"$in": ids,
},
}); err != nil {
HandleErrorInternalServerError(c, err)
Expand Down
4 changes: 2 additions & 2 deletions core/controllers/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func DeleteUserById(c *gin.Context) {
return
}
if user.RootAdmin {
HandleErrorBadRequest(c, errors.New("root admin cannot be deleted"))
HandleErrorForbidden(c, errors.New("root admin cannot be deleted"))
return
}

Expand Down Expand Up @@ -217,7 +217,7 @@ func DeleteUserList(c *gin.Context) {
"root_admin": true,
}, nil)
if err == nil {
HandleErrorBadRequest(c, errors.New("root admin cannot be deleted"))
HandleErrorForbidden(c, errors.New("root admin cannot be deleted"))
return
}
if !errors.Is(err, mongo2.ErrNoDocuments) {
Expand Down
4 changes: 2 additions & 2 deletions core/controllers/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ func TestDeleteUserById_Success(t *testing.T) {

w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, http.StatusForbidden, w.Code)

// Test deleting with invalid ID
req, err = http.NewRequest(http.MethodDelete, "/users/invalid-id", nil)
Expand Down Expand Up @@ -492,7 +492,7 @@ func TestDeleteUserList_Success(t *testing.T) {

w = httptest.NewRecorder()
router.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, http.StatusForbidden, w.Code)

// Test with mix of valid and invalid ids
reqBody = strings.NewReader(fmt.Sprintf(`{"ids":["%s","invalid-id"]}`, normalUserIds[0].Hex()))
Expand Down

0 comments on commit c6ca5cb

Please sign in to comment.