UNPKG

serverless-api-gateway-throttling

Version:

A plugin for the Serverless framework which configures throttling for API Gateway endpoints.

89 lines (76 loc) 2.51 kB
'use strict'; const get = require('lodash.get'); const REST_API_ID_KEY = 'RestApiIdForApigThrottling'; const getConfiguredRestApiId = (serverless) => { return get(serverless, 'service.provider.apiGateway.restApiId') } const restApiExists = async (serverless, settings) => { if (get(settings, 'restApiId')) { return true; } const configuredRestApiId = getConfiguredRestApiId(serverless); if (configuredRestApiId) { return true; } if (serverless.service.provider.compiledCloudFormationTemplate) { const resource = serverless.service.provider.compiledCloudFormationTemplate.Resources['ApiGatewayRestApi']; if (resource) { return true; } } if (settings) { const restApiIdFromAlreadyDeployedStack = await retrieveRestApiId(serverless, settings); if (restApiIdFromAlreadyDeployedStack) { return true; } } return false; } const outputRestApiIdTo = (serverless) => { const configuredRestApiId = getConfiguredRestApiId(serverless); const autoGeneratedRestApiId = { Ref: 'ApiGatewayRestApi' }; serverless.service.provider.compiledCloudFormationTemplate.Outputs[REST_API_ID_KEY] = { Description: 'REST API ID', Value: configuredRestApiId || autoGeneratedRestApiId, }; }; const getAlreadyDeployedStack = async (serverless, settings) => { const stackName = serverless.providers.aws.naming.getStackName(settings.stage); try { const stack = await serverless.providers.aws.request('CloudFormation', 'describeStacks', { StackName: stackName }, settings.stage, settings.region ); return stack; } catch (error) { serverless.cli.log(`[serverless-api-gateway-throttling] Could not retrieve stack because: ${error.message}.`); return; } } const retrieveRestApiId = async (serverless, settings) => { if (settings.restApiId) { return settings.restApiId; } const configuredRestApiId = getConfiguredRestApiId(serverless); if (configuredRestApiId) { return configuredRestApiId; } const stack = await getAlreadyDeployedStack(serverless, settings); if(!stack){ return; } const outputs = stack.Stacks[0].Outputs; const restApiKey = outputs.find(({ OutputKey }) => OutputKey === REST_API_ID_KEY) if (restApiKey) { return restApiKey.OutputValue; } else { serverless.cli.log(`[serverless-api-gateway-throttling] Could not find stack output variable named ${REST_API_ID_KEY}.`); } }; module.exports = { restApiExists, outputRestApiIdTo, retrieveRestApiId };