-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate.go
86 lines (62 loc) · 2.07 KB
/
create.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
package mgorepo
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson"
)
// Create creates a new record on the collection based on the model.
func (r Repository[M, D, SF, SORD, SO, UF]) Create(ctx context.Context, model M) (M, error) {
var zeroM M
data, err := r.createBuildData(model)
if err != nil {
return zeroM, err
}
r.logDebugf(actionCreate, "data: %+v", data)
res, err := r.Collection().InsertOne(ctx, data)
if err != nil {
r.logErrorf(err, actionCreate, "error inserting %s DAO", r.collectionName)
return zeroM, err
}
data["_id"] = res.InsertedID
r.logDebugf(actionCreate, "insertedId: %+v", res.InsertedID)
resModel, err := r.createBuildModel(data)
return resModel, err
}
func (r Repository[M, D, SF, SORD, SO, UF]) createBuildModel(data bson.M) (M, error) {
var zeroM M
dao := new(D)
bytes, err := bson.Marshal(data)
if err != nil {
r.log.Errorf(err, actionCreate, "error creating %s model", r.collectionName)
return zeroM, errors.Join(ErrCreatingModel, err)
}
if err := bson.Unmarshal(bytes, dao); err != nil {
r.log.Errorf(err, actionCreate, "error creating %s model", r.collectionName)
return zeroM, errors.Join(ErrCreatingModel, err)
}
filler := any(dao).(DaoFiller[M])
return filler.ToModel(), nil
}
func (r Repository[M, D, SF, SORD, SO, UF]) createBuildData(model M) (bson.M, error) {
dao := any(new(D)).(DaoFiller[M])
if errDao := dao.FromModel(model); errDao != nil {
r.logErrorf(errDao, actionCreate, "error filling %s DAO", r.collectionName)
return bson.M{}, errors.Join(ErrCreatingDAO, errDao)
}
bsonData := bson.M{}
bsonBytes, err := bson.Marshal(dao)
if err != nil {
r.log.Errorf(err, actionCreate, "error filling %s DAO", r.collectionName)
return bson.M{}, errors.Join(ErrCreatingDAO, err)
}
if err := bson.Unmarshal(bsonBytes, &bsonData); err != nil {
r.log.Errorf(err, actionCreate, "error filling %s DAO", r.collectionName)
return bson.M{}, errors.Join(ErrCreatingDAO, err)
}
if r.withTimestamps {
now := r.Now()
bsonData["createdAt"] = now
bsonData["updatedAt"] = now
}
return bsonData, nil
}