Move audit subscribe to client, Fix tests
This commit is contained in:
24
insert.go
24
insert.go
@@ -2,8 +2,11 @@ package mongo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
|
||||
"git.gsuntres.com/general/commons"
|
||||
)
|
||||
|
||||
|
||||
@@ -18,9 +21,11 @@ func (c *MongoClient) InsertOneFromStruct(ctx context.Context, database, name st
|
||||
}
|
||||
|
||||
// InsertOne will add missing ids and the created date before saving to the database.
|
||||
func (c *MongoClient) InsertOne(ctx context.Context, database, name string, data bson.M) (bson.M, error) {
|
||||
func (c *MongoClient) InsertOne(ctx context.Context, database, name string, original bson.M) (bson.M, error) {
|
||||
collection := c.GetCollection(database, name)
|
||||
|
||||
data := commons.BsonClone(original)
|
||||
|
||||
prepareForInsert(data, c.GetIdPrefix(name))
|
||||
|
||||
if err := c.DiscriminatorCheckAndApplyToData(ctx, name, data); err != nil {
|
||||
@@ -30,6 +35,21 @@ func (c *MongoClient) InsertOne(ctx context.Context, database, name string, data
|
||||
if _, err := collection.InsertOne(ctx, data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ignoreAudit := slices.Contains(c.IgnoreAudit, name)
|
||||
|
||||
if c.WithAudit && !ignoreAudit {
|
||||
contx := commons.ContextSerialize(ctx, c.ContextFields)
|
||||
audit := &AuditResult {
|
||||
Entity: name,
|
||||
Op: OpInsert,
|
||||
Data: original,
|
||||
After: data,
|
||||
Context: contx,
|
||||
}
|
||||
|
||||
(*c.OnAudit)(audit)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
@@ -42,5 +62,3 @@ func prepareForInsert(data bson.M, idPrefix string) {
|
||||
ensureCreatedAt(data)
|
||||
ensureUpdatedAt(data)
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user