javascriptgoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functions

How to decode Google CloudEvent data?


I have a Google Cloud Function that is triggered when a document is written in my Firestore:

functions.cloudEvent('onItemCreate', async (cloudEvent: functions.CloudEvent<any>) => {
    console.log("cloudEvent.data", typeof cloudEvent.data, cloudEvent.data)
    const decodedData = cloudEvent.data.toString('utf8');
    console.log("Decoded Data:", decodedData);
}

// > cloudEvent.data object <Buffer 0a 9e 03 0a 7f 70 72 6f 6a 65 63 74 73 2f 65 69 6e 73 6b 35 67 2d 69 6d 2d 64 65 76 2f 64 61 74 61 62 61 73 65 73 2f 66 69 72 65 73 74 6f 72 65 2d 69 ... 367 more bytes>
// > Decoded Data: 
// �
// oprojects/my-project-id/databases/firestore/my-firestore/documents/items/Rfhg7PU9Rb1i55VNPzxH    
// a�a��������"��������

How do I correctly decode the data as there are some weird characters with my current approach?


Solution

  • When you call .toString('utf8') on the cloudEvent.data object you're just printing the encoded data that exists in the cloudEvent object. That's the reason why you're getting those indistinguishable characters.

    If you want to decode the data, then please use the following lines of code:

    const firestoreReceived = DocumentEventData.decode(cloudEvent.data);
    
    console.log('\nOld value:');
    console.log(JSON.stringify(firestoreReceived.oldValue, null, 2));
    
    console.log('\nNew value:');
    console.log(JSON.stringify(firestoreReceived.value, null, 2));
    

    As seen above, you can now print the old and the new value.