• Stars
    star
    443
  • Rank 97,962 (Top 2 %)
  • Language
  • Created almost 5 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

DynamoDB JavaScript DocumentClient cheat sheet

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()
}

More Repositories

1

awesome-aws-amplify

Curated list of AWS Amplify Resources
1,785
star
2

polygon-ethereum-nextjs-marketplace

A full stack digital marketplace running on Ethereum with Polygon & Next.js
JavaScript
1,303
star
3

full-stack-ethereum

Building full stack apps with Solidity, Ethers.js, Hardhat, and The Graph
TypeScript
802
star
4

react-native-ai

Full stack framework for building cross-platform mobile AI apps
TypeScript
794
star
5

semantic-search-nextjs-pinecone-langchain-chatgpt

Embeds text files into vectors, stores them on Pinecone, and enables semantic search using GPT3 and Langchain in a Next.js UI
TypeScript
739
star
6

awesome-aws-appsync

Curated list of AWS AppSync Resources
625
star
7

gpt-travel-advisor

reference architecture for building a travel application with GPT3
TypeScript
543
star
8

foundry-cheatsheet

522
star
9

complete-guide-to-full-stack-solana-development

Code examples for the blog post titled The Complete Guide to Full Stack Solana Development with React, Anchor, Rust, and Phantom
JavaScript
474
star
10

full-stack-web3

A full stack web3 on-chain blog and CMS
JavaScript
420
star
11

next.js-amplify-workshop

AWS Amplify Next.js workshop
JavaScript
360
star
12

gatsby-auth-starter-aws-amplify

Starter Project with Authentication with Gatsby & AWS Amplify
JavaScript
320
star
13

gpt-fine-tuning-with-nodejs

GPT Fine-Tuning using Node.js - an easy to use starter project
JavaScript
250
star
14

full-stack-serverless-code

Code examples for my book Full Stack Serverless with O'Reilly Publications
JavaScript
244
star
15

openai-functions-god-app

TypeScript
240
star
16

heard

React Native Enterprise Social Messaging App
JavaScript
236
star
17

aws-appsync-react-workshop

Building real-time offline-ready Applications with React, GraphQL & AWS AppSync
JavaScript
228
star
18

nextjs-chatgpt-plugin-starter

ChatGPT plugin starter project using Next.js
TypeScript
209
star
19

micro-frontend-example

Building Micro Frontends with React, Vue, and Single-spa
JavaScript
207
star
20

amplify-photo-sharing-workshop

Building full-stack cloud apps with AWS Amplify and React
JavaScript
197
star
21

chicken-tikka-masala-recipe

Nader's chicken tikka masala recipe
PHP
193
star
22

decentralized-identity-example

An authentication system built with Ceramic & self.id
JavaScript
190
star
23

aws-amplify-workshop-react

Building Serverless React Applications with AWS Amplify
172
star
24

building-a-subgraph-workshop

In this workshop you'll learn how to build an NFT Subgraph using any smart contract or smart contracts.
TypeScript
165
star
25

graphql-recipes

A list of GraphQL recipes that, when used with the Amplify CLI, will deploy an entire AWS AppSync GraphQL backend.
158
star
26

next.js-cdk-amplify-workshop

Full stack serverless workshop with Next.js, CDK, and AWS Amplify
JavaScript
157
star
27

supabase-next.js

Full stack app built with Supabase and Next.js
JavaScript
152
star
28

titter

Decentralized Twitter prototype built with Polygon, GraphQL, Next.js, Ceramic, Arweave, and Bundlr
JavaScript
152
star
29

supabase-nextjs-auth

Example project implementing authentication, authorization, and routing with Next.js and Supabase
JavaScript
151
star
30

react-native-in-action

React Native in Action, written for Manning Publications
146
star
31

prompt-engineering-for-javascript-developers

Notes summarized from ChatGPT Prompt Engineering for Developers by DeepLearning.ai
145
star
32

