Skip to content

Instantly share code, notes, and snippets.

@astuyve
Created May 26, 2023 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astuyve/94029d6206eaf144903579cb5d1ea843 to your computer and use it in GitHub Desktop.
Save astuyve/94029d6206eaf144903579cb5d1ea843 to your computer and use it in GitHub Desktop.
Lazy load todo app
'use strict';
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, PutCommand } = require("@aws-sdk/lib-dynamodb");
const dynamoClient = new DynamoDBClient({ region: process.env.AWS_REGION });
const ddbClient = DynamoDBDocumentClient.from(dynamoClient);
let snsClient, PublishBatchCommand, SNSClient
const { v4: uuidv4 } = require("uuid");
const loadSns = () => {
({ SNSClient, PublishBatchCommand } = require("@aws-sdk/client-sns"));
snsClient = new SNSClient({ region: process.env.AWS_REGION });
}
module.exports.addItem = async (event) => {
const body = JSON.parse(event.body);
const promises = []
const newItemId = uuidv4()
if (body.userId === 'aj') {
loadSns();
const snsCommand = new PublishBatchCommand({
PublishBatchRequestEntries: [{
Message: JSON.stringify(body),
Id: newItemId,
}],
TopicArn: process.env.TODO_TOPIC_ARN
})
promises.push(snsClient.send(snsCommand))
}
const { status, item, itemName } = body
const putItemCommand = new PutCommand({
TableName: process.env.TODO_TABLE_NAME,
Item: {
pk: newItemId,
sk: Date.now().toString(),
status,
item,
itemName
}
})
promises.push(ddbClient.send(putItemCommand))
const res = await Promise.allSettled(promises)
return {
statusCode: 200,
headers: {
"content-type": "application/json",
},
body: JSON.stringify({ status: "pushed", body }),
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment