[英]Automatically change a variable in Firestore after 24 hours - Swift
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.我想在 Swift 中创建一个应用程序,用户可以在其中临时更改他们在 Firestore 文档上的数据,然后在 24 小时结束时它会像以前一样返回。 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".
他选择的用户想要将其更改为“Andrew”并且可以做到,但 24 小时后他必须返回“Michael”。 How can I do?
我能怎么做?
Suppose the docs the user is changing are in a collection called MyDocs
, a reasonable design for this would work as follows:假设用户正在更改的文档位于名为
MyDocs
的集合中,对此的合理设计将按如下方式工作:
MyDocsToRestore
, that will maintain copies of the docs the user changes.MyDocsToRestore
,它将维护用户更改的文档的副本。restoreAt
date when it should be restored.restoreAt
日期。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);
});
restoreAt
dates have passed.restoreAt
日期已过的文档。 ("every so often" means as infrequently as possible, but with acceptable precision relative to 24 hour expiration). 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.