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

如何通过@aws-cdk/aws-apigatewayv2为AWS WebSocket API添加集成响应

AWS CDK WebSocket API 集成响应配置方案

你遇到的核心问题是LambdaWebSocketIntegration属于CDK的高级抽象构造,没有直接暴露底层集成ID属性,可通过CDK的escape hatch机制获取对应底层CloudFormation资源来解决,完整代码示例如下:

import { WebSocketApi, WebSocketStage, LambdaWebSocketIntegration } from '@aws-cdk/aws-apigatewayv2-alpha';
import { CfnIntegrationResponse, CfnIntegration } from 'aws-cdk/aws-apigatewayv2';
import * as lambda from 'aws-cdk-lib/aws-lambda';

// 你的Lambda处理函数
const lambdaFn = new lambda.Function(this, 'Handler', {
  runtime: lambda.Runtime.NODEJS_18_X,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda'),
});

// 单独声明Lambda集成实例
const lambdaIntegration = new LambdaWebSocketIntegration({ 
  handler: lambdaFn 
});

const webSocketApi = new WebSocketApi(this, 'Api', {
  defaultRouteOptions: {
    integration: lambdaIntegration,
  },
});

// 获取默认路由绑定的底层CfnIntegration资源
const defaultRouteIntegration = webSocketApi.defaultRoute?.node.children.find(
  child => child instanceof CfnIntegration
) as CfnIntegration;

// 创建集成响应
new CfnIntegrationResponse(this, 'DefaultIntegrationResponse', {
  apiId: webSocketApi.apiId,
  integrationId: defaultRouteIntegration.ref, // CfnIntegration的ref属性就是integrationId
  integrationResponseKey: '$default',
  // 按需添加响应模板、参数映射等配置
  // responseTemplates: {
  //   "application/json": "$input.path('$')"
  // }
});

const stage = new WebSocketStage(this, 'Stage', {
  webSocketApi,
  stageName: 'dev',
  autoDeploy: true,
});

自定义路由场景的适配

如果你需要给非默认的自定义路由添加集成响应,只需要在定义路由后,用同样的方式从路由实例下找到CfnIntegration资源即可,示例如下:

// 自定义sendMessage路由
const sendMessageRoute = webSocketApi.addRoute('sendMessage', {
  integration: new LambdaWebSocketIntegration({ handler: sendMessageLambda }),
});

// 获取自定义路由的集成ID
const sendMsgIntegration = sendMessageRoute.node.children.find(
  child => child instanceof CfnIntegration
) as CfnIntegration;

// 给自定义路由创建集成响应
new CfnIntegrationResponse(this, 'SendMsgIntegrationResponse', {
  apiId: webSocketApi.apiId,
  integrationId: sendMsgIntegration.ref,
  integrationResponseKey: '$default',
});

内容的提问来源于stack exchange,提问作者Martin Šťáva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:57:04