All Projects → dabit3 → Dynamodb Documentclient Cheat Sheet

dabit3 / Dynamodb Documentclient Cheat Sheet

DynamoDB JavaScript DocumentClient cheat sheet

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Dynamodb Documentclient Cheat Sheet

Aws Sdk Perl
A community AWS SDK for Perl Programmers
Stars: ✭ 153 (-47.78%)
Mutual labels:  aws, dynamodb
Faraday
DynamoDB client for Clojure
Stars: ✭ 193 (-34.13%)
Mutual labels:  aws, dynamodb
Sqs Worker Serverless
Example for SQS Worker in AWS Lambda using Serverless
Stars: ✭ 164 (-44.03%)
Mutual labels:  aws, dynamodb
Serverless Dynamodb Autoscaling
Serverless Plugin for Amazon DynamoDB Auto Scaling configuration.
Stars: ✭ 142 (-51.54%)
Mutual labels:  aws, dynamodb
Terraform Aws Tfstate Backend
Terraform module that provision an S3 bucket to store the `terraform.tfstate` file and a DynamoDB table to lock the state file to prevent concurrent modifications and state corruption.
Stars: ✭ 229 (-21.84%)
Mutual labels:  aws, dynamodb
Dynomite
⚡🦀 🧨 make your rust types fit DynamoDB and visa versa
Stars: ✭ 144 (-50.85%)
Mutual labels:  aws, dynamodb
Realworld Dynamodb Lambda
λ serverless backend implementation for RealWorld using AWS DynamoDB + Lambda
Stars: ✭ 185 (-36.86%)
Mutual labels:  aws, dynamodb
Designing Cloud Native Microservices On Aws
Introduce a fluent way to design cloud native microservices via EventStorming workshop, this is a hands-on workshop. Contains such topics: DDD, Event storming, Specification by example. Including the AWS product : Serverless Lambda , DynamoDB, Fargate, CloudWatch.
Stars: ✭ 131 (-55.29%)
Mutual labels:  aws, dynamodb
Serverless Analytics
Track website visitors with Serverless Analytics using Kinesis, Lambda, and TypeScript.
Stars: ✭ 219 (-25.26%)
Mutual labels:  aws, dynamodb
Dialetus Service
API to Informal dictionary for the idiomatic expressions that each Brazilian region It has
Stars: ✭ 202 (-31.06%)
Mutual labels:  aws, dynamodb
Dql
A SQL-ish language for DynamoDB
Stars: ✭ 141 (-51.88%)
Mutual labels:  aws, dynamodb
Aws Toolkit Eclipse
AWS Toolkit for Eclipse – an open-source plugin for developing, deploying, and managing AWS applications.
Stars: ✭ 252 (-13.99%)
Mutual labels:  aws, dynamodb
Graphql Recipes
A list of GraphQL recipes that, when used with the Amplify CLI, will deploy an entire AWS AppSync GraphQL backend.
Stars: ✭ 137 (-53.24%)
Mutual labels:  aws, dynamodb
Awsmobile Cli
CLI experience for Frontend developers in the JavaScript ecosystem.
Stars: ✭ 147 (-49.83%)
Mutual labels:  aws, dynamodb
Dynamo Easy
DynamoDB client for NodeJS and browser with a fluent api to build requests. We take care of the type mapping between JS and DynamoDB, customizable trough typescript decorators.
Stars: ✭ 133 (-54.61%)
Mutual labels:  aws, dynamodb
Aws Cost Saver
A tiny CLI tool to help save costs in development environments when you're asleep and don't need them!
Stars: ✭ 178 (-39.25%)
Mutual labels:  aws, dynamodb
Flywheel
Object mapper for Amazon's DynamoDB
Stars: ✭ 124 (-57.68%)
Mutual labels:  aws, dynamodb
Dynein
DynamoDB CLI written in Rust.
Stars: ✭ 126 (-57%)
Mutual labels:  aws, dynamodb
Aws Mobile React Native Starter
AWS Mobile React Native Starter App https://aws.amazon.com/mobile
Stars: ✭ 2,247 (+666.89%)
Mutual labels:  aws, dynamodb
Komiser
☁️ Cloud Environment Inspector 👮🔒 💰
Stars: ✭ 2,684 (+816.04%)
Mutual labels:  aws, dynamodb

DynamoDB JavaScript DocumentClient cheat sheet

The DynamoDB Document Client is the easiest and most preferred way to interact with a DynamoDB database from a Nodejs or JavaScript application.

This cheat sheet will help you get up and running quickly building applications with DynamoDB in a Nodejs or JavaScript environment.

This is meant to be a concise version of the full documentation located here to help you get productive as quickly as possible.

For more great DynamoDB resources, check out the DynamoDB Guide.

Getting started

  1. Make sure you have the aws-sdk JavaScript SDK installed or available in the environment. If you are using AWS Lambda, this should already be available.
npm install aws-sdk
  1. Import the SDK and create a new DynamoDB document client.
const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

The AWS.DynamoDB.DocumentClient() constructor takes an optional hash of options. For instance, if you are wanting to set the location to a different region than the main AWS configuration, you could pass it in like this:

const docClient = new AWS.DynamoDB.DocumentClient({ region: 'us-east-2' })

Check out the documentation for those options here.

Database operations

The main things you will be doing are interacting with the database in one of the following ways:

