mirror of
https://github.com/0ceanSlim/grain.git
synced 2024-11-24 01:17:13 +00:00
check for duplicates before storing
This commit is contained in:
parent
a7ade9a40d
commit
353510b74f
25
server/db/mongo/checkDuplicate.go
Normal file
25
server/db/mongo/checkDuplicate.go
Normal 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
|
||||
}
|
@ -66,6 +66,19 @@ func HandleEvent(ws *websocket.Conn, message []interface{}) {
|
||||
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
|
||||
mongo.StoreMongoEvent(context.TODO(), evt, ws)
|
||||
fmt.Println("Event processed:", evt.ID)
|
||||
|
Loading…
Reference in New Issue
Block a user