在Firebase Cloud函数中获取无限循环

时间:2018-11-27 12:32:23

标签: node.js firebase google-cloud-firestore google-cloud-functions

我正在使用Firestore将数据存储在Firebase中。为了获得计数,我正在使用云功能。当我尝试添加/更新/删除一个集合中的条目时,它将与另一个集合开始无限循环。 例: 添加/更新/删除用户时,我有一个用户表和代理表,应该在代理表中对其进行更新。

尽管我已经为用户和代理使用了单独的功能,但我仍然遇到无限循环。有人可以告诉我如何解决它

查询以更新用户和代理表中的用户:

 export const addUser = (values) =>
  db
    .collection('users')
    .add(values)
    .then((docRef) => {
      let customer = { customer: {} };
      customer.customer[docRef.id] = {
        id: docRef.id,
        name: values.name,
        commission: values.agent.commission
      };
      let agentId = values.agent.id;
      db.collection('agents')
        .doc(agentId)
        .set(customer, { merge: true });
    });

用户的云功能:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports = module.exports = functions.firestore
  .document("users/{userUid}")
  .onWrite(
    (change, context) =>
      new Promise((resolve, reject) => {
        let dashboardId;
        getDashboardId();
      })
  );

  getDashboardId = () => {
    admin.firestore().collection('dashboard').get().then((snapshot) => {
      if (snapshot.size < 1) {
        dashboardId = admin.firestore().collection('dashboard').doc().id;
      } else {
        snapshot.docs.forEach((doc) => {
          dashboardId = doc.id;
        });
      }
      return updateUser(dashboardId);
    }).catch((error) => {
      console.log('error is', error);
    });
  }

  updateUser = (id) => {
    admin.firestore().collection('users').where('isDeleted', '==', false).get().then((snap) => {
      let usersData = {users: snap.size};
      return admin.firestore().collection('dashboard').doc(id).set(usersData, {merge: true});
    }).catch((error) => {
      console.log('error is', error);
    });
  }

代理的云功能:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

exports = module.exports = functions.firestore
  .document("agents/{agentUid}")
  .onWrite(
    (change, context) =>
      new Promise((resolve, reject) => {
        let dashboardId;
        getDashboardId();
      })
  );

  getDashboardId = () => {
    admin.firestore().collection('dashboard').get().then((snapshot) => {
      if (snapshot.size < 1) {
        dashboardId = admin.firestore().collection('dashboard').doc().id;
      } else {
        snapshot.docs.forEach((doc) => {
          dashboardId = doc.id;
        });
      }
      return updateAgent(dashboardId);
    }).catch((error) => {
      console.log('error is', error);
    });
  }

  updateAgent = (id) => {
    admin.firestore().collection('agents').where('isDeleted', '==', false).get().then((snap) => {
      let agentsData = {agents: snap.size};
      return admin.firestore().collection('dashboard').doc(id).set(agentsData, {merge: true});
    }).catch((error) => {
      console.log('error is', error);
    });
  }

0 个答案:

没有答案