问题
I tried to upgrade one of my lambda but can't make it work... so I have a lambda to manage my stripe payment, everything work fine.
I want to send a message to SQS when a payment is OK.
You can see my lambda function below :
const stripe = require('stripe')("sk_test_xXxXxXxXxX");
const ApiBuilder = require('claudia-api-builder');
const querystring = require('querystring');
var api = new ApiBuilder();
var AWS = require('aws-sdk');
var sqs = new AWS.SQS({region : 'eu-west-1'});
var queueUrl = 'https://sqs.eu-west-1.amazonaws.com/xXXxXXxXXx/xXxXxX-new-site.fifo';
api.post('/stripe',request => {
console.log(request);
let params = querystring.parse(request.body);
console.log(params);
return stripe.charges.create({
amount: params.package,
currency: 'eur',
description: `12 month charge`,
source: params.stripeToken,
receipt_email: params.email,
metadata: {domain_name: params.domain_name, email: params.email},
}).then(charge => {
var responseBody = {
message: ''
};
var responseCode = 200;
var message = {
MessageBody: "TEST",
QueueUrl: queueUrl
};
console.log(message);
sqs.sendMessage(message, function(err, data) {
console.log(err);
console.log(data);
if (err) {
console.log('error:', "failed to send message" + err);
var responseCode = 500;
} else {
console.log('data:', data.MessageId);
responseBody.message = 'Sent to ' + queueUrl;
responseBody.messageId = data.MessageId;
}
var response = {
statusCode: responseCode,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(responseBody)
};
return response;
});
return charge;
}).catch((err) => {
return err;
});
});
module.exports = api;
I added the code betweend line 25 and 59.
On cloudwatch logs I can see the console output from line 36 ( console.log(message);) but nothing from the line 39.
Thanks for helping :)
回答1:
I'm not so experienced in AWS Lambda, but I see that you execute async code with callback (sqs.sendMessage()) and immediately call return charge
without awaiting of result of such execution (sqs.sendMessage())
I'm not pretty sure about what Lambda should return (probably, response
, not charge
), but if you want to see your console.log
results inside sqs.sendMessage()
call, the code might look something like this:
// above code ommitted
}).then(async charge => {
//code ommitted
console.log(message);
// if Lambda supports async/await OR return this promise and process it in next chain
await sqs.sendMessage(message)
.promise()
.then(data=>{
// process data here
})
.catch(err=>{
// process error here
})
return charge;
}).catch((err) => {
return err;
});
});
来源:https://stackoverflow.com/questions/51642942/lambda-send-a-message-to-sqs