Add Audit cababilities. First try on deleteOne
This commit is contained in:
54
delete.go
Normal file
54
delete.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package mongo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"slices"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
|
||||
"git.gsuntres.com/general/mongo/options"
|
||||
"git.gsuntres.com/general/commons"
|
||||
)
|
||||
|
||||
// DeleteOne will delete the first document that matches the filter.
|
||||
func (c *MongoClient) DeleteOne(ctx context.Context, database, name string, filter bson.M, opts ...options.Lister[options.DeleteOneOptions]) error {
|
||||
var err error
|
||||
|
||||
// 1. Prepare query.
|
||||
collection := c.GetCollection(database, name)
|
||||
|
||||
// 2. Check discriminator and mongofy
|
||||
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
f := Mongofy(&Query{ Filter: filter })
|
||||
|
||||
var found bson.M
|
||||
if c.WithAudit {
|
||||
err = collection.FindOne(ctx, f).Decode(&found)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Delete
|
||||
_, err = collection.DeleteOne(ctx, f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if c.WithAudit && !slices.Contains(c.IgnoreAudit, name) {
|
||||
contx := commons.ContextSerialize(ctx, c.ContextFields)
|
||||
audit := &AuditResult {
|
||||
Entity: name,
|
||||
Op: OpDelete,
|
||||
Before: found,
|
||||
Context: contx,
|
||||
}
|
||||
|
||||
(*c.OnAudit)(audit)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user