Skip to content

Instantly share code, notes, and snippets.

@hoffination
Created February 14, 2017 02:28
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 hoffination/9ada9c89c1b656ce747a6ad9281adb47 to your computer and use it in GitHub Desktop.
Save hoffination/9ada9c89c1b656ce747a6ad9281adb47 to your computer and use it in GitHub Desktop.
Introduction to DynamoDB on NodeJS
var AWS = require('aws-sdk');
AWS.config.update({
endpoint: "http://localhost:8000",
region: "us-west-2",
accessKeyId: "myKeyId",
secretAccessKey: "secretKey"
});
var dyn = new AWS.DynamoDB();
var docClient = new AWS.DynamoDB.DocumentClient();
dyn.listTables(function (err, data) {
if (data.TableNames.indexOf('Entries') === -1) {
var params = {
TableName : "Entries",
KeySchema: [
{ AttributeName: "userId", KeyType: "HASH" }, //Partition key
{ AttributeName: "id", KeyType: "RANGE"} //Sort key
],
AttributeDefinitions: [
{ AttributeName: "userId", AttributeType: "S" },
{ AttributeName: "id", AttributeType: "N" }
],
ProvisionedThroughput: {
ReadCapacityUnits: 10,
WriteCapacityUnits: 10
}
};
dyn.createTable(params, function(err, data) {
if (err) {
console.log("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
}
});
} else {
var reqParams = {
TableName: "Entries",
Key: {
"userId": 'BEN',
"id": 2
}
};
docClient.get(reqParams, function(err, data) {
if (err) {
console.log("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
} else {
if (Object.keys(data).length === 0) {
var docParams = {
TableName: "Entries",
Item: {
"userId": 'BEN',
"id": 2,
"title": 'Slurpie',
"calories": 300
},
};
docClient.put(docParams, function(err, data) {
if (err) {
console.log("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
}
});
} else {
console.log("Item insertion succeeded:", JSON.stringify(data, null, 2));
}
}
});
var query = {
TableName: 'Entries',
KeyConditionExpression: "#id = :userId",
ExpressionAttributeNames:{
"#id": "userId"
},
ExpressionAttributeValues: {
":userId":'BEN'
}
};
docClient.query(query, function(err, data) {
if (err) {
console.log('Unable to query data. Error JSON:', JSON.stringify(err, null, 2));
} else {
console.log('Gathered queried item:', JSON.stringify(data, null, 2));
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment