Connect AWS mobile backend to DynamoDB The 2019 Stack Overflow Developer Survey Results Are InAWS node.js lambda request dynamodb but no response (no err, no return data)Amazon SimpleDB vs Amazon DynamoDBDynamoDB vs MongoDB NoSQLAWS API Gateway Custom Authorizer AuthorizerConfigurationExceptionAWS API Gateway CORS ok for OPTIONS, fail for POSTPython AWS Lambda 301 redirectCalling AWS API Gateway from distant webclient using CORSAWS API Gateway return HTMLUnable to integrate API gateway with aws lambdaAWS Api Gateway Post to DynamoDBAWS API Gateway fails with “Unable to invoke” when query string contains key without value
What to do when moving next to a bird sanctuary with a loosely-domesticated cat?
Delete all lines which don't have n characters before delimiter
When should I buy a clipper card after flying to OAK?
Why do we hear so much about the Trump administration deciding to impose and then remove tariffs?
Aging parents with no investments
What does ひと匙 mean in this manga and has it been used colloquially?
Where to refill my bottle in India?
Resizing object distorts it (Illustrator CC 2018)
Deal with toxic manager when you can't quit
Loose spokes after only a few rides
Are there incongruent pythagorean triangles with the same perimeter and same area?
Am I thawing this London Broil safely?
Pokemon Turn Based battle (Python)
What are the motivations for publishing new editions of an existing textbook, beyond new discoveries in a field?
Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?
Time travel alters history but people keep saying nothing's changed
Have you ever entered Singapore using a different passport or name?
What do the Banks children have against barley water?
FPGA - DIY Programming
Apparent duplicates between Haynes service instructions and MOT
How to answer pointed "are you quitting" questioning when I don't want them to suspect
Should I use my personal e-mail address, or my workplace one, when registering to external websites for work purposes?
How come people say “Would of”?
Can one be advised by a professor who is very far away?
Connect AWS mobile backend to DynamoDB
The 2019 Stack Overflow Developer Survey Results Are InAWS node.js lambda request dynamodb but no response (no err, no return data)Amazon SimpleDB vs Amazon DynamoDBDynamoDB vs MongoDB NoSQLAWS API Gateway Custom Authorizer AuthorizerConfigurationExceptionAWS API Gateway CORS ok for OPTIONS, fail for POSTPython AWS Lambda 301 redirectCalling AWS API Gateway from distant webclient using CORSAWS API Gateway return HTMLUnable to integrate API gateway with aws lambdaAWS Api Gateway Post to DynamoDBAWS API Gateway fails with “Unable to invoke” when query string contains key without value
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I am trying to use AWS mobile backend (using lambda function) to insert into dynamoDB (also configured at the mobile backend) but with no success so far.
The relevant code:
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = function(event, context, callback)
var responseCode = 200;
var requestBody, pathParams, queryStringParams, headerParams, stage,
stageVariables, cognitoIdentityId, httpMethod, sourceIp, userAgent,
requestId, resourcePath;
console.log("request: " + JSON.stringify(event));
// Request Body
requestBody = event.body;
if (requestBody !== undefined && requestBody !== null)
// Set 'test-status' field in the request to test sending a specific response status code (e.g., 503)
responseCode = JSON.parse(requestBody)['test-status'];
// Path Parameters
pathParams = event.path;
// Query String Parameters
queryStringParams = event.queryStringParameters;
// Header Parameters
headerParams = event.headers;
if (event.requestContext !== null && event.requestContext !== undefined)
var requestContext = event.requestContext;
// API Gateway Stage
stage = requestContext.stage;
// Unique Request ID
requestId = requestContext.requestId;
// Resource Path
resourcePath = requestContext.resourcePath;
var identity = requestContext.identity;
// Amazon Cognito User Identity
cognitoIdentityId = identity.cognitoIdentityId;
// Source IP
sourceIp = identity.sourceIp;
// User-Agent
userAgent = identity.userAgent;
// API Gateway Stage Variables
stageVariables = event.stageVariables;
// HTTP Method (e.g., POST, GET, HEAD)
httpMethod = event.httpMethod;
// TODO: Put your application logic here...
let params =
Item:
"prop1":0,
"prop2":"text"
,
TableName:"testTable"
;
docClient.put(params, function(data, err)
if(err)
responseCode = 500;
else
responseCode = 200;
context.succeed(data);
);
// For demonstration purposes, we'll just echo these values back to the client
var responseBody =
requestBody : requestBody,
pathParams : pathParams,
queryStringParams : queryStringParams,
headerParams : headerParams,
stage : stage,
stageVariables : stageVariables,
cognitoIdentityId : cognitoIdentityId,
httpMethod : httpMethod,
sourceIp : sourceIp,
userAgent : userAgent,
requestId : requestId,
resourcePath : resourcePath
;
var response =
statusCode: responseCode,
headers:
"x-custom-header" : "custom header value"
,
body: JSON.stringify(responseBody)
;
console.log("response: " + JSON.stringify(response))
context.succeed(response);
;
this doesn't put the item to the table for some reason.
I gave the necessary permissions using the roles part, anything I am missing?
**responseCode is only for testing purposes.
Edit:
tried AWS node.js lambda request dynamodb but no response (no err, no return data) and doesn't work either.
Edit2:
Added the full handler code. (it the default generated code when creating first AWS lambda).
amazon-web-services amazon-dynamodb
|
show 3 more comments
I am trying to use AWS mobile backend (using lambda function) to insert into dynamoDB (also configured at the mobile backend) but with no success so far.
The relevant code:
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = function(event, context, callback)
var responseCode = 200;
var requestBody, pathParams, queryStringParams, headerParams, stage,
stageVariables, cognitoIdentityId, httpMethod, sourceIp, userAgent,
requestId, resourcePath;
console.log("request: " + JSON.stringify(event));
// Request Body
requestBody = event.body;
if (requestBody !== undefined && requestBody !== null)
// Set 'test-status' field in the request to test sending a specific response status code (e.g., 503)
responseCode = JSON.parse(requestBody)['test-status'];
// Path Parameters
pathParams = event.path;
// Query String Parameters
queryStringParams = event.queryStringParameters;
// Header Parameters
headerParams = event.headers;
if (event.requestContext !== null && event.requestContext !== undefined)
var requestContext = event.requestContext;
// API Gateway Stage
stage = requestContext.stage;
// Unique Request ID
requestId = requestContext.requestId;
// Resource Path
resourcePath = requestContext.resourcePath;
var identity = requestContext.identity;
// Amazon Cognito User Identity
cognitoIdentityId = identity.cognitoIdentityId;
// Source IP
sourceIp = identity.sourceIp;
// User-Agent
userAgent = identity.userAgent;
// API Gateway Stage Variables
stageVariables = event.stageVariables;
// HTTP Method (e.g., POST, GET, HEAD)
httpMethod = event.httpMethod;
// TODO: Put your application logic here...
let params =
Item:
"prop1":0,
"prop2":"text"
,
TableName:"testTable"
;
docClient.put(params, function(data, err)
if(err)
responseCode = 500;
else
responseCode = 200;
context.succeed(data);
);
// For demonstration purposes, we'll just echo these values back to the client
var responseBody =
requestBody : requestBody,
pathParams : pathParams,
queryStringParams : queryStringParams,
headerParams : headerParams,
stage : stage,
stageVariables : stageVariables,
cognitoIdentityId : cognitoIdentityId,
httpMethod : httpMethod,
sourceIp : sourceIp,
userAgent : userAgent,
requestId : requestId,
resourcePath : resourcePath
;
var response =
statusCode: responseCode,
headers:
"x-custom-header" : "custom header value"
,
body: JSON.stringify(responseBody)
;
console.log("response: " + JSON.stringify(response))
context.succeed(response);
;
this doesn't put the item to the table for some reason.
I gave the necessary permissions using the roles part, anything I am missing?
**responseCode is only for testing purposes.
Edit:
tried AWS node.js lambda request dynamodb but no response (no err, no return data) and doesn't work either.
Edit2:
Added the full handler code. (it the default generated code when creating first AWS lambda).
amazon-web-services amazon-dynamodb
Can you please post your whole Lambda handler? I have some some things in mind but need to check your handler first.
– Thales Minussi
Mar 8 at 9:45
Thanks, I added the full code (the automatically generated one from AWS). I should mention that this is just a test function to learn how to access the DB using lambda. (doing a university project and want to use a cloud DB)
– Daniel Toledano
Mar 8 at 10:03
Please also add the exact error message you are receiving when executing this code.
– Sébastien Stormacq
Mar 8 at 10:17
no error message at all.. it just doesn't add the item to the DB.
– Daniel Toledano
Mar 8 at 10:18
1
I was just thinking about that too. Thanks for the suggestion. I will reach out to the doc team
– Sébastien Stormacq
Mar 8 at 10:31
|
show 3 more comments
I am trying to use AWS mobile backend (using lambda function) to insert into dynamoDB (also configured at the mobile backend) but with no success so far.
The relevant code:
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = function(event, context, callback)
var responseCode = 200;
var requestBody, pathParams, queryStringParams, headerParams, stage,
stageVariables, cognitoIdentityId, httpMethod, sourceIp, userAgent,
requestId, resourcePath;
console.log("request: " + JSON.stringify(event));
// Request Body
requestBody = event.body;
if (requestBody !== undefined && requestBody !== null)
// Set 'test-status' field in the request to test sending a specific response status code (e.g., 503)
responseCode = JSON.parse(requestBody)['test-status'];
// Path Parameters
pathParams = event.path;
// Query String Parameters
queryStringParams = event.queryStringParameters;
// Header Parameters
headerParams = event.headers;
if (event.requestContext !== null && event.requestContext !== undefined)
var requestContext = event.requestContext;
// API Gateway Stage
stage = requestContext.stage;
// Unique Request ID
requestId = requestContext.requestId;
// Resource Path
resourcePath = requestContext.resourcePath;
var identity = requestContext.identity;
// Amazon Cognito User Identity
cognitoIdentityId = identity.cognitoIdentityId;
// Source IP
sourceIp = identity.sourceIp;
// User-Agent
userAgent = identity.userAgent;
// API Gateway Stage Variables
stageVariables = event.stageVariables;
// HTTP Method (e.g., POST, GET, HEAD)
httpMethod = event.httpMethod;
// TODO: Put your application logic here...
let params =
Item:
"prop1":0,
"prop2":"text"
,
TableName:"testTable"
;
docClient.put(params, function(data, err)
if(err)
responseCode = 500;
else
responseCode = 200;
context.succeed(data);
);
// For demonstration purposes, we'll just echo these values back to the client
var responseBody =
requestBody : requestBody,
pathParams : pathParams,
queryStringParams : queryStringParams,
headerParams : headerParams,
stage : stage,
stageVariables : stageVariables,
cognitoIdentityId : cognitoIdentityId,
httpMethod : httpMethod,
sourceIp : sourceIp,
userAgent : userAgent,
requestId : requestId,
resourcePath : resourcePath
;
var response =
statusCode: responseCode,
headers:
"x-custom-header" : "custom header value"
,
body: JSON.stringify(responseBody)
;
console.log("response: " + JSON.stringify(response))
context.succeed(response);
;
this doesn't put the item to the table for some reason.
I gave the necessary permissions using the roles part, anything I am missing?
**responseCode is only for testing purposes.
Edit:
tried AWS node.js lambda request dynamodb but no response (no err, no return data) and doesn't work either.
Edit2:
Added the full handler code. (it the default generated code when creating first AWS lambda).
amazon-web-services amazon-dynamodb
I am trying to use AWS mobile backend (using lambda function) to insert into dynamoDB (also configured at the mobile backend) but with no success so far.
The relevant code:
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = function(event, context, callback)
var responseCode = 200;
var requestBody, pathParams, queryStringParams, headerParams, stage,
stageVariables, cognitoIdentityId, httpMethod, sourceIp, userAgent,
requestId, resourcePath;
console.log("request: " + JSON.stringify(event));
// Request Body
requestBody = event.body;
if (requestBody !== undefined && requestBody !== null)
// Set 'test-status' field in the request to test sending a specific response status code (e.g., 503)
responseCode = JSON.parse(requestBody)['test-status'];
// Path Parameters
pathParams = event.path;
// Query String Parameters
queryStringParams = event.queryStringParameters;
// Header Parameters
headerParams = event.headers;
if (event.requestContext !== null && event.requestContext !== undefined)
var requestContext = event.requestContext;
// API Gateway Stage
stage = requestContext.stage;
// Unique Request ID
requestId = requestContext.requestId;
// Resource Path
resourcePath = requestContext.resourcePath;
var identity = requestContext.identity;
// Amazon Cognito User Identity
cognitoIdentityId = identity.cognitoIdentityId;
// Source IP
sourceIp = identity.sourceIp;
// User-Agent
userAgent = identity.userAgent;
// API Gateway Stage Variables
stageVariables = event.stageVariables;
// HTTP Method (e.g., POST, GET, HEAD)
httpMethod = event.httpMethod;
// TODO: Put your application logic here...
let params =
Item:
"prop1":0,
"prop2":"text"
,
TableName:"testTable"
;
docClient.put(params, function(data, err)
if(err)
responseCode = 500;
else
responseCode = 200;
context.succeed(data);
);
// For demonstration purposes, we'll just echo these values back to the client
var responseBody =
requestBody : requestBody,
pathParams : pathParams,
queryStringParams : queryStringParams,
headerParams : headerParams,
stage : stage,
stageVariables : stageVariables,
cognitoIdentityId : cognitoIdentityId,
httpMethod : httpMethod,
sourceIp : sourceIp,
userAgent : userAgent,
requestId : requestId,
resourcePath : resourcePath
;
var response =
statusCode: responseCode,
headers:
"x-custom-header" : "custom header value"
,
body: JSON.stringify(responseBody)
;
console.log("response: " + JSON.stringify(response))
context.succeed(response);
;
this doesn't put the item to the table for some reason.
I gave the necessary permissions using the roles part, anything I am missing?
**responseCode is only for testing purposes.
Edit:
tried AWS node.js lambda request dynamodb but no response (no err, no return data) and doesn't work either.
Edit2:
Added the full handler code. (it the default generated code when creating first AWS lambda).
amazon-web-services amazon-dynamodb
amazon-web-services amazon-dynamodb
edited Mar 8 at 10:03
Daniel Toledano
asked Mar 8 at 9:38
Daniel ToledanoDaniel Toledano
83
83
Can you please post your whole Lambda handler? I have some some things in mind but need to check your handler first.
– Thales Minussi
Mar 8 at 9:45
Thanks, I added the full code (the automatically generated one from AWS). I should mention that this is just a test function to learn how to access the DB using lambda. (doing a university project and want to use a cloud DB)
– Daniel Toledano
Mar 8 at 10:03
Please also add the exact error message you are receiving when executing this code.
– Sébastien Stormacq
Mar 8 at 10:17
no error message at all.. it just doesn't add the item to the DB.
– Daniel Toledano
Mar 8 at 10:18
1
I was just thinking about that too. Thanks for the suggestion. I will reach out to the doc team
– Sébastien Stormacq
Mar 8 at 10:31
|
show 3 more comments
Can you please post your whole Lambda handler? I have some some things in mind but need to check your handler first.
– Thales Minussi
Mar 8 at 9:45
Thanks, I added the full code (the automatically generated one from AWS). I should mention that this is just a test function to learn how to access the DB using lambda. (doing a university project and want to use a cloud DB)
– Daniel Toledano
Mar 8 at 10:03
Please also add the exact error message you are receiving when executing this code.
– Sébastien Stormacq
Mar 8 at 10:17
no error message at all.. it just doesn't add the item to the DB.
– Daniel Toledano
Mar 8 at 10:18
1
I was just thinking about that too. Thanks for the suggestion. I will reach out to the doc team
– Sébastien Stormacq
Mar 8 at 10:31
Can you please post your whole Lambda handler? I have some some things in mind but need to check your handler first.
– Thales Minussi
Mar 8 at 9:45
Can you please post your whole Lambda handler? I have some some things in mind but need to check your handler first.
– Thales Minussi
Mar 8 at 9:45
Thanks, I added the full code (the automatically generated one from AWS). I should mention that this is just a test function to learn how to access the DB using lambda. (doing a university project and want to use a cloud DB)
– Daniel Toledano
Mar 8 at 10:03
Thanks, I added the full code (the automatically generated one from AWS). I should mention that this is just a test function to learn how to access the DB using lambda. (doing a university project and want to use a cloud DB)
– Daniel Toledano
Mar 8 at 10:03
Please also add the exact error message you are receiving when executing this code.
– Sébastien Stormacq
Mar 8 at 10:17
Please also add the exact error message you are receiving when executing this code.
– Sébastien Stormacq
Mar 8 at 10:17
no error message at all.. it just doesn't add the item to the DB.
– Daniel Toledano
Mar 8 at 10:18
no error message at all.. it just doesn't add the item to the DB.
– Daniel Toledano
Mar 8 at 10:18
1
1
I was just thinking about that too. Thanks for the suggestion. I will reach out to the doc team
– Sébastien Stormacq
Mar 8 at 10:31
I was just thinking about that too. Thanks for the suggestion. I will reach out to the doc team
– Sébastien Stormacq
Mar 8 at 10:31
|
show 3 more comments
2 Answers
2
active
oldest
votes
I have refactored some bits of your code to look much simpler and use async/await (make sure to select Node 8.10 as the running environment for your function) instead of callbacks. I also got rid of the context and callback parameters, as they were used for older versions of NodeJS. Once you're using Node 8+, async/await should be the default option.
Also, it is possible to chain a .promise() on docClient.putItem, so you can easily await on it, making your code way simpler. I have left only the DynamoDB part (which is what is relevant to your question)
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = async (event) =>
let params =
Item:
"prop0":1,
"prop2":"text"
,
TableName:"testTable"
;
try
await docClient.put(params).promise();
catch (e)
console.log(e)
return
messsage: e.message
return message: 'Data inserted successfully' ;
;
Things to keep in mind if still it does not work:
Make sure your Lambda function has the right permissions to insert items on DynamoDB (AmazonDynamoDBFullAccess will do it)
You ALWAYS have to provide the partition key when inserting items to DynamoDB. On your example, the JSON only has two properties: prop1 and prop2. If none of them are the partition key, your code will certainly fail.
Make sure you table also exists
If you code fails, just check CloudWatch logs as any exception is now captured and printed out on the console.
add a comment |
The reason why no data is written in the table is because the call to DynamoDB put
is asynchronous and will return by calling your callback. But during that time, the rest of the code continues to execute and your function eventually finish before the call to DynamoDB has a chance to complete.
You can use the await
/ async
keywords to make your code sychronous :
async function writeToDynamoDB(params)
return new Promise((resolve,reject) =>
docClient.put(params, function(data, err)
if(err)
reject(500);
else
resolve(data);
);
);
let params = ...
var data = await writeToDynamoDB(params)
You can find sample code I wrote (in Typescript) at https://github.com/sebsto/maxi80-alexa/blob/master/lambda/src/DDBController.ts
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55060415%2fconnect-aws-mobile-backend-to-dynamodb%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
I have refactored some bits of your code to look much simpler and use async/await (make sure to select Node 8.10 as the running environment for your function) instead of callbacks. I also got rid of the context and callback parameters, as they were used for older versions of NodeJS. Once you're using Node 8+, async/await should be the default option.
Also, it is possible to chain a .promise() on docClient.putItem, so you can easily await on it, making your code way simpler. I have left only the DynamoDB part (which is what is relevant to your question)
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = async (event) =>
let params =
Item:
"prop0":1,
"prop2":"text"
,
TableName:"testTable"
;
try
await docClient.put(params).promise();
catch (e)
console.log(e)
return
messsage: e.message
return message: 'Data inserted successfully' ;
;
Things to keep in mind if still it does not work:
Make sure your Lambda function has the right permissions to insert items on DynamoDB (AmazonDynamoDBFullAccess will do it)
You ALWAYS have to provide the partition key when inserting items to DynamoDB. On your example, the JSON only has two properties: prop1 and prop2. If none of them are the partition key, your code will certainly fail.
Make sure you table also exists
If you code fails, just check CloudWatch logs as any exception is now captured and printed out on the console.
add a comment |
I have refactored some bits of your code to look much simpler and use async/await (make sure to select Node 8.10 as the running environment for your function) instead of callbacks. I also got rid of the context and callback parameters, as they were used for older versions of NodeJS. Once you're using Node 8+, async/await should be the default option.
Also, it is possible to chain a .promise() on docClient.putItem, so you can easily await on it, making your code way simpler. I have left only the DynamoDB part (which is what is relevant to your question)
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = async (event) =>
let params =
Item:
"prop0":1,
"prop2":"text"
,
TableName:"testTable"
;
try
await docClient.put(params).promise();
catch (e)
console.log(e)
return
messsage: e.message
return message: 'Data inserted successfully' ;
;
Things to keep in mind if still it does not work:
Make sure your Lambda function has the right permissions to insert items on DynamoDB (AmazonDynamoDBFullAccess will do it)
You ALWAYS have to provide the partition key when inserting items to DynamoDB. On your example, the JSON only has two properties: prop1 and prop2. If none of them are the partition key, your code will certainly fail.
Make sure you table also exists
If you code fails, just check CloudWatch logs as any exception is now captured and printed out on the console.
add a comment |
I have refactored some bits of your code to look much simpler and use async/await (make sure to select Node 8.10 as the running environment for your function) instead of callbacks. I also got rid of the context and callback parameters, as they were used for older versions of NodeJS. Once you're using Node 8+, async/await should be the default option.
Also, it is possible to chain a .promise() on docClient.putItem, so you can easily await on it, making your code way simpler. I have left only the DynamoDB part (which is what is relevant to your question)
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = async (event) =>
let params =
Item:
"prop0":1,
"prop2":"text"
,
TableName:"testTable"
;
try
await docClient.put(params).promise();
catch (e)
console.log(e)
return
messsage: e.message
return message: 'Data inserted successfully' ;
;
Things to keep in mind if still it does not work:
Make sure your Lambda function has the right permissions to insert items on DynamoDB (AmazonDynamoDBFullAccess will do it)
You ALWAYS have to provide the partition key when inserting items to DynamoDB. On your example, the JSON only has two properties: prop1 and prop2. If none of them are the partition key, your code will certainly fail.
Make sure you table also exists
If you code fails, just check CloudWatch logs as any exception is now captured and printed out on the console.
I have refactored some bits of your code to look much simpler and use async/await (make sure to select Node 8.10 as the running environment for your function) instead of callbacks. I also got rid of the context and callback parameters, as they were used for older versions of NodeJS. Once you're using Node 8+, async/await should be the default option.
Also, it is possible to chain a .promise() on docClient.putItem, so you can easily await on it, making your code way simpler. I have left only the DynamoDB part (which is what is relevant to your question)
'use strict';
console.log("Loading function");
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient(region:process.env.MOBILE_HUB_PROJECT_REGION);
exports.handler = async (event) =>
let params =
Item:
"prop0":1,
"prop2":"text"
,
TableName:"testTable"
;
try
await docClient.put(params).promise();
catch (e)
console.log(e)
return
messsage: e.message
return message: 'Data inserted successfully' ;
;
Things to keep in mind if still it does not work:
Make sure your Lambda function has the right permissions to insert items on DynamoDB (AmazonDynamoDBFullAccess will do it)
You ALWAYS have to provide the partition key when inserting items to DynamoDB. On your example, the JSON only has two properties: prop1 and prop2. If none of them are the partition key, your code will certainly fail.
Make sure you table also exists
If you code fails, just check CloudWatch logs as any exception is now captured and printed out on the console.
edited Mar 8 at 10:41
Wai Ha Lee
6,146124166
6,146124166
answered Mar 8 at 10:22
Thales MinussiThales Minussi
1,6851519
1,6851519
add a comment |
add a comment |
The reason why no data is written in the table is because the call to DynamoDB put
is asynchronous and will return by calling your callback. But during that time, the rest of the code continues to execute and your function eventually finish before the call to DynamoDB has a chance to complete.
You can use the await
/ async
keywords to make your code sychronous :
async function writeToDynamoDB(params)
return new Promise((resolve,reject) =>
docClient.put(params, function(data, err)
if(err)
reject(500);
else
resolve(data);
);
);
let params = ...
var data = await writeToDynamoDB(params)
You can find sample code I wrote (in Typescript) at https://github.com/sebsto/maxi80-alexa/blob/master/lambda/src/DDBController.ts
add a comment |
The reason why no data is written in the table is because the call to DynamoDB put
is asynchronous and will return by calling your callback. But during that time, the rest of the code continues to execute and your function eventually finish before the call to DynamoDB has a chance to complete.
You can use the await
/ async
keywords to make your code sychronous :
async function writeToDynamoDB(params)
return new Promise((resolve,reject) =>
docClient.put(params, function(data, err)
if(err)
reject(500);
else
resolve(data);
);
);
let params = ...
var data = await writeToDynamoDB(params)
You can find sample code I wrote (in Typescript) at https://github.com/sebsto/maxi80-alexa/blob/master/lambda/src/DDBController.ts
add a comment |
The reason why no data is written in the table is because the call to DynamoDB put
is asynchronous and will return by calling your callback. But during that time, the rest of the code continues to execute and your function eventually finish before the call to DynamoDB has a chance to complete.
You can use the await
/ async
keywords to make your code sychronous :
async function writeToDynamoDB(params)
return new Promise((resolve,reject) =>
docClient.put(params, function(data, err)
if(err)
reject(500);
else
resolve(data);
);
);
let params = ...
var data = await writeToDynamoDB(params)
You can find sample code I wrote (in Typescript) at https://github.com/sebsto/maxi80-alexa/blob/master/lambda/src/DDBController.ts
The reason why no data is written in the table is because the call to DynamoDB put
is asynchronous and will return by calling your callback. But during that time, the rest of the code continues to execute and your function eventually finish before the call to DynamoDB has a chance to complete.
You can use the await
/ async
keywords to make your code sychronous :
async function writeToDynamoDB(params)
return new Promise((resolve,reject) =>
docClient.put(params, function(data, err)
if(err)
reject(500);
else
resolve(data);
);
);
let params = ...
var data = await writeToDynamoDB(params)
You can find sample code I wrote (in Typescript) at https://github.com/sebsto/maxi80-alexa/blob/master/lambda/src/DDBController.ts
answered Mar 8 at 10:29
Sébastien StormacqSébastien Stormacq
8,31822445
8,31822445
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55060415%2fconnect-aws-mobile-backend-to-dynamodb%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Can you please post your whole Lambda handler? I have some some things in mind but need to check your handler first.
– Thales Minussi
Mar 8 at 9:45
Thanks, I added the full code (the automatically generated one from AWS). I should mention that this is just a test function to learn how to access the DB using lambda. (doing a university project and want to use a cloud DB)
– Daniel Toledano
Mar 8 at 10:03
Please also add the exact error message you are receiving when executing this code.
– Sébastien Stormacq
Mar 8 at 10:17
no error message at all.. it just doesn't add the item to the DB.
– Daniel Toledano
Mar 8 at 10:18
1
I was just thinking about that too. Thanks for the suggestion. I will reach out to the doc team
– Sébastien Stormacq
Mar 8 at 10:31