How to insert into DynamoDB with AWS Lambda, using NodeJS

11 April 2021

Lambda and DynamoDB are great AWS solutions that work perfectly together. We’ll show you how to call DynamoDB via your AWS Lambda function, using NodeJS, to create an entry.

Before everything, we have to ensure our DynamoDB table and Lambda function are created, and all the necessary access permissions are given. Once they are defined, you can use the following nodeJS code in your lambda to create an entry in your table. In this case, we are creating a user entry:

const AWS = require("aws-sdk");
const Joi = require('joi');
const uuid = require('uuid');
const AWS = require("aws-sdk");
const docClient = new AWS.DynamoDB.DocumentClient();

const schema = Joi.object({
    name: Joi.string().required(),
    surname: Joi.string().required(),
    country: Joi.string().required(),
    phone: Joi.string().required(),
    email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
});

exports.handler = async (event, context) => {
    let validParams = await schema.validateAsync(event.body);
    let itemId: uuid.v4();
    let params = {
        'Contact',
        Item:{
        id: itemId,
        name: event.body.name,
        surname: event.body.surname,
        country: event.body.country,
        phone: event.body.phone,
        email: event.body.email
        }
    };
    await docClient.put(params).promise;
    return {
    statusCode: 200,
    body: JSON.stringify({id: itemId}),
    }
});
                    

To make this whole process easier and in a matter of minutes, without any local setup, use ModernCloud. ModernCloud is the best way to create, manage and deploy your lambdas. We provide everything you need, out of the box. Try it now for free!