0
如何使用aws-sdk在現有的lambda函數上創建觸發器?如何使用aws-sdk在現有的lambda函數上創建API網關觸發器?
我想要一個代理集成類型的API網關端點作爲觸發器。
我正在使用nodejs和aws-sdk 2.39.0。
如何使用aws-sdk在現有的lambda函數上創建觸發器?如何使用aws-sdk在現有的lambda函數上創建API網關觸發器?
我想要一個代理集成類型的API網關端點作爲觸發器。
我正在使用nodejs和aws-sdk 2.39.0。
不優雅,但它的工作原理。
我很樂意接受修訂/更好的解決方案。我對AWS SDK非常陌生。
const createApi =() => {
sts.getCallerIdentity(function(err, data) {
if (err) {
console.log(err);
} else {
const accountId = data.Account;
const functionName = 'resize-images-on-' + settings.aws.bucket;
const apiName = 'resize-images-on-' + settings.aws.bucket + '-api';
const uri = 'arn:aws:apigateway:' + settings.aws.region + ':lambda:path/2015-03-31/functions/arn:aws:lambda:' + settings.aws.region + ':' + accountId + ':function:' + functionName + '/invocations';
var apiSwagger = {
"swagger": "2.0",
"info": {
"version": "2017-04-10T12:43:16Z",
"title": apiName
},
"basePath": "/prod",
"schemes": [
"https"
],
"paths": {
"/resize": {
"x-amazon-apigateway-any-method": {
"responses": {
"200": {
"description": "200 response"
}
},
"x-amazon-apigateway-integration": {
"responses": {
".*": {
"statusCode": "200"
}
},
"uri": uri,
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"type": "aws_proxy"
}
}
}
}
}
apiSwagger = JSON.stringify(apiSwagger);
const apiParams = {
body: apiSwagger,
};
apigateway.importRestApi(apiParams, function(err, data) {
if (err) {
console.log(err);
} else {
console.log('API created');
configureLambda(data.id, accountId);
}
});
}
});
}
const configureLambda = (apiId, accountId) => {
console.log('Configuring lambda ...');
const functionName = 'resize-images-on-' + settings.aws.bucket;
const lambdaPolicies = [
{
Action: "lambda:InvokeFunction",
FunctionName: functionName,
Principal: "apigateway.amazonaws.com",
StatementId: uuid(),
SourceArn: 'arn:aws:execute-api:' + settings.aws.region + ':' + accountId + ':' + apiId + '/prod/ANY/resize'
},
{
Action: "lambda:InvokeFunction",
FunctionName: functionName,
Principal: "apigateway.amazonaws.com",
StatementId: uuid(),
SourceArn: 'arn:aws:execute-api:' + settings.aws.region + ':' + accountId + ':' + apiId + '/*/*/resize'
}
];
lambda.addPermission(lambdaPolicies[0], function(err, data) {
if (err) {
console.log(err);
} else {
lambda.addPermission(lambdaPolicies[1], function(err, data) {
if (err) {
console.log(err);
} else {
console.log('Lambda configured');
}
});
}
});
}