Home > OS >  Firebase google cloud function to return a Snapshot
Firebase google cloud function to return a Snapshot

Time:07-02

Is it possible to return a snapshot like this from a Firebase google cloud function?

exports.getFreshData = functions.https.onCall(async (data, context) => {
  const ref = data.ref;
  try {
    const snap = await admin.database().ref(ref).once("value");
    return {res: true, snapshot: snap};
  } catch (e) {
    error(e);
    return false;
  }
});

When I call this function from my client I get the following error:

Unhandled error RangeError: Maximum call stack size exceeded
    at keys (/workspace/node_modules/lodash/lodash.js:13333:60)
    at /workspace/node_modules/lodash/lodash.js:4920:21
    at baseForOwn (/workspace/node_modules/lodash/lodash.js:2990:24)
    at Function.mapValues (/workspace/node_modules/lodash/lodash.js:13426:7)
    at encode (/workspace/node_modules/firebase-functions/lib/providers/https.js:184:18)
    at /workspace/node_modules/lodash/lodash.js:13427:38
    at /workspace/node_modules/lodash/lodash.js:4925:15
    at baseForOwn (/workspace/node_modules/lodash/lodash.js:2990:24)
    at Function.mapValues (/workspace/node_modules/lodash/lodash.js:13426:7)
    at encode (/workspace/node_modules/firebase-functions/lib/providers/https.js:184:18) 

However, if I return snap.val() instead, it runs just fine. I want to be able to return the Snapshot though. Is it possible?

CodePudding user response:

Callable Cloud Functions can only return JSON types, as mentioned in the documentation on returning a value:

To send data back to the client, return data that can be JSON encoded.

A DatabaseSnapshot is not a JSON type, but a more complex JavaScript object. You'll typically want to either return the value of the snapshot, or its key and its value:

return { res: true, key: snap.key, value: snap.val() };
  • Related