如何使用无服务器框架将来自 AWS Lambda 的查询请求发送到 AppSync GraphQL API?

How to send query request from AWS Lambda with Serverless Framework to AppSync GraphQL API?

我一直在理解如何以最简单的方式通过使用 AWS Lambda 将查询请求发送到某个 AppSync GraphQL API(具有 API KEY 授权模式)。

我是初学者,因此我阅读了很多书,寻找可能解释这一点的有用提示和教程,我最接近解决方案的是本教程:https://docs.aws.amazon.com/appsync/latest/devguide/building-a-client-app-node.html ,这建议使用 Apollo Client。 我的第一个问题是,这是实现我目标的最佳方法吗(使用 Apollo Client + AWS Lambda 向 AppSync GraphQL API 发送查询和变更)?如果没有,最好的做法是什么 practice/way?

这是我基于上述教程的当前代码:

const gql  = require('graphql-tag');
const AWSAppSyncClient = require('aws-appsync').default;
const AUTH_TYPE = require('aws-appsync-auth-link/lib/auth-link').AUTH_TYPE;
require('es6-promise').polyfill();
require('isomorphic-fetch');


module.exports.handler =  async function(event, context) {

    //console.log("before_client_setup");

    const client = new AWSAppSyncClient({
      url: '******',
      region: '******',
      auth: {
        type: AUTH_TYPE.API_KEY,
        apiKey:'******'
      },
      disableOffline: true
    });

    //console.log("before_gql_query");

    const query = gql`
      query listJobs {
        listJobs{
          items {
            id title employer datePosted location url
          }
        }
      }
    `;

   //console.log("before_client_call");

    client.hydrated().then(function (client) {
      //Now run a query

      //console.log("before_client_query");

        client.query({ query: query, fetchPolicy: 'network-only' })   //Uncomment for AWS Lambda
          .then(function logData(data) {
              console.log('results of query: ', data);
          })
          .catch(console.error);
    });
}

url, region, auth 参数是硬编码的,只是为了测试它是否有效(我知道这不是最佳实践),但是当我调用这个函数通过无服务器框架使用命令:sls invoke -f streamFunction --stage stg 我在控制台中得到的结果是:

预期结果(我在使用 Postman 并传递正确的 url 和 api 键时得到的结果): https://i.stack.imgur.com/gAfRL.png

CloudWatch Logs 也没有任何帮助,因为它们没有提供有关问题可能的有用见解。这是它们被调用时的屏幕截图:

https://i.stack.imgur.com/WKXsP.png

有什么建议吗?

好的,所以我认为主要问题是因为我使用了这种语法:

client.hydrated().then(function (client) {

      client.query({ query: query, fetchPolicy: 'network-only' })   //Uncomment for AWS Lambda
      .then(function logData(data) {
          console.log('results of query: ', data);
      })
      .catch(console.error);
});

在我的 lambda 异步函数内部。相反,应该使用 await 关键字。这是解决问题的完整代码:

const gql = require('graphql-tag');
const AWSAppSyncClient = require('aws-appsync').default;
const AUTH_TYPE = require('aws-appsync-auth-link/lib/auth-link').AUTH_TYPE;
require('es6-promise').polyfill();
require('isomorphic-fetch');
module.exports.handler = async function (event, context) {
  try {
    const appSyncClient = new AWSAppSyncClient(
      {
        url: '******',
        region: '******',
        auth: {
          type: AUTH_TYPE.API_KEY,
          apiKey: '******'
        },
        disableOffline: true
      },
      {
        defaultOptions: {
          query: {
            fetchPolicy: 'network-only',
            errorPolicy: 'all',
          },
        },
      }
    );  
    const query = await gql`
      query listJobs {
        listJobs{
          items {
            id title employer datePosted location url
          }
        }
      }
    `;
    const client = await appSyncClient.hydrated();
    const data =   await client.query({query});
    console.log(data);

  } catch (error) {
    return context.fail(error);
  }
  return context.succeed("success");
}

这里是来自 CloudWatch 的日志: https://i.stack.imgur.com/O6AcB.png

希望这对您有所帮助:)