-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete_view.go
More file actions
69 lines (57 loc) · 1.64 KB
/
delete_view.go
File metadata and controls
69 lines (57 loc) · 1.64 KB
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
package database
import (
"encoding/json"
"fmt"
"time"
"github.com/labbs/nexo/infrastructure/helpers/apperrors"
"github.com/labbs/nexo/application/database/dto"
spaceDto "github.com/labbs/nexo/application/space/dto"
"github.com/labbs/nexo/domain"
)
func (app *DatabaseApplication) DeleteView(input dto.DeleteViewInput) error {
database, err := app.DatabasePers.GetById(input.DatabaseId)
if err != nil {
return fmt.Errorf("database not found: %w", err)
}
// Verify user has access to the space
spaceResult, err := app.SpaceApplication.GetSpaceById(spaceDto.GetSpaceByIdInput{SpaceId: database.SpaceId})
if err != nil {
return fmt.Errorf("space not found: %w", err)
}
if spaceResult.Space.GetUserRole(input.UserId) == nil {
return apperrors.ErrAccessDenied
}
// Parse existing views
var views []dto.ViewConfig
if database.Views != nil {
viewsJSON, _ := json.Marshal(database.Views)
json.Unmarshal(viewsJSON, &views)
}
// Cannot delete the last view
if len(views) <= 1 {
return fmt.Errorf("cannot delete last view")
}
// Find and remove the view
found := false
newViews := make([]dto.ViewConfig, 0, len(views)-1)
for _, view := range views {
if view.Id == input.ViewId {
found = true
continue
}
newViews = append(newViews, view)
}
if !found {
return fmt.Errorf("view not found")
}
// Save back to database
viewsJSON, _ := json.Marshal(newViews)
var viewsArray domain.JSONBArray
json.Unmarshal(viewsJSON, &viewsArray)
database.Views = viewsArray
database.UpdatedAt = time.Now()
if err := app.DatabasePers.Update(database); err != nil {
return fmt.Errorf("failed to delete view: %w", err)
}
return nil
}