Created
April 1, 2021 03:33
-
-
Save ccortezb/9ccee39dba558688de39d64a9f791521 to your computer and use it in GitHub Desktop.
create-book.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const AWS = require("aws-sdk"); | |
const crypto = require("crypto"); | |
// Generate unique id with no external dependencies | |
const generateUUID = () => crypto.randomBytes(16).toString("hex"); | |
// Initialising the DynamoDB SDK | |
const documentClient = new AWS.DynamoDB.DocumentClient(); | |
exports.handler = async event => { | |
const { title } = JSON.parse(event.body); | |
const params = { | |
TableName: "books", // The name of your DynamoDB table | |
Item: { // Creating an Item with a unique id and with the passed title | |
id: generateUUID(), | |
title: title | |
} | |
}; | |
try { | |
// Utilising the put method to insert an item into the table (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.03.html#GettingStarted.NodeJs.03.01) | |
const data = await documentClient.put(params).promise(); | |
const response = { | |
statusCode: 200 | |
}; | |
return response; // Returning a 200 if the item has been inserted | |
} catch (e) { | |
return { | |
statusCode: 500, | |
body: JSON.stringify(e) | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment