我希望根据发送到 AWS Lambda 的事件从外部静态 JSON 文件中提取一些数据。
因此,当有人发送他们的“customer_id”时,我们从外部 JSON 文件中提取匹配的“电子邮件”和“选项”
https://3objects.netlify.com/3objects.json
这是我到目前为止的代码?
const AWS = require('aws-sdk');
const ses = new AWS.SES();
const request = require('request');
exports.handler = (event) => {
console.log(event.customer_id);
request({
url: 'https://3objects.netlify.com/3objects.json',
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
})
}, function (error, response) {
if (!error && response.statusCode == 200) {
var jsonResponse = JSON.parse(body); // turn response into JSON
// do stuff with the response and pass it back to Lambda...
});
// After JSON data retrieval of 'email' and 'option' from https://3objects.netlify.com/3objects.json we send them an email with this info
clientEmail = email;
contact_option = option;
var eParams = {Destination: {ToAddresses: [clientEmail]}, Message: {Body: { Text: { Data: 'Your contact option is ${contact_option}' },},Subject: { Data: "Your Contact Preference" }}, Source: "sales@example.com"};
var email = ses.sendEmail(eParams, function (err, data) { if (err) console.log(err); else { console.log("===EMAIL SENT==="); } });
};
如何查询和使用外部 JSON url 数据?
最佳答案
我更喜欢使用 node-fetch 。它是一个让您使用 ES6 中的 fetch
函数的包。
我创建了一个使用 Node 获取的示例。函数 getCustomers
从 url 获取客户。
然后我创建了一个返回 Promise
的函数。在此 Promise 内,检索到的数据使用 AWS.SES()
通过邮件发送。
const AWS = require('aws-sdk'),
ses = new AWS.SES(),
fetch = require('node-fetch');
exports.handler = async (event) => {
console.log(event.customer_id);
const customers = await getCustomers();
customers.map(async customer => {
await sendEmailToCustomer(customer);
});
}
async function getCustomers() {
try {
const resp = await fetch('https://3objects.netlify.com/3objects.json');
const json = await resp.json();
console.log(json);
return json;
}
catch(e) {
throw e;
}
}
const sendEmailToCustomer = (customer) => new Promise((resolve, reject) => {
ses.sendEmail({
Destination:
{ ToAddresses: [customer.email] },
Message:
{
Body: { Text: { Data: `Your contact option is ${customer.customer_id}` }},
Subject: { Data: "Your Contact Preference" }
},
Source: "sales@example.com"}, (error, result => {
if (error) return reject(error);
resolve(result);
console.log(result);
})
}
关于javascript - 从外部静态 JSON 文件检索数据并在 AWS Lambda 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56789401/