Checking a DB table before doing an insert using AWS Lambda Pretty new to AWS Lambda and Javascript, and particularly Promises.

Simple check db table before insert.

It all seems to be working - I'm just wondering if there was a neater way of doing any of this that I'm not aware of.

import AWS from 'aws-sdk';
const dynamo = new AWS.DynamoDB.DocumentClient({ region: 'eu-west-1'})

export function main(event, context, callback) {

  dynamo.get({ TableName: 'client', Key: { id: event.name } })
    .promise()
    .then(function(data) {

      if(data.Item){
        callback(null, `Client name '${event.name}' is already in use.`)
        return
      }

      const timestamp = new Date().getTime()

      dynamo.put({
        TableName: 'client',
        Item: {
          id: event.name,
          created: timestamp,
          updated: timestamp,
          deleted: null
        },
        ConditionExpression: 'attribute_not_exists(id)'
      })
      .promise()
      .then(function(data) {
        callback(null, event)
      }).catch(function(err) {
        callback(err)
      })

  }).catch(function(err) {
     callback(err)
  })

}
Your code is already pretty good by common standards, IMO.

If it is possible, you can try to adopt ES7's async/await. The code will become more linear, while still asynchronous.

Watch out for browser compatibility though.



export async function main(event) {

  const data = await dynamo
    .get({ TableName: 'client', Key: { id: event.name } })
    .promise();

  if (data.Item) {
    throw new Error(`Client name '${event.name}' is already in use.`);
  }

  const timestamp = new Date().getTime();

  return await dynamo
    .put({
      TableName: 'client',
      Item: {
        id: event.name,
        created: timestamp,
        updated: timestamp,
        deleted: null
      },
      ConditionExpression: 'attribute_not_exists(id)'
    })
    .promise();

}