DynamoDB仅从JSON列表中保存一个记录
我正在尝试循环浏览JSON文件中的URL列表,调用API,然后将结果保存在数据库中。它循环遍历整个列表,但仅保存了第一个URL结果。在每个API调用后,如何将所有URL保存在循环中?
我的代码:
exports.putItemHandler = async (event) => {
const { body, httpMethod, path } = event;
if (httpMethod !== 'POST') {
throw new Error(`postMethod only accepts POST method, you tried: ${httpMethod} method.`);
}
// All log statements are written to CloudWatch by default. For more information, see
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html
console.log('received:', JSON.stringify(event));
console.log('----STARTING LOOP----')
console.log(v4())
console.log(urls)
var _id;
try {
for (const url of urls) {
_id = v4();
const resp = await axios.get(endpoint, {
params: {
key: API_KEY,
url: url
}
});
console.log(JSON.stringify(resp.data))
const lighthouseResults = resp.data;
const params = {
TableName: tableName,
Item: { id: _id,
created_at: new Date().toISOString(),
URL: url,
fullJson: lighthouseResults,
},
};
await docClient.put(params).promise();
const response = {
statusCode: 200,
body,
};
console.log(`response from: ${path} statusCode: ${response.statusCode} body: ${response.body}`);
return response;
}
} catch (err) {
console.error(err)
}
};
I'm trying to loop through a list of URLs in a JSON file, call an API and then save the results in the database. It loops through the whole list but only saves the first URL results. How can I get all URLs in the loop to be saved after each API call?
My code:
exports.putItemHandler = async (event) => {
const { body, httpMethod, path } = event;
if (httpMethod !== 'POST') {
throw new Error(`postMethod only accepts POST method, you tried: ${httpMethod} method.`);
}
// All log statements are written to CloudWatch by default. For more information, see
// https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-logging.html
console.log('received:', JSON.stringify(event));
console.log('----STARTING LOOP----')
console.log(v4())
console.log(urls)
var _id;
try {
for (const url of urls) {
_id = v4();
const resp = await axios.get(endpoint, {
params: {
key: API_KEY,
url: url
}
});
console.log(JSON.stringify(resp.data))
const lighthouseResults = resp.data;
const params = {
TableName: tableName,
Item: { id: _id,
created_at: new Date().toISOString(),
URL: url,
fullJson: lighthouseResults,
},
};
await docClient.put(params).promise();
const response = {
statusCode: 200,
body,
};
console.log(`response from: ${path} statusCode: ${response.statusCode} body: ${response.body}`);
return response;
}
} catch (err) {
console.error(err)
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论