You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过IAM权限从AWS Lambda调用AWS AppSync执行查询/变更(适配最新SDK)

适配最新AWS SDK的Lambda调用AppSync(IAM授权)可运行代码

前置准备

  • 安装所需依赖:
    npm install @aws-sdk/credential-provider-node aws-appsync graphql graphql-tag cross-fetch
    
  • Lambda执行角色需配置如下权限,替换<APPSYNC_API_ARN>为你的AppSync API实际ARN:
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "appsync:GraphQL",
          "Resource": "<APPSYNC_API_ARN>/*"
        }
      ]
    }
    
  • AppSync对应Schema的操作需开启IAM授权,对应字段添加@aws_iam指令
  • Lambda配置环境变量APPSYNC_ENDPOINT为你的AppSync API端点

完整可运行代码

const { defaultProvider } = require('@aws-sdk/credential-provider-node');
const { AUTH_TYPE, AWSAppSyncClient } = require('aws-appsync');
const gql = require('graphql-tag');
// Node.js 18.x及以上运行时自带fetch,可删除下一行导入
require('cross-fetch/polyfill');

// AppSync客户端配置
const client = new AWSAppSyncClient({
  url: process.env.APPSYNC_ENDPOINT,
  region: process.env.AWS_REGION,
  auth: {
    type: AUTH_TYPE.AWS_IAM,
    credentials: defaultProvider(),
  },
  disableOffline: true
});

// 定义mutation,可替换为你自己的query/mutation语句
const createLogMutation = gql`
  mutation createLog($input: CreateLogInput!) {
    createLog(input: $input) {
      id
      event
      detail
    }
  }
`;

// Lambda异步Handler,无需callback
exports.handler = async (event) => {
  // 解析SNS消息,注意SNS的Message为字符串需先反序列化
  const payload = JSON.parse(event.Records[0].Sns.Message);
  
  if (!payload.event) {
    throw new Error("event must be provided in the message body");
  }

  const logDetails = {
    event: payload.event,
    detail: payload.detail
  };

  try {
    const result = await client.mutate({
      mutation: createLogMutation,
      variables: { input: logDetails }
    });
    console.log('Mutation执行成功:', result.data);
    return result.data;
  } catch (e) {
    console.error('Mutation执行失败:', e);
    throw new Error(e);
  }
};

注意事项

  • 如果是执行查询操作,将client.mutate替换为client.query,同时传入query参数即可
  • 打包部署时请确保所有依赖都被包含在部署包中,避免运行时找不到模块的错误

内容的提问来源于stack exchange,提问作者Arman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:45:03