/
logs.go
115 lines (88 loc) · 2.41 KB
/
logs.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
package atlas
import (
"context"
"fmt"
"time"
"github.com/DarioAle/counter-api"
guuid "github.com/google/uuid"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
// Collection keeps the collection name
const Collection = "logs"
// log model for mongodb
type log struct {
ID string `bson:"_id"`
Count int `bson:"count,omitempty"`
ImageKey string `bson:"image_key,omitempty"`
DeviceID string `bson:"device_id,omitempty"`
ShapeID string `bson:"shape_id,omitempty"`
CreatedAt time.Time `bson:"createdAt"`
UpdatedAt time.Time `bson:"updatedAt"`
}
func (r *repository) CreateLog(ctx context.Context, countLog counter.Log) (counter.Log, error) {
collection := r.mongo.Collection(Collection)
time := time.Now()
uuid := guuid.New().String()
insert := &log{
ID: uuid,
ImageKey: countLog.ImageKey,
DeviceID: countLog.DeviceID,
ShapeID: countLog.ShapeID,
CreatedAt: time,
UpdatedAt: time,
}
_, err := collection.InsertOne(ctx, insert)
if err != nil {
return counter.Log{}, err
}
return insert.toModel(), nil
}
// GetByID retrieves a log with the ID
func (r *repository) GetByID(ctx context.Context, id string) (counter.Log, error) {
collection := r.mongo.Collection(Collection)
var response log
filter := bson.M{"_id": id}
err := collection.FindOne(ctx, filter).Decode(&response)
if err != nil {
if err == mongo.ErrNoDocuments {
return counter.Log{}, fmt.Errorf("not found")
}
return counter.Log{}, err
}
return response.toModel(), nil
}
func (r *repository) UpdateLog(ctx context.Context, id string, countLog counter.Log) (counter.Log, error) {
collection := r.mongo.Collection(Collection)
time := time.Now()
var insert log
filter := bson.M{"_id": id}
err := collection.FindOne(ctx, filter).Decode(&insert)
if err != nil {
if err == mongo.ErrNoDocuments {
return counter.Log{}, fmt.Errorf("not found")
}
return counter.Log{}, err
}
insert.UpdatedAt = time
insert.Count = countLog.Count
update := bson.M{
"$set": insert,
}
_, err = collection.UpdateOne(ctx, filter, update)
if err != nil {
return counter.Log{}, err
}
return insert.toModel(), nil
}
func (l log) toModel() counter.Log {
return counter.Log{
ID: l.ID,
Count: l.Count,
ImageKey: l.ImageKey,
DeviceID: l.DeviceID,
ShapeID: l.ShapeID,
CreatedAt: l.CreatedAt.UTC().String(),
UpdatedAt: l.UpdatedAt.UTC().String(),
}
}