firestore-backup-restore icon indicating copy to clipboard operation
firestore-backup-restore copied to clipboard

Correct usage of restore when date is within array of objects

Open evallgar opened this issue 4 years ago • 2 comments

Hi there!

I would like to ask how to correctly use restore for date timestamp when data looks like this:

 "wFLrjgdW7Jjmjs5sX": {
  "_id": "wFLrjgdW7Jjmjs5sX",
  "notifications": [
    {
      "date": {
        "_seconds": 1589998976,
        "_nanoseconds": 490000000
      },
      "type": "new",
      "message": "Contract has been created.",
      "user": "Philip Rawsen"
    },
    {
      "date": {
        "_seconds": 1589999521,
        "_nanoseconds": 985000000
      },
      "type": "payment",
      "message": "Customer payment for USD $ 67.92",
      "user": "Lena Perks"
    }
  ]
}

When I use the command

// Start exporting your data
firestoreService
  .restore(`./collections/${collectionName}.json`, {
    dates: ['notifications.date']
  });

I cannot get it to restore it as a timestamp. It restores as a map field. I have also tried with 'notifications[].date' and simply 'date' unsuccessfully.

Any help is greatly appreciated. Thanks.

evallgar avatar May 25 '20 18:05 evallgar

Hi @evallgar, an object of data under array is not supported yet. I will figure a solution to solve this. You can check the code and make some changes to support this case if you want to contribute.

dalenguyen avatar May 26 '20 04:05 dalenguyen

If you put this in helper.ts

const applyConversion = (data: any, conversion: Function, key: Array<string>) => {
  if (!key || key.length === 0) return;

  if (Array.isArray(data)) {
    data.forEach(d => applyConversion(d, conversion, key));
    return;
  }

  if (!data.hasOwnProperty(key[0])) return;

  if (key.length === 1) {
    const theKey: string = key[0];
    const checkResult = conversion(data[theKey]);
    if (checkResult) data[theKey] = checkResult;
  } else if (isObject(data)) {
    applyConversion(data[key[0]], conversion, key.splice(1));
  }
}

//gives the properties of data, specified by keys, to conversion; keeps old value of conversion returns null, else replaces value with return value of conversion
export const convertProperty = (data: any, conversion: Function, keys: Array<string>) => {
  keys.forEach((key: string) => {
    applyConversion(data, conversion, key.split('.'));
  });
}

and replace the relevant part (line 132) in import.ts with

// Update date value
if (options.dates && options.dates.length > 0) {
  convertProperty(data, makeTime, options.dates)
}

(similarly for refs and and geos), that should do the trick. I've tested it only with one set of data though.

In the above example you'd use 'notifcations.date' to get the desired result; the layer of the array in the JSON tree basically gets skipped.

Parranoh avatar Jul 29 '20 20:07 Parranoh