check for duplicates before storing

This commit is contained in:
Chris kerr 2024-11-09 11:32:23 -05:00
parent a7ade9a40d
commit 353510b74f
2 changed files with 50 additions and 12 deletions

View File

@ -0,0 +1,25 @@
package mongo
import (
"context"
"fmt"
nostr "grain/server/types" // Adjust import path as needed
"go.mongodb.org/mongo-driver/bson"
)
// CheckDuplicateEvent checks if an event with the same ID already exists in the collection.
func CheckDuplicateEvent(ctx context.Context, evt nostr.Event) (bool, error) {
collection := GetCollection(evt.Kind)
filter := bson.M{"id": evt.ID}
var existingEvent nostr.Event
err := collection.FindOne(ctx, filter).Decode(&existingEvent)
if err != nil {
if err.Error() == "mongo: no documents in result" {
return false, nil // No duplicate found
}
return false, fmt.Errorf("error checking for duplicate event: %v", err)
}
return true, nil // Duplicate found
}

View File

@ -66,6 +66,19 @@ func HandleEvent(ws *websocket.Conn, message []interface{}) {
return return
} }
// Check for duplicate event
isDuplicate, err := mongo.CheckDuplicateEvent(context.TODO(), evt)
if err != nil {
fmt.Printf("Error checking for duplicate event: %v\n", err)
response.SendOK(ws, evt.ID, false, "error: internal server error during duplicate check")
return
}
if isDuplicate {
response.SendOK(ws, evt.ID, false, "blocked: the database already contains this event")
return
}
// Store the event in MongoDB or other storage // Store the event in MongoDB or other storage
mongo.StoreMongoEvent(context.TODO(), evt, ws) mongo.StoreMongoEvent(context.TODO(), evt, ws)
fmt.Println("Event processed:", evt.ID) fmt.Println("Event processed:", evt.ID)