Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Writing data to Dynamodb from Serverless
'use strict';
const doc = require('dynamodb-doc');
const dynamo = new doc.DynamoDB();
const Q = require('kew');
module.exports.handler = (event, context, callback) => {
function putItem() {
const defer = Q.defer();
const query = event.queryStringParameters;
const params = {
TableName: 'test',
Item: {
customerId: query.customerId,
durationInHours: parseInt(query.durationInHours),
dynamo.putItem(params, defer.makeNodeResolver());
return defer.promise;
function response(data, statusCode) {
const response = {
statusCode: statusCode,
body: JSON.stringify({
data: data,
input: event,
callback(null, response);
.then(data => response(data, 200))
.fail(err => response(err, 500));
service: aws-nodejs
name: aws
runtime: nodejs4.3
stage: dev
region: ap-southeast-2
- Effect: "Allow"
- dynamodb:GetItem
- dynamodb:BatchGetItem
- dynamodb:Query
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
- dynamodb:BatchWriteItem
Resource: "arn:aws:dynamodb:ap-southeast-2:*:*"
handler: index.handler
- http:
path: index
method: post
Copy link

martimatix commented Oct 19, 2016

I was struggling with getting writes to Dynamodb to work through API gateway even though it was working fine through the Lambda console. The reason, it seems, was that the callback function was not being called and the parent function finished before the callback executed.

My solution here is to use promises as this ensures that the callback function is executed.

Still not sure if this pattern is the best way to go but putting this out there in case this is of any help to someone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment