Null Propagation Error In Firebase Cloud Function

Viewed 490

I'm looking to deploy a cloud function where I'm reading from my database. I want to validate a field exists deep in an object so I was trying to use the null propagation operator ?.

Expected Behavior: if a deep key doesn't exist (or anything along the path), the expression below returns undefined.

Example Code: if (doc.data()?.key?.subKey?.subSubKey) { // Do Stuff }

When I deploy, I'm getting an error.

Error: Error occurred while parsing your function triggers.

Clear Problem Statement

Am I doing something stupidly wrong? Are ?. permitted in cloud functions? Its just vanilla JS right?

2 Answers

I just found the optional chaining operator in the MDN docs. From there it seems that it was implement in Node.js version 14, so you're likely using an earlier version either for your Cloud Functions runtime or somewhere in your deployment pipeline.

You'll either have to compile your code down to as supported version, or write the expression fully (which is what a transpiler will do):

if (doc.data() && doc.data().key && doc.data().key.subKey && doc.data().key && doc.data().key.subKey?.subSubKey) { // Do Stuff }

The node version I was using, mismatched the one I specified in my package.json. You can check which version you are using by running the following in your terminal:

node --version

I changed the version with nvm to the appropriate one.

Related