代码之家  ›  专栏  ›  技术社区  ›  Jason Berryman

如何使用云功能和云FireStore维护状态

  •  2
  • Jason Berryman  · 技术社区  · 7 年前

    使用云功能时如何保持正确的状态?他们不能保证按他们被召唤的顺序开火。

    以下是一系列事件:

    1. 文档已更新 currentState: state1
    2. 文档已更新 currentState: state2
    3. cloud函数触发 state2 更新。
    4. cloud函数触发 state1 更新。

    如果您的应用程序要求以正确的状态顺序执行函数,则会出现问题。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Jason Berryman    7 年前

    云功能不能保证按顺序或只发射一次。因此,你必须使它们是等幂的。

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

    1. 始终使用事务更新状态,这样2个客户机就不会同时尝试更改状态。
    2. 创建一个状态表,用于管理状态,并基于当前状态与前一状态运行函数。
    3. 客户端不能将状态更改为小于当前存在值的值。

    状态.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"]}
    ]
    

    应用程序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: {
            }
          }
        }
      }
    }
    

    一旦您有了一个状态数组,您就可以使用 forEach map 处理所需的命令。