/
right_service.go
101 lines (76 loc) · 2.01 KB
/
right_service.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
100
101
package permissions
import (
"context"
"github.com/georgi-georgiev/passport"
"github.com/georgi-georgiev/passport/payloads"
"github.com/rotisserie/eris"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.uber.org/zap"
)
type RightService struct {
repository *RightRepository
conf *passport.Config
log *zap.Logger
}
func NewRightService(repository *RightRepository, conf *passport.Config, log *zap.Logger) *RightService {
return &RightService{repository: repository, conf: conf, log: log}
}
func (s *RightService) CreateRight(ctx context.Context, payload payloads.CreateRightPayload) (*Right, error) {
right := &Right{
Name: payload.Name,
}
_, err := s.repository.Create(ctx, right)
if err != nil {
return nil, err
}
return right, nil
}
func (s *RightService) GetByName(ctx context.Context, name string) (*Right, error) {
return s.repository.GetByName(ctx, name)
}
func (s *RightService) GetManyByIds(ctx context.Context, ids []primitive.ObjectID) ([]Right, error) {
filter := bson.M{"_id": bson.M{"$in": ids}}
cursor, err := s.repository.Collection.Find(ctx, filter)
if err != nil {
return nil, err
}
defer cursor.Close(ctx)
var rights []Right
for cursor.Next(ctx) {
var right Right
if err := cursor.Decode(&right); err != nil {
return nil, err
}
rights = append(rights, right)
}
if err := cursor.Err(); err != nil {
return nil, err
}
return rights, nil
}
func (s *RightService) GetRights(ctx context.Context) ([]*Right, error) {
rights, err := s.repository.GetAll(ctx)
if err != nil {
return nil, eris.Wrap(err, "could no get all rights")
}
return rights, nil
}
func (s *RightService) UpdateRight(ctx context.Context, id primitive.ObjectID, name string) (*Right, error) {
r := &Right{}
found, err := s.repository.GetById(ctx, id, r)
if err != nil {
return nil, err
}
if !found {
return nil, nil
}
if r.Name != name {
r.Name = name
}
err = s.repository.Update(ctx, r)
if err != nil {
return nil, err
}
return r, nil
}