-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget.go
53 lines (41 loc) · 1.4 KB
/
get.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
package mgorepo
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
mgo "go.mongodb.org/mongo-driver/mongo"
)
func (r Repository[M, D, SF, SORD, SO, UF]) Get(ctx context.Context, id string) (M, error) {
var dao D
var zeroM M
oid, err := primitive.ObjectIDFromHex(id)
if err != nil {
r.logErrorf(err, actionGet, "invalid ObjectId %s", id)
return zeroM, errors.Join(ErrInvalidIDFilter, ErrNotFound, err)
}
filters := bson.D{
{Key: "_id", Value: oid},
{Key: r.deletedAtField, Value: nil},
}
r.logDebugf(actionGet, "filters: %+v", filters)
res := r.Collection().FindOne(ctx, filters)
if errRes := res.Err(); errRes != nil {
if errors.Is(errRes, mgo.ErrNoDocuments) {
r.logErrorf(errRes, actionGet, "%s document not found by id %s", r.collectionName, id)
return zeroM, errors.Join(ErrNotFound, errRes)
}
r.logErrorf(err, actionGet, "error getting %s document by id %s", r.collectionName, id)
return zeroM, err
}
if errDecode := res.Decode(&dao); errDecode != nil {
r.logErrorf(errDecode, actionGet, "error decoding %s document by id %s", r.collectionName, id)
return zeroM, errDecode
}
filler, ok := any(&dao).(DaoFiller[M])
if !ok {
r.logErrorf(ErrInvalidDaoFiller, actionGet, "error building model on get for %s in document id %s", r.collectionName, id)
return zeroM, ErrInvalidDaoFiller
}
return filler.ToModel(), nil
}