I have an http request in my Lambda function that returns a json. I'm using node.js. I want to save that json as an object in my DynamoDB table.
const http = require('https')
const AWS = require('aws-sdk');
AWS.config.update({region: "eu-west-1"});
exports.handler = async (event) => {
return httprequest().then((data) => {
//Parse JSON to objects
// in this case not neccessary because it's already parsed.
// data is already object
// var arr_from_json = JSON.parse(data);
//add Item to DynamoDB
var params = {
TableName: 'json',
Item: {
date: Date.now(),
answer: data.answer,
forced: data.forced,
image: data.image
}
};
var docClient = new AWS.DynamoDB.DocumentClient();
docClient.put(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
// Respond with JSON
const response = {
statusCode: 200,
body: JSON.stringify(data),
};
return response;
});
};
function httprequest() {
return new Promise((resolve, reject) => {
const options = {
host: 'yesno.wtf',
path: '/api',
port: 443,
method: 'GET'
};
const req = http.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
var body = [];
res.on('data', function (chunk) {
body.push(chunk);
});
res.on('end', function () {
try {
body = JSON.parse(Buffer.concat(body).toString());
} catch (e) {
reject(e);
}
resolve(body);
});
});
req.on('error', (e) => {
reject(e.message);
});
// send the request
req.end();
});
}
JSON
{"answer":"no","forced":false,"image":"https://yesno.wtf/assets/no/8-5e08abbe5aacd2cf531948145b787e9a.gif"}
However, it's not storing the object in DynamoDB. What can I do differently? Is the section for storing in DynamoDB correct in the first place?