0

I would like to create an application in Swift in which the user will be able to temporarily change their data on a Firestore document, and then at the end of 24 hours it will return as before. For example in a "Name" document, the name "Michael" is present; the user of his choice wants to change it to "Andrew" and can do it, but after 24 hours he must return to "Michael". How can I do?

mickele29
  • 19
  • 3

1 Answers1

1

Suppose the docs the user is changing are in a collection called MyDocs, a reasonable design for this would work as follows:

  1. Create a second collection, like MyDocsToRestore, that will maintain copies of the docs the user changes.
  2. Place an update trigger on MyDocs that saves the old doc data along with a restoreAt date when it should be restored.
exports.updateMyDocs = functions.firestore
    .document('MyDocs/{docId}')
    .onUpdate(async (change, context) => {
      // if we've got a backup, just change the restoreAt time
      const ref = doc(db, 'MyDocsToRestore', context.params.docId);
      const doc = await ref.get();
      const data = doc.exists ?  doc.data() : change.before.data();

      data.restoreAt = new Date();
      data.restoreAt.setDate(data.restoreAt.getDate() + 1);
      
      // save a copy in MyDocsToRestore
      await setDoc(ref, data);
    });
  1. Create a scheduled function that awakes every so often and looks for docs who's restoreAt dates have passed. ("every so often" means as infrequently as possible, but with acceptable precision relative to 24 hour expiration). Like this...
exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun(async (context) => {

  const q = query(collection(db, "MyDocsToRestore"), where("restoreAt", "<=", new Date()));

  const querySnapshot = await getDocs(q);
  const promises = querySnapshot.docs.map(doc => {
    const data = doc.data();
    delete data.restoreAt;
    return update(doc(db, 'MyDocs', doc.id), data);
  });
  return Promise.all(promises);
});
danh
  • 62,181
  • 10
  • 95
  • 136
  • where should i add this code? it's not swift or am I wrong? – mickele29 Aug 21 '22 at 18:29
  • It's javascript, which is what's used to write cloud functions. The backup collection is conveniently placed in the cloud, so you don't have to touch all of the places in the client code where the user might make an update. The scheduled function must be placed in the cloud, because there's no guarantee that any client will be running 24 hours from now. https://firebase.google.com/products/functions?gclid=Cj0KCQjwr4eYBhDrARIsANPywCjaHAEAYsGEqER96njjRVifiLuXJ-iHUHWWhrjE5PdfiLcF1t0PwnIaAliWEALw_wcB&gclsrc=aw.ds – danh Aug 21 '22 at 18:33