write-with-me

Real-time Collaborative Markdown Editor
JavaScript
144
star
33

foundry-workshop

Building and testing smart contracts with Foundry
Solidity
144
star
34

aws-amplify-workshop-react-native

Building Cloud-enabled Mobile Applications with React Native & AWS Amplify
JavaScript
139
star
35

lens-protocol-frontend

Example of a basic front end built on Lens Protocol
JavaScript
136
star
36

cdk-graphql-backend

A real-time GraphQL API deployed with CDK using AWS AppSync, AWS Lambda, and DynamoDB
TypeScript
131
star
37

create-new-cli

Create your own CLI using a series of simple commands.
JavaScript
128
star
38

perma

Perma is a web3 prototype of permanent video storage and viewing using Next.js, Arweave, and Bundlr.
JavaScript
120
star
39

appsync-graphql-real-time-canvas

Collaborative real-time canvas built with GraphQL, AWS AppSync, & React Canvas Draw
JavaScript
119
star
40

full-stack-ethereum-marketplace-workshop

Build a Full Stack Marketplace on Ethereum with React, Solidity, Hardhat, and Ethers.js
JavaScript
118
star
41

hype-beats

Real-time Collaborative Beatbox with React & GraphQL
JavaScript
111
star
42

amplify-auth-demo

Demo of OAuth + Username / Password authentication in AWS Amplify
JavaScript
111
star
43

next.js-authentication-aws

This project deploys a Next.js project to AWS with comprehensive authentication enabled
JavaScript
104
star
44

this-or-that

This or that - Real-time atomic voting app built with AWS Amplify
CSS
98
star
45

react-native-deep-linking

Deep Linking set up in a React Native App
Objective-C
96
star
46

beginning-webpack

This repository goes along with the medium post titled "Beginner's guide to Webpack"
JavaScript
95
star
47

react-native-bootcamp

React Native Bootcamp Materials for TylerMcginnis.com
94
star
48

react-native-mobx-list-app

React Native + Mobx List Application
JavaScript
91
star
49

appsync-auth-and-unauth

How to allow both authenticated & unauthenticated access to an API
JavaScript
91
star
50

aws-amplify-workshop-web

Building web applications with React & AWS Amplify
JavaScript
90
star
51

full-stack-ethereum-workshop

Building full stack dapps on the EVM with Hardhat, React, and Ethers.js
HTML
89
star
52

sign-in-with-ethereum-authentication-flow

Example implementation of how to implement Sign In with Ethereum
JavaScript
85
star
53

react-notes

React notes tutorial
JavaScript
84
star
54

vue-graphql-appsync

Vue example using GraphQL with AWS AppSync
JavaScript
81
star
55

lens-pwa

Lens PWA
TypeScript
80
star
56

amplify-datastore-example

Example of basic app using Amplify DataStore
JavaScript
78
star
57

custom-nft-subgraph-workshop

78
star
58

lens-shadcn

Example application combining Lens Protocol, WalletConnect, Next.js, and ShadCN
TypeScript
78
star
59

amplify-with-cdk

An example project showing how to mix CDK with AWS Amplify
TypeScript
77
star
60

react-aws-live-streaming

This project shows how to implement a live-streaming platform using AWS and React
JavaScript
73
star
61

react-native-navigation-v2

Up and running with React Native Navigation - V2 - by Wix
JavaScript
73
star
62

bored-ape-yacht-club-api-and-subgraph

Graph Protocol Subgraph / API for querying Bored Ape Yacht Club NFT data with full text search
TypeScript
70
star
63

react-appsync-graphql-recipe-app

Example application using React + AWS AppSync + GraphQL
JavaScript
70
star
64

react-amplify-appsync-files-s3

An example project showing how to upload and download public and private images in GraphQL using AppSync and S3
JavaScript
70
star
65

react-strict-dom-example

JavaScript
69
star
66

full-stack-react-native-appsync-workshop

Building Full Stack GraphQL Applications with React Native & AWS AppSync
JavaScript
67
star
67

speakerchat

SpeakerChat - Real-time Event Q&A Platform with Markdown Support
JavaScript
66
star
68

react-p2p-messaging

A real-time peer-to-peer messaging app built with React & Gun.js
JavaScript
65
star
69

graphql-suspense

Lightweight component that allows you to interact with a GraphQL API using React Suspense
JavaScript
65
star
70

nuxt-supabase-full-multi-user-blog

Build a mult-user blogging app with Supabase and Nuxt.js
Vue
65
star
71

archive-forever

HTML
63
star
72

next.js-tailwind-authentication

A Next.js authentication starter built with Tailwind and AWS Amplify
JavaScript
63
star
73

near-subgraph-workshop

Building a NEAR NFT API with The Graph
60
star
74

react-authentication-in-depth

Example of User Authentication using React with React Router and AWS Amplify
JavaScript
60
star
75

graphql-api-cdk-serverless-postgres

TypeScript
59
star
76

curious-cases-of-graphql

Code and examples from my talk - Curious Cases of GraphQL
57
star
77

gasless-transactions-example

Example of Gasless Transactions with Biconomy
JavaScript
57
star
78

react-chatbots

Building Chatbots with React, Amazon Lex, AWS Lambda, & AWS Amplify
JavaScript
57
star
79

xmtp-chat-app-nextjs

Real-time encrypted chat, built with XMTP and Next.js
TypeScript
57
star
80

react-native-lens-example

Example app built with React Native Lens UI Kit
JavaScript
55
star
81

lens-protocol-workshop

Introduction to web3 social media with Next.js and Lens Protocol
TypeScript
54
star
82

zora-nextjs-app

Example Full Stack App built with Next.js, Zora, Tailwind, and The Graph
TypeScript
54
star
83

draw-together

TypeScript
53
star
84

terminal-portfolio

TypeScript
51
star
85

arweave-workshop

JavaScript
50
star
86

lens-gated-publications

Example application implementing gated Lens posts, encryption, and decryption
JavaScript
49
star
87

graphql-search

Implementing Search in GraphQL using AWS AppSync & React Apollo
JavaScript
49
star
88

basic-amplify-storage-example

A basic example app showing how to add storage with Amazon S3
JavaScript
49
star
89

production-ready-vue-authentication

How to implement a real user authentication flow in Vue with Vue Router & AWS Amplify.
Vue
48
star
90

build-an-authenticated-api-with-cdk

Workshop - Build an authenticated CDK back end
TypeScript
48
star
91

real-time-image-tracking

Real-time image tracking with React, GraphQL, and AWS AppSync
JavaScript
48
star
92

appsync-lambda-ai

Demo of using a GraphQL resolver to hit a lambda function, then hit a few AI services, and return the response.
JavaScript
47
star
93

appsync-react-native-with-user-authorization

End to end React Native + AWS AppSync GraphQL application with queries, mutations, subscriptions, & user authentication & authorization
JavaScript
47
star
94

openzeppelin-nft-api

Building NFT APIs with OpenZeppelin and The Graph
46
star
95

cryptocoven-api

Cryptocoven Graph API
TypeScript
46
star
96

transilator

Text translation and synthesization Chrome plugin
JavaScript
46
star
97

basic-serverless-api

A basic full stack example of building an API with AWS Amplify, Amazon API Gateway, AWS Lambda, and Amazon DynamoDB
JavaScript
46
star
98

xp-mobile-account-abstraction

TypeScript
45
star
99

react-native-navigator-experimental-redux

React Native Navigator Experimental with Redux
JavaScript
45
star
100

next.js-amplify-datastore

An example app using Amplify DataStore with Next.js for static site generation, pre-rendering, and SSR
JavaScript
45
star