markusklems / serverless-node-dynamodb-example

Sample application that uses serverless + nodejs + dynamodb
Apache License 2.0
76 stars 17 forks source link

context.succeed for create? #2

Open AlexMcConnell opened 8 years ago

AlexMcConnell commented 8 years ago

I haven't cloned this repository, so maybe there's just something different from your code and mine that I'm missing, but when I use context.succeed for the create operation, it shows the postId in Postman, but it doesn't actually create the db entry.

deryl27 commented 8 years ago

Even I am facing this issue

luctus commented 8 years ago

It worked for me. Did you set the permissions to dynamodb?

abalone0204 commented 8 years ago

@luctus I've faced the same problem.

I set theAdministratorAccess policy to the IAM user. And also modified the s-resources-cf.json: add resources permission to access dynamodb. It would very helpful if you could tell me what's wrong with my codes, or let us see how it worked on your project. I've stuck by this issue for whole day.

btw, I've posted a question on stackoverflow

AlexMcConnell commented 8 years ago

If I were missing permissions, it would return an error instead of just not doing anything. Everything works fine with context.done, just not with context.succeed.

abalone0204 commented 8 years ago

@AlexMcConnell ! I just figure it out! In the second arguments of the putItem, it should be a callback function, but in the example:

 dynamo.putItem(event.payload,context.succeed({"postId":event.payload.Item.postId}));

It's executed inline..

So if we change this into

dynamo.putItem(event.payload, function() {
  context.succeed({"postId":event.payload.Item.postId})
});

The context.succeed will be executed after the putItem be done.

:D Hope this may helpful to you!

luctus commented 8 years ago

@abalone0204 I'm kind of new to node, but I was pretty sure that there is no difference between

dynamo.putItem(event.payload,context.succeed({"postId":event.payload.Item.postId}));

and

dynamo.putItem(event.payload, function() {
  context.succeed({"postId":event.payload.Item.postId})
});

Am I wrong?

abalone0204 commented 8 years ago

No, they are absolutely different.

dynamo.putItem(event.payload, function() {
  context.succeed({"postId":event.payload.Item.postId})
});

It's a function declaration in the second argument, it will wait for the putItem done then call this function.

As for this:

 dynamo.putItem(event.payload,context.succeed({"postId":event.payload.Item.postId}));

context.succeed will be executed in line and return a result to the second argument.

You can check this link to understand the callback style in JavaScript.

Or you can just give a try, you will be suprised that it works. Btw, you should put some permission into the s-resources-cf.json. I've created a similar example, you can check my repo, too