【问题标题】:How to maintain state with Cloud Functions and Cloud FIrestore如何使用 Cloud Functions 和 Cloud FIrestore 维护状态
【发布时间】:2018-11-21 06:59:56
【问题描述】:

在使用 Cloud Functions 时如何保持正确的状态?它们不能保证按照调用它们的顺序触发。

这是一系列事件:

  1. 文档已更新currentState: state1
  2. 文档已更新currentState: state2
  3. Cloud Function 触发 state2 更新。
  4. Cloud Function 触发 state1 更新。

如果您的应用程序需要以正确的状态顺序执行功能,那就有问题了。

【问题讨论】:

    标签: firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    云函数不保证按顺序触发或仅触发一次。因此,您必须使它们具有幂等性。

    您可以通过以下方式解决此问题:

    1. 始终使用事务来更新状态,以免 2 个客户端同时尝试更改状态。
    2. 创建一个状态表,用于管理状态并根据当前状态与先前状态运行函数。
    3. 客户端不得将状态更改为小于当前存在的值。

    states.json

    [
      {"currentState": "state1", "action": "state2", "newStates": ["state2"]},
      {"currentState": "state1", "action": "state3", "newStates": ["state2", "state3"]},
      {"currentState": "state1", "action": "state4", "newStates": ["state2", "state3", "state4"]},
      {"currentState": "state1", "action": "state5", "newStates": ["state2", "state3", "state4", "state5"]},
      {"currentState": "state2", "action": "state3", "newStates": ["state3"]},
      {"currentState": "state2", "action": "state4", "newStates": ["state3", "state4"]},
      {"currentState": "state2", "action": "state5", "newStates": ["state3", "state4", "state5"]},
      {"currentState": "state3", "action": "state4", "newStates": ["state4"]},
      {"currentState": "state3", "action": "state5", "newStates": ["state4", "state5"]},
      {"currentState": "state4", "action": "state5", "newStates": ["state5"]}
    ]
    

    app.js

    function processStates (beforeState, afterState) {
      const states = require('../states');
      let newStates;
    
      // Check the states and set the new state
      try {
        newStates = states.filter(function(e) {return e.currentState == beforeState && e.action == afterState;})[0].newStates;
      }
      catch (err) {
        newStates = null;
      }
    
      console.log(`newStates: ${newStates}`);
    
      if (newStates) {
        newStates.forEach(newState) {
          // Process state change here
          switch (newState) {
            case 'state1': {
              // Process state1 change
              break;
            }
            case 'state2': {
              // Process state2 change
              break;
            }
            default: {
            }
          }
        }
      }
    }
    

    一旦你有了一个状态数组,你就可以通过使用类似forEachmap 的东西来处理所需的命令。

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 2018-03-23
      • 2018-03-27
      • 2021-03-29
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多