示例编写程序4 如何利用函数对全局继承变量进行赋值和使用

在函数编写的过程中可以通过全局变量来维护在整个对话流程中需要用到的数据,共分为变量定义,变量赋值,变量引用三个过程,在对话的任意节点可对变量进行引用变量定义:

全局变量在函数中对全局变量进行修改:此示例说明了如何为全局变量赋值并在后续的节点中引用,其中eventObj.global[“transedOrderId”]中引用的变量为在对话中创建的全局变量,函数开始时,通过slots=eventObj.slotSummary,获取图中的所有槽位节点,在下一步是判断,如果“选择订单意图.order_id”有值,则将此值赋值组全局变量,并在后续需要用到的节点可以引用。

module.exports.handler = function(event, context, callback) { 
  var eventResult = "";
  try {
      var eventObj = JSON.parse(event.toString());

      // add your code here
      /**
      * code block
      **/
      //console.info(null, eventObj.toString());
      var slots = eventObj.slotSummary;
      var slotValue = slots["选择订单意图.order_id"]||'';
      console.info(null, "slotValue:" + slotValue);
      if (slotValue && slotValue !==''){
        eventObj.global["transedOrderId"] = slotValue; //此处对全局变量进行赋值
      } else {
        eventObj.global["transedOrderId"] = eventObj.environment["orderId"];
      }
      console.log(eventObj.global["transedOrderId"]);
      eventResult = JSON.stringify(eventObj);
      callback(null, eventResult);
  } catch (e) {
      console.error(null, e);
      callback(null, e);
  }
};

Python

# -*- coding: utf-8 -*-
import logging
import json


def handler(event, context):
    logger = logging.getLogger()
    logger.info(event)
    eventObj = json.loads(event)

    slots = eventObj["slotSummary"]
    logger.info(slots)
    slotValue = slots["选择订单意图.orderId"]

    if  slotValue is not None:
        eventObj["global"]["transedOrderId"] = slotValue;
    else:
        eventObj["global"]["transedOrderId"] = eventObj["environment"]["orderId"];

    return eventObj

JAVA

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;

/**
 * Created by weili on 2018/8/2.
 *
 * @author weili
 * @date 2018/08/02
 */
public class FunctionHandler implements PojoRequestHandler<JSONObject, JSONObject> {
    @Override
    public JSONObject handleRequest(JSONObject eventObj, Context context) {

        /**
         *  eventObj structure definition
         *
         *  read-only variables
         *  "environment": "Object",
         *  "lastOutputForFunction": "String",
         *  "slotSummary": "Object",
         *
         *  read/write variables
         *  "global": "Object",
         *  "overrideResponse": "Object",
         *  "functionOutput": "String",
         *  "routeVariable": "String"
         */

        JSONObject slots = eventObj.getJSONObject("slotSummary");
        String slotValue = slots.getString("选择订单意图.order_id");
        if (null != slotValue && !"".equals(slotValue)) {
            eventObj.getJSONObject("global").get("transedOrderId") = slotValue;
        } else {
            eventObj.getJSONObject("global").get("transedOrderId") = eventObj.getJSONObject("environment").getString("orderId");
        }

        return eventObj;
    }
}

全局变量引用:

全局变量的引用