/
database.go
225 lines (186 loc) · 5.2 KB
/
database.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package commentdb
import (
"context"
"errors"
"fmt"
"time"
"github.com/tierklinik-dobersberg/cis/pkg/httperr"
"github.com/tierklinik-dobersberg/cis/pkg/models/comment/v1alpha"
"github.com/tierklinik-dobersberg/cis/pkg/pkglog"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var log = pkglog.New("commentdb")
// CommentCollection is the MongoDB collection name
// that holds all comments.
const CommentCollection = "comments"
type Database interface {
// Create creates a new comment.
Create(ctx context.Context, key string, userId, message string) (string, error)
// Reply replies to a comment.
Reply(ctx context.Context, id string, userId, message string) (string, error)
// ByID returns a singel comment by ID.
ByID(ctx context.Context, id string) (*v1alpha.Comment, error)
// ByKey returns all comments that are associated with key.
ByKey(ctx context.Context, key string, prefix bool) ([]v1alpha.Comment, error)
}
type database struct {
cli *mongo.Client
comments *mongo.Collection
}
// New connects to the MongoDB server at URL and returns
// a new database interface.
func New(ctx context.Context, url, dbName string) (Database, error) {
clientConfig := options.Client().ApplyURI(url)
client, err := mongo.NewClient(clientConfig)
if err != nil {
return nil, fmt.Errorf("failed to create client: %w", err)
}
// Try to connect
if err := client.Connect(ctx); err != nil {
return nil, fmt.Errorf("failed to connect to server %s: %w", url, err)
}
commentDB, err := NewWithClient(ctx, dbName, client)
if err != nil {
defer func() {
if err := client.Disconnect(ctx); err != nil {
log.From(ctx).Errorf("failed to gracefully disconnect from MongoDB: %s", err)
}
}()
return nil, err
}
return commentDB, nil
}
// NewWithClient is like New but uses an already existing mongodb client.
func NewWithClient(ctx context.Context, dbName string, client *mongo.Client) (Database, error) {
if err := client.Ping(ctx, nil); err != nil {
return nil, err
}
commentDB := &database{
cli: client,
comments: client.Database(dbName).Collection(CommentCollection),
}
// prepare collections and indexes.
if err := commentDB.setup(ctx); err != nil {
return nil, err
}
return commentDB, nil
}
func (db *database) setup(ctx context.Context) error {
_, err := db.comments.Indexes().CreateMany(ctx, []mongo.IndexModel{
{
Keys: bson.D{
{Key: "parentID", Value: 1},
},
},
{
Keys: bson.D{
{Key: "key", Value: 1},
},
},
{
Keys: bson.D{
{Key: "user", Value: 1},
},
},
})
if err != nil {
return fmt.Errorf("creating indexes: %w", err)
}
return nil
}
func (db *database) Create(ctx context.Context, key string, userId, message string) (string, error) {
c := v1alpha.Comment{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Key: key,
UserId: userId,
Message: message,
}
result, err := db.comments.InsertOne(ctx, c)
if err != nil {
return "", fmt.Errorf("failed to insert comment: %w", err)
}
id, ok := result.InsertedID.(primitive.ObjectID)
if !ok {
return "", fmt.Errorf("failed to get ID of new comment, invalid type %T", result.InsertedID)
}
return id.String(), nil
}
func (db *database) Reply(ctx context.Context, id string, userId, message string) (string, error) {
parent, err := db.ByID(ctx, id)
if err != nil {
return "", err
}
c := v1alpha.Comment{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Key: parent.Key,
ParentID: parent.ID,
UserId: userId,
Message: message,
}
result, err := db.comments.InsertOne(ctx, c)
if err != nil {
return "", err
}
cid, ok := result.InsertedID.(primitive.ObjectID)
if !ok {
return "", fmt.Errorf("failed to get ID of new comment, invalid type %T", result.InsertedID)
}
return cid.String(), nil
}
func (db *database) ByID(ctx context.Context, id string) (*v1alpha.Comment, error) {
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
return nil, httperr.BadRequest(err)
}
result := db.comments.FindOne(ctx, bson.M{
"_id": oid,
})
if err := result.Err(); err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, httperr.NotFound("comment", id).SetInternal(err)
}
return nil, err
}
var c v1alpha.Comment
if err := result.Decode(&c); err != nil {
return nil, fmt.Errorf("failed to decode comment: %w", err)
}
return &c, nil
}
func (db *database) ByKey(ctx context.Context, key string, prefix bool) ([]v1alpha.Comment, error) {
opts := options.Find()
opts.SetSort(bson.M{
"createdAt": 1,
})
filter := bson.M{
"key": key,
}
if prefix {
filter = bson.M{
"key": bson.M{
"$regex": primitive.Regex{
Pattern: "^" + key,
Options: "i",
},
},
}
}
results, err := db.comments.Find(ctx, filter, opts)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, httperr.NotFound("comments", key).SetInternal(err)
}
return nil, fmt.Errorf("failed to query comments: %w", err)
}
defer results.Close(ctx)
var comments []v1alpha.Comment
if err := results.All(ctx, &comments); err != nil {
return nil, fmt.Errorf("failed to decode comments: %w", err)
}
return comments, nil
}