多对多关系交易

时间:2021-03-21 05:21:20

标签: dart google-cloud-firestore

我正在将 Firestore 与 Flutter 和 dart 结合使用。在我的数据库中,我有以下内容:

  1. userA 喜欢 userB
  2. userB 匹配 userA
  3. userA 和 userB 现在匹配,可以开始互相聊天了。

我有两个集合:用户&&关系

我为“喜欢”和“匹配”写了一个交易。

我们不要以“喜欢”为例。当用户 A 喜欢用户 B 时,必须将两个文档放入关系集合中

document1 将如下所示:

{
  "createdAt": Timestamp.fromDate(now),
  "status": 'liked',
  "pid": "id of user2"
  "pName": "name of user2",
  "pImage": "image of user2",
  "unseen": 1,
}

document2 将如下所示:

{
  "createdAt": Timestamp.fromDate(now),
  "status": 'likedby',
  "pid": "id of user1"
  "pName": "name of user1",
  "pImage": "image of user1",
  "unseen": 1,
}

“like”操作的代码如下所示:

  Future<void> createLike({required String pid}) async {
    await _firestore.runTransaction(
      (transaction) async {
        // Make sure that both profiles exist
        final myProfileSnapshot =
            await transaction.get(_firestore.doc(PathService.user(uid)));
        final otherProfileSnapshot =
            await transaction.get(_firestore.doc(PathService.user(pid)));

        if (!myProfileSnapshot.exists || !otherProfileSnapshot.exists) {
          throw Exception('Profile does not exist');
        }

        // Make sure previous relationship does not exist between profiles
        final myRelationship = await transaction
            .get(_firestore.doc(PathService.relationship(uid, pid)));
        final otherRelationship = await transaction
            .get(_firestore.doc(PathService.relationship(pid, uid)));

        if (myRelationship.exists || otherRelationship.exists) {
          throw Exception("Previous relationship exists");
        }

        Map<String, dynamic> myProfile = myProfileSnapshot.data()!;
        Map<String, dynamic> otherProfile = otherProfileSnapshot.data()!;

        final myImages = List<Map<String, dynamic>>.from(myProfile['images']);
        final otherImages =
            List<Map<String, dynamic>>.from(otherProfile['images']);
        final myImage = myImages[0]['url'];
        final otherImage = otherImages[0]['url'];
        final now = DateTime.now();

        // Perform an update on the documents
        transaction.set(myRelationship.reference, {
          'createdAt': Timestamp.fromDate(now),
          'status': 'liked',
          'pid': otherProfile['id'],
          'pName': otherProfile['name'],
          'pImage': otherImage,
          'unseen': 1,
        });

        transaction.set(otherRelationship.reference, {
          'createdAt': Timestamp.fromDate(now),
          'status': 'likedby',
          'pid': myProfile['id'],
          'pName': myProfile['name'],
          'pImage': myImage,
          'unseen': 1,
        });
      },
    );
  }

代码可以正常工作,没有任何问题。问题是它太慢了。
我的问题是我可以做些什么来加快速度吗?

0 个答案:

没有答案
相关问题