-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.go
92 lines (69 loc) · 1.75 KB
/
manager.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
package organization
import (
"context"
"fmt"
"github.com/kamva/mgm/v3"
"github.com/kamva/mgm/v3/field"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
)
type Manager struct {
}
func NewManager() *Manager {
return &Manager{}
}
func (m *Manager) Save(ctx context.Context, name string, creatorID string) (*Organization, error) {
organization := &Organization{
Name: name,
CreatorID: creatorID,
Deleted: false,
}
err := mgm.Coll(organization).CreateWithCtx(ctx, organization)
if err != nil {
return nil, err
}
return organization, nil
}
func (m *Manager) GetByName(ctx context.Context, name string) (*Organization, error) {
organization := &Organization{}
err := mgm.Coll(organization).FirstWithCtx(ctx, bson.M{
"name": name,
"deleted": false,
}, organization)
if err == mongo.ErrNoDocuments {
return nil, fmt.Errorf("organization %s not found", name)
}
if err != nil {
return nil, err
}
return organization, nil
}
func (m *Manager) Get(ctx context.Context, organizationID string) (*Organization, error) {
id, err := primitive.ObjectIDFromHex(organizationID)
if err != nil {
return nil, err
}
organization := &Organization{}
err = mgm.Coll(organization).FirstWithCtx(ctx, bson.M{
field.ID: id,
"deleted": false,
}, organization)
if err == mongo.ErrNoDocuments {
return nil, fmt.Errorf("organization not found")
}
if err != nil {
return nil, err
}
return organization, nil
}
func (m *Manager) NameExists(ctx context.Context, name string) (bool, error) {
count, err := mgm.Coll(&Organization{}).CountDocuments(ctx, bson.M{
"name": name,
"deleted": false,
})
if err != nil {
return false, err
}
return count != 0, nil
}