代码之家  ›  专栏  ›  技术社区  ›  ProfDFrancis

单个AWS Lambda函数响应Alexa skill请求,并根据调用方式返回JSON对象

  •  0
  • ProfDFrancis  · 技术社区  · 6 年前

    我正在尝试使用相同的AWS Lambda函数对相同的DynamoDB数据集执行两个操作。

    我已经实现了这一点,并且技能操作正确。我正在使用NodeJS和Amazon技能工具包版本2。我的最后几行索引.js具体如下:

    const skillBuilder = Alexa.SkillBuilders.standard();
    exports.handler = skillBuilder
      .addRequestHandlers(
        LaunchRequest,
        HelpIntent,
        // .... various other intents
        UnhandledIntent
      )
      .addErrorHandlers(ErrorHandler)
      .lambda();
    

    (b) 提供一个JSON对象来总结一些数据库内容

    我的问题是,将这个JSON响应返回到我的请求的Lambda代码的结构如下 https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html :

     'use strict';
     console.log('Loading hello world function');
    
     exports.handler = function(event, context, callback) {
        let name = "you";
        let city = 'World';
        // etc ... more code ...
        callback(null, response);
     };
    

    这两段代码都为`导出.handler`

    我想我要达到这样的效果:

    if ( /* test whether being called by Alexa or by API Gateway */ )
      { /* Make the Alexa Response */ }
    else
      { /* Construct the JSON data summary response  */ }
    

    index_Alexa.js index_JSON.js .

    1 回复  |  直到 6 年前
        1
  •  1
  •   Michael - sqlbot    6 年前

    我对这种方法的有用性有些怀疑,下面还有一些优化的潜力,但实现这一点的一种方法是声明 exports.handler 作为一个简单的包装器,它根据您可以在请求中测试的条件调用之前声明的正确处理程序函数。

    // set up handler for alexa
    
    const skillBuilder = Alexa.SkillBuilders.standard();
    const alexa_handler = skillBuilder
      .addRequestHandlers(
        LaunchRequest,
        HelpIntent,
        // .... various other intents
        UnhandledIntent
      )
      .addErrorHandlers(ErrorHandler)
      .lambda();
    
    // set up handler for API Gateway
    
    const api_gateway_handler = function(event, context, callback) {
        let name = "you";
        let city = 'World';
        // etc ... more code ...
        callback(null, response);
     };
    
    // for each invocation, choose which of the above to invoke
    
    exports.handler = function(event, context, callback) {
        if(/* some test that is true only for API Gateway */)
        {
            api_gateway_handler(event, context, callback);
        }
        else
        {
            alexa_handler(event, context, callback);
        }
    };
    

    线路 if(/* some test that is true only for API Gateway */)

    if(event.input && event.input.requestContext && event.input.requestContext.apiId)
    

    API网关文档 suggest 这个值总是存在的。