jon
jon

Reputation: 3600

Returning a map in Firebase cloud function is null

I am trying to return a set of values in a Firebase cloud onCall function, but when I read the value in my Android app, part of the data is missing.

Here is the cloud function:

exports.getPhotoUrls = functions.https.onCall(async (data, context) => {

  let usersAndPhotos = new Map();
  usersAndPhotos.set("bob", "2345");
  usersAndPhotos.set("sam", "345");

  const returnVal = {
    payload: usersAndPhotos,
    status: 200,
    message: "Success"
  }
  console.log("ReturnVal: " );
  console.log(returnVal)

  return returnVal
})

When I check in the Firebase functions log, I see that the returned value is:

{ payload: Map { 'bob' => '2345', 'sam' => '345' },
  status: 200,
  message: 'Success' }

However, when the function returns to my Android app, the payload Map is missing:

enter image description here

Why is my payload Map data disappearing?

Upvotes: 3

Views: 561

Answers (2)

jon
jon

Reputation: 3600

In addition to Doug's answer, which identified the source of the problem, I was able to make the solution more dynamic with this code:

let usersAndPhotos: { Name: string; ID: string; }[] = []
usersAndPhotos.push({Name: "bob", ID: "2345"});
usersAndPhotos.push({Name: "sam", ID: "345"});

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317477

This Map right here:

let usersAndPhotos = new Map();

is an ES6 Map type object. It can't be effectively serialized by Cloud Functions callables. If you want to send a map back to the client, what you should use instead is use a plain old JavaScript object, which has a clear and direct serialization to JSON (which is what's being used as the actual payload):

let usersAndPhotos = {
  bob: "2345",
  sam: "345"
}

Upvotes: 3

Related Questions