2
\$\begingroup\$

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)
  })

}
\$\endgroup\$
1
\$\begingroup\$

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();

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.