How to extarxt a background event?

54 Views Asked by At

I have deployed a cloud function as bellow

package functions

import (
    "context"
    "encoding/json"
    "log"

    "github.com/Capstone/models"
    "github.com/GoogleCloudPlatform/functions-framework-go/functions"
    "github.com/cloudevents/sdk-go/v2/event"
)

func init() {
    // Register a CloudEvent function with the Functions Framework
    functions.CloudEvent("StoreAuditRecords", StoreAuditRecords)
}

func StoreAuditRecords(ctx context.Context, m event.Event) error {

    // Extract data from CloudEvent
    data := m.Data()

    // Unmarshal the decoded data into the AuditRecord struct
    var auditRecord models.AuditRecord
    if err := json.Unmarshal(data, &auditRecord); err != nil {
        log.Printf("Error unmarshaling data: %v", err)
        return err
    }

    // Store data to Firestore
    _, _, err := firestoreClient.Collection("audit-records").Add(ctx, auditRecord)
    if err != nil {
        log.Printf("Error storing data to Firestore: %v", err)
        return err
    }

    return nil
}

It processes the pub/sub message and store it into a collection named "audit-records". All the clients are initialized appropriately.

Note that - I have a push subscription to which this function's endpoint url is linked to with the Push payload unwrapping enabled.

But I am facing an error that is

unable to extract background event from {"Action":"Update","DocumentId":"P3y4uItPTGR1ACdj8vCx","Timestamp":"2024-01-29 05:48:31","UserId":"[email protected]"}

Where {"Action":"Update","DocumentId":"P3y4uItPTGR1ACdj8vCx","Timestamp":"2024-01-29 05:48:31","UserId":"[email protected]"} is the message data being published to pubsub topic to which it subscribe.

I seek help.

I want to store the message payload data to my collection as in code but I am getting the error above.

0

There are 0 best solutions below