-
Notifications
You must be signed in to change notification settings - Fork 0
/
next.go
64 lines (58 loc) · 1.54 KB
/
next.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
package db
import (
"context"
"time"
"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"
"github.com/nam-truong-le/lambda-utils-go/v3/pkg/logger"
)
func Next(ctx context.Context, key string) (int64, error) {
log := logger.FromContext(ctx)
log.Infof("next increment of [%s]", key)
colIncrement, err := collectionIncrement(ctx)
if err != nil {
return 0, err
}
inc := new(increment)
findExisting := colIncrement.FindOne(ctx, bson.M{"key": key})
if err := findExisting.Decode(inc); err != nil {
if err != mongo.ErrNoDocuments {
log.Info("unwanted error from mongo")
return 0, err
}
log.Infof("no existing increment found for [%s], create new increment", key)
create, err := colIncrement.InsertOne(ctx, increment{
ID: primitive.NewObjectID(),
Value: 0,
Key: key,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
if err != nil {
return 0, err
}
findNew := colIncrement.FindOne(ctx, bson.M{"_id": create.InsertedID})
if err := findNew.Decode(inc); err != nil {
return 0, err
}
}
returnAfter := options.After
opts := options.FindOneAndUpdateOptions{
ReturnDocument: &returnAfter,
}
update := colIncrement.FindOneAndUpdate(ctx, bson.M{"key": key}, bson.M{
"$set": bson.M{
"updatedAt": time.Now(),
},
"$inc": bson.M{
"value": 1,
},
}, &opts)
updatedInc := new(increment)
if err := update.Decode(updatedInc); err != nil {
return 0, err
}
return updatedInc.Value, nil
}