我正在客户端构建一个具有高级延迟加载功能的评论系统,如下所示:
comment 1
|
[load more]
|
comment 7
|
comment 8
|
[load more]
|
comment 10为此,我需要根据comments文档的创建时间对它们进行编号(以便知道在两个注释之间是否有更多的注释要加载)。
事情是这样的,因为云函数触发器是异步的,所以我没有真正的方法来根据创建时间来索引传入的文档。
例如,一个文档在另一个文档创建几毫秒之后,可能会更早地触发云函数,从而导致索引错误。
我现在能想到的唯一解决方案是,对于每个传入的comment,运行一个查询集合中时间戳小于此时间戳的comments的数量,并将其用作索引。但就性价比而言,这显然不是真正可行的。
您将如何处理此问题?:)
发布于 2019-10-21 22:12:39
在函数本身中指定注释的创建时间戳,而不是在客户端。然后,您仍然可以获得基于时间的排序,而不必要求客户端立即同步文档写入。
发布于 2019-10-21 23:56:39
多亏了Doug的建议,在云函数中分配时间戳之前先分配索引,以确保索引顺序,我提出了以下代码:
const { post_id, text } = data;
return db.runTransaction(async transaction => {
const postDocRef = db.collection('posts').doc(post_id);
const postComDocRef = postDocRef.collection('comments').doc();
const postDoc = await transaction.get(postDocRef);
if (!postDoc.exists)
throw new functions.https.HttpsError(
'not-found',
`Post ${post_id} not found.`
);
try {
const comments_count = postDoc.data()!.comments_count;
transaction.update(postDocRef, {
comments_count: comments_count + 1
});
transaction.create(postComDocRef, {
author: context.auth!.uid,
text,
index: comments_count,
created_at: admin.firestore.Timestamp.now()
});
} catch (e) {
throw new functions.https.HttpsError('internal', `Transaction failed.`);
}
});它使用一个事务来获取已经做出的评论的当前计数的原子值,然后在分配相应的时间戳之前使用该值作为评论索引
https://stackoverflow.com/questions/58486303
复制相似问题