put - docs - Creates a new item, or replaces an old item with a new item by delegating to AWS.DynamoDB.putItem().
scan - docs - Returns one or more items and item attributes by accessing every item in a table or a secondary index (limit of 1 MB of data).
get - docs - Returns a single item given the primary key of that item
query - docs - Returns one or more items and item attributes by accessing every item in a table or a secondary index (maximum of 1 MB of data).
delete - docs - Deletes a single item in a table by primary key by delegating to AWS.DynamoDB.deleteItem().
update - docs - Edits an existing item's attributes, or adds a new item to the table if it does not already exist by delegating to AWS.DynamoDB.updateItem().
batchWrite - docs - Puts or deletes multiple items in one or more tables by delegating to AWS.DynamoDB.batchWriteItem().

There are also other methods:

batchGet - Returns the attributes of one or more items from one or more tables by delegating to AWS.DynamoDB.batchGetItem().
createSet - Creates a set of elements inferring the type of set from the type of the first element.
transactGet - Atomically retrieves multiple items from one or more tables (but not from indexes) in a single account and region.
transactWrite - Synchronous write operation that groups up to 10 action requests.

Usage

Put - Creating a new item / replacing an old item with a new item

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Item: {
    id: '001',
    price: 100.0,
    inStock: true,
    name: 'Yeezys',
    sizes: [8, 8.5, 9, 10, 11, 12, 13],
  },
}

docClient.put(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function createItem(itemData) {
  var params = {
    TableName: 'ProductTable',
    Item: itemData,
  }
  try {
    await docClient.put(params).promise()
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const { data } = event.body
    await createItem(data)
    return { body: 'successfully created item' }
  } catch (err) {
    return { error: err }
  }
}

scan - scanning and returning all of the items in the database

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  FilterExpression: '#shoename = :shoename', // optional
  ExpressionAttributeValues: { ':shoename': 'yeezys' }, // optional
  ExpressionAttributeNames: { '#shoename': 'name' }, // optional
}

docClient.scan(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function listItems() {
  var params = {
    TableName: 'ProductTable',
  }
  try {
    const data = await docClient.scan(params).promise()
    return data
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const data = await listItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

get - getting a single item by primary key

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Key: {
    HashKey: 'hashkey',
  },
}

docClient.get(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function getItem(id) {
  var params = {
    TableName: 'ProductTable',
    Key: { id },
  }
  try {
    const data = await docClient.get(params).promise()
    return data
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const data = await getItem(event.item.id)
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

query - Access items from a table by primary key or a secondary index / GSI.

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  IndexName: 'type-index',
  KeyConditionExpression: '#typename = :typename', // this equals "type = hat"
  ExpressionAttributeNames: { '#typename': 'type' },
  ExpressionAttributeValues: { ':typename': 'hat' },
}

docClient.query(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function queryItems(type) {
  var params = {
    TableName: 'ProductTable',
    IndexName: 'type-index',
    ExpressionAttributeNames: { '#typename': 'type' },
    KeyConditionExpression: '#typename = :typename',
    ExpressionAttributeValues: { ':typename': type },
  }
  try {
    const data = await docClient.query(params).promise()
    return data
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const data = await queryItems(event.item.type)
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

delete - Delete a single item

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Key: {
    id: 'my-item-id-to-delete',
  },
}

docClient.delete(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function deleteItem(id) {
  var params = {
    TableName: 'ProductTable',
    Key: { id },
  }
  try {
    await docClient.delete(params).promise()
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    await deleteItem(event.item.id)
    return { body: 'successfully deleted item' }
  } catch (err) {
    return { error: err }
  }
}

update - Update a single item

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

var params = {
  TableName: 'ProductTable',
  Key: { id: 'my-item-id' },
  UpdateExpression: 'set price = :newprice',
  ExpressionAttributeValues: { ':newprice': 100 },
}

docClient.update(params, function (err, data) {
  if (err) console.log(err)
  else console.log(data)
})

// async function abstraction
async function updateItem(id, price) {
  var params = {
    TableName: 'ProductTable',
    Key: { id },
    UpdateExpression: 'set price = :newprice',
    ExpressionAttributeValues: { ':newprice': price },
  }
  try {
    await docClient.update(params).promise()
  } catch (err) {
    return err
  }
}

// usage
exports.handler = async (event, context) => {
  try {
    const { id, price } = event.item
    await updateItem(id, price)
    return { body: 'successfully updated item' }
  } catch (err) {
    return { error: err }
  }
}

batchWrite - Seed a table with data

full docs

const AWS = require('aws-sdk')
const docClient = new AWS.DynamoDB.DocumentClient()

// JSON data
const fetchedData = [
  { language: 'JavaScript', isFun: true },
  { language: 'Rust', isFun: true },
]

// format data for docClient
const seedData = fetchedData.map((item) => {
  return {
    PutRequest: {
      Item: item,
    },
  }
})

/* We can only batch-write 25 items at a time,
  so we'll store both the quotient, as well as what's left.
  */

let quotient = Math.floor(seedData.length / 25)
const remainder = (seedData.length % 25)

/* Upload in increments of 25 */

let batchMultiplier = 1
while (quotient > 0) {
  for (let i = 0; i < seedData.length - 1; i += 25) {
    await docClient.batchWrite(
      {
        RequestItems: {
          YOUR_TABLE_NAME: seedData.slice(i, 25 * batchMultiplier),
        },
      },
      (err, data) => {
        if (err) {
          console.log('something went wrong...')
        } else {
          console.log('yay...uploaded!')
        }
      }
    ).promise()
    console.log({ quotient })
    ++batchMultiplier
    --quotient
  }
}

/* Upload the remaining items (less than 25) */]
if(remainder > 0){
  await docClient.batchWrite(
    {
      RequestItems: {
        YOUR_TABLE_NAME: seedData.slice(seedData.length - remainder),
      },
    },
    (err, data) => {
      if (err) {
        console.log('something went wrong...')
      } else {
        console.log('yay...the remainder uploaded!')
      }
    }
  ).promise()
}
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].