UNPKG

@kumologica/builder

Version:
117 lines (97 loc) 3.04 kB
const codegen = require('../../build/codegen'); // api gw triggers function isNewApi(params) { return params && params.apiId && params.apiId === "create new"; } function getApiId(params) { return isNewApi(params)? {Ref: "ApiGW"}: params.apiId; } function websocketListenerNodeType(node) { return node && node.type && node.type === "EventListener" && node.provider === "aws" && node.eventSource === "websocket"; } function sanitizeName(n) { return codegen.sanitizeResourceName(n); } function trigger(params, flow) { let ws; if (flow) { ws = flow.filter(node => websocketListenerNodeType(node)); } let templateResources = {}; let dependsOn = []; if (isNewApi(params)) { templateResources.ApiGW = { Type: "AWS::ApiGatewayV2::Api", Properties: { Name: params.apiName || "websocket api", ProtocolType: "WEBSOCKET", RouteSelectionExpression: "$request.body.action", ApiKeySelectionExpression: "$request.header.x-api-key" } } templateResources.ApiGWStage = { Type: "AWS::ApiGatewayV2::Stage", Properties: { StageName: params.stage, ApiId: { Ref: "ApiGW" } } }; dependsOn.push("ApiGW"); dependsOn.push("ApiGWStage"); } // Note ${Lambda.Arn} - the flow lambda must have resource defined as Lambda templateResources.ApiGWPermission = { Type: "AWS::Lambda::Permission", DependsOn: 'Lambda', Properties: { FunctionName: { "Fn::GetAtt": [ "Lambda", "Arn" ] }, Action: "lambda:InvokeFunction", Principal: 'apigateway.amazonaws.com', SourceArn: { "Fn::Sub": "arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:" + (isNewApi(params)? "${ApiGW}": params.apiId) + "/*" } } }; ws.forEach(w => { const name = (w.websocketRoute === "custom"? sanitizeName(w.websocketCustom) :w.websocketRoute); templateResources["Route" + name] = { Type: "AWS::ApiGatewayV2::Route", Properties: { ApiId: getApiId(params), ApiKeyRequired: params.apiKeyRequired || false, RouteKey: w.websocketRoute === "custom"? w.websocketCustom: "$" + w.websocketRoute, Target: {"Fn::Join": ["/", ["integrations", {Ref: "Integration" + name}]]} } }; if (w.websocketRoute === "connect") { templateResources["Route" + name].Properties.AuthorizationType = params.authorizerType || "NONE"; templateResources["Route" + name].Properties.AuthorizerId = params.authorizerId; } dependsOn.push("Route" + name); templateResources["Integration" + name] = { Type: "AWS::ApiGatewayV2::Integration", Properties: { ApiId: getApiId(params), IntegrationType: "AWS_PROXY", IntegrationUri: { "Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Lambda.Arn}/invocations" } } } }); templateResources.Deployment = { Type: "AWS::ApiGatewayV2::Deployment", DependsOn: dependsOn, Properties: { ApiId: getApiId(params), StageName: params.stage } } return templateResources; } module.exports = { trigger }