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)
 })
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Sep 6, 2017 at 21:21
\$\endgroup\$

1 Answer 1

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();
}
answered Sep 8, 2017 at 20:04
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.