serverless-api-gateway-throttling
Version:
A plugin for the Serverless framework which configures throttling for API Gateway endpoints.
94 lines (80 loc) • 2.77 kB
JavaScript
const get = require('lodash.get');
const HTTP_API_ID_KEY = 'HttpApiIdForApigThrottling';
const getConfiguredHttpApiId = (serverless) => {
return get(serverless, 'service.provider.httpApi.id')
}
const httpApiExists = async (serverless, settings) => {
const configuredHttpApiId = getConfiguredHttpApiId(serverless);
if (configuredHttpApiId) {
return true;
}
if (httpApiExistsInCloudFormationTemplate(serverless)) {
return true;
}
if (settings) {
const httpApiIdFromAlreadyDeployedStack = await retrieveHttpApiIdFromAlreadyDeployedStack(serverless, settings);
if (httpApiIdFromAlreadyDeployedStack) {
return true;
}
}
return false;
}
const retrieveHttpApiId = async (serverless, settings) => {
const configuredHttpApiId = getConfiguredHttpApiId(serverless);
if (configuredHttpApiId) {
return configuredHttpApiId;
}
const httpApiId = await retrieveHttpApiIdFromAlreadyDeployedStack(serverless, settings);
if (!httpApiId) {
serverless.cli.log(`[serverless-api-gateway-throttling] Could not find stack output variable named ${HTTP_API_ID_KEY}.`);
}
return httpApiId;
};
const outputHttpApiIdTo = (serverless, settings) => {
const configuredHttpApiId = getConfiguredHttpApiId(serverless);
const autoGeneratedHttpApiId = { Ref: 'HttpApi' };
serverless.service.provider.compiledCloudFormationTemplate.Outputs[HTTP_API_ID_KEY] = {
Description: 'HTTP API ID',
Value: configuredHttpApiId || autoGeneratedHttpApiId,
};
};
const httpApiExistsInCloudFormationTemplate = (serverless) => {
if (serverless.service.provider.compiledCloudFormationTemplate) {
const resource = serverless.service.provider.compiledCloudFormationTemplate.Resources['HttpApi'];
if (resource) {
return true;
}
}
return false;
}
const retrieveHttpApiIdFromAlreadyDeployedStack = async (serverless, settings) => {
const stack = await getAlreadyDeployedStack(serverless, settings);
if (!stack) {
return;
}
const outputs = stack.Stacks[0].Outputs;
const HttpApiKey = outputs.find(({ OutputKey }) => OutputKey === HTTP_API_ID_KEY)
if (HttpApiKey) {
return HttpApiKey.OutputValue;
}
}
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;
}
}
module.exports = {
httpApiExists,
outputHttpApiIdTo,
retrieveHttpApiId
};
;