AfroWizzxx
AfroWizzxx

Reputation: 13

Firebase Pub/Sub trigger function is called but event is null

I successfully publish to a topic:

gcloud pubsub topics publish my-topic --message '{"value":"data"}' --attribute value=myValue

and can succesfuly view the entry using the gcloud command:

gcloud beta pubsub subscriptions pull --auto-ack my-subcription

I then created a firebase pubsub onPublish trigger function as follows:

exports.myfunction = functions.pubsub.topic('my-topic').onPublish(event => {

     const attributes = event.data.attributes;
     const message = event.data.json;

     const value= attributes['value'];
     const data = {
         key: value,
         key2: message.value
     };

     let ref= db.collection('devices').doc(value);

     return updateTheDataInMyFirestore(ref, data);
});

What i aim to do is update the data in my firestore to maintain real time data. The function is called but the event is always null and i get the error 'TypeError: Cannot read property 'value' of undefined' when i try to access the attributes. I don't understand why this happens.

Upvotes: 1

Views: 1096

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317758

PubSub handler functions receive a first argument which is a Message type object. (You're calling it event.) According to the API docs that I linked to, the Message object has a property called json, which is the parsed JSON data from the payload of the message.

It looks like you're assuming that data.attributes in the Message contains the payload. It doesn't. Use the Message json property instead:

exports.myfunction = functions.pubsub.topic('my-topic').onPublish(message => {
    const payload = message.json
    console.log(payload)

    const value = payload.value

    // continue processing...
});

Upvotes: 0

Related Questions