Ad

Firebase Function Storing Datetime As Map

I have firebase functions setup to create a new event in the firestore db with the onCall method. I am passing data to the onCall method from my frontend vue app. The data that i want to set in the database contains a bunch of data, with it a few Dates that need to be saved. The dates are future date/times and once they get added to the firestore db, they show as type map instead of timestamp

My firebase-admin version is 8.0.0 and firebase-functions version is 3.0.0

This adds the data to the collection but the timestamp is now in the map type with nanoseconds and seconds. How can this be made to save in the Timestamp type??

Frontend js call to onCall:

let data = {
  firstName: 'John',
  lastName: 'Doe',
  startDate: myStartDate  // This is a JS date object - Fri Aug 30 2019 17:00:00 GMT-0500 (Central Daylight Time)
};
return db.httpsCallable('myFunction')({ myData: data });

Backend Google Function:

exports.myFunction= functions.https.onCall((data, context) => {
  const myData = data.myData;
  return admin
    .firestore()
    .collection('myCollection')
    .doc('myDocument')
    .collection('myAccount')
    .add({ ...myData  });
});
Ad

Answer

When you use a callable function, all the type information in the input object is going to be completely stripped of type information before it's sent to the function. It will be serialized as JSON, which is just objects, arrays, numbers, strings, booleans, and nulls. The timestamp will be serialized as seconds and nanos, because that's how it's represented internally.

If you want to send a timestamp to a callable function, your function should be prepared to receive seconds and nanos, and create a new Timestamp object with those values before passing them to the Firebase Admin SDK, which will interpret it correctly.

Ad
source: stackoverflow.com
Ad