Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't return a date from a firebase cloud function?

I'm trying to simply return a date from a firebase function:

import * as functions from 'firebase-functions';

const date = functions.https.onCall(() => {
  return {
    date: new Date(),
    iso: new Date().toISOString()
  };
});
export default date;

But here's the result I'm getting (using firebase functions:shell):

RESPONSE RECEIVED FROM FUNCTION: 200, {
  "result": {
    "date": {},
    "iso": "2018-12-08T18:00:20.794Z"
  }
}

Note that the Date() object is being serialized as an empty object which seems wrong? I would have expected at least a .toString() or something of the Date instance...

Does this mean I have to explicitly avoid returning Date instances? I can write a custom serializer which I wrap around my functions to deeply convert Date instances to strings via .toISODate() etc but that seems like I must be missing something!

THanks.

like image 230
Eric Avatar asked Dec 08 '18 18:12

Eric


1 Answers

If you have a date object d, you should either:

  1. Send its unix epoch time in milliseconds with d.getTime(), or
  2. Send it JSON serialized form with d.toJSON().

I suggest #1, as it's easier to interop with different systems. Every system understands dates in unix epoch time, and that number doesn't require parsing.

like image 120
Doug Stevenson Avatar answered Nov 12 '22 18:11

Doug Stevenson