kind0 events are now being updated per pubkey

This commit is contained in:
Chris kerr 2024-07-20 10:03:52 -04:00
parent 36956603ed
commit c7b0e9c390
2 changed files with 21 additions and 16 deletions

View File

@ -41,25 +41,15 @@ func InitCollections(client *mongo.Client, eventKind0, eventKind1 string) {
} }
func HandleEvent(ctx context.Context, evt Event) error { func HandleEvent(ctx context.Context, evt Event) error {
var collection *mongo.Collection
switch evt.Kind { switch evt.Kind {
case 0: case 0:
collection = eventKind0Collection return HandleEventKind0(ctx, evt, eventKind0Collection)
case 1: case 1:
return HandleEventKind1(ctx, evt, eventKind1Collection) return HandleEventKind1(ctx, evt, eventKind1Collection)
default: default:
fmt.Println("Unknown event kind:", evt.Kind) fmt.Println("Unknown event kind:", evt.Kind)
return fmt.Errorf("unknown event kind: %d", evt.Kind) return fmt.Errorf("unknown event kind: %d", evt.Kind)
} }
_, err := collection.InsertOne(ctx, evt)
if err != nil {
fmt.Println("Error inserting event into MongoDB:", err)
return err
}
fmt.Println("Inserted event into MongoDB:", evt.ID)
return nil
} }
func GetCollections() map[string]*mongo.Collection { func GetCollections() map[string]*mongo.Collection {

View File

@ -4,23 +4,38 @@ import (
"context" "context"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
) )
func HandleEventKind0(ctx context.Context, evt Event, collection *mongo.Collection) error { func HandleEventKind0(ctx context.Context, evt Event, collection *mongo.Collection) error {
// Perform specific validation for event kind 1 // Perform specific validation for event kind 0
if !isValidEventKind0(evt) { if !isValidEventKind0(evt) {
return fmt.Errorf("validation failed for event kind 0: %s", evt.ID) return fmt.Errorf("validation failed for event kind 0: %s", evt.ID)
} }
// Insert event into MongoDB // Replace the existing event if it has the same pubkey
_, err := collection.InsertOne(ctx, evt) filter := bson.M{"pubkey": evt.PubKey}
update := bson.M{
"$set": bson.M{
"id": evt.ID,
"created_at": evt.CreatedAt,
"kind": evt.Kind,
"tags": evt.Tags,
"content": evt.Content,
"sig": evt.Sig,
},
}
options := options.Update().SetUpsert(true) // Insert if not found
_, err := collection.UpdateOne(ctx, filter, update, options)
if err != nil { if err != nil {
fmt.Println("Error inserting event into MongoDB:", err) fmt.Println("Error updating/inserting event kind 0 into MongoDB:", err)
return err return err
} }
fmt.Println("Inserted event kind 0 into MongoDB:", evt.ID) fmt.Println("Upserted event kind 0 into MongoDB:", evt.ID)
return nil return nil
} }