Last active
June 24, 2020 03:58
-
-
Save jooeycheng/54f38aa91c4b7fc05263ea2d7120ce29 to your computer and use it in GitHub Desktop.
NodeJS DynamoDB Cheat Sheet (straight to the point!)
This file contains 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
// Simplified from https://github.com/dabit3/dynamodb-documentclient-cheat-sheet | |
/** | |
* DynamoDB.DocumentClient | |
*/ | |
const dynamoDbClient = new AWS.DynamoDB.DocumentClient({ | |
region: 'ap-southeast-1', | |
convertEmptyValues: true, | |
httpOptions: { | |
connectTimeout: 1000, // 1s | |
timeout: 100, // 100ms | |
}, | |
}) | |
/** | |
* Query | |
*/ | |
const params = { | |
TableName: 'table-name', | |
IndexName: 'optional-gsi-name', | |
Limit: 10, | |
ScanIndexForward: false, // order sk in desc order | |
KeyConditionExpression: 'pk = :pk and begins_with(gsi2sk, :gsi2sk)', | |
ExpressionAttributeValues: { ':pk': 'pk-value', ':gsi2sk': 'sk-value' }, | |
} | |
const data = await dynamoDbClient.query(params).promise() | |
const items = data.Items | |
/** | |
* Get | |
*/ | |
const params = { | |
TableName: 'table-name', | |
Key: { | |
pk: 'pk-value', | |
sk: 'sk-value', | |
}, | |
} | |
const data = await dynamoDbClient.get(params).promise() | |
const item = data.Item | |
/** | |
* Update | |
*/ | |
const params = { | |
TableName: 'table-name', | |
Key: { pk: 'pk-value', sk: 'sk-value' }, | |
UpdateExpression: 'set someAttrName = :someAttrName', | |
ExpressionAttributeValues: { ':someAttrName': 'new-attr-value' }, | |
} | |
await dynamoDbClient.update(item).promise() | |
/** | |
* Update (if attr name is a DynamoDB reserved keyword) | |
* | |
* Set an alias "#someAttrName" to the actual key name ":someAttrName". | |
* DynamoDB will automatically translate it accordingly. | |
*/ | |
const params = { | |
TableName: 'table-name', | |
Key: { pk: 'pk-value', sk: 'sk-value' }, | |
UpdateExpression: 'set #someAttrName = :someAttrName', | |
KeyConditionExpression: { '#someAttrName': ':someAttrName' }, | |
ExpressionAttributeNames: { '#someAttrName': 'someAttrName' }, | |
ExpressionAttributeValues: { ':someAttrName': 'new-attr-value' }, | |
} | |
await dynamoDbClient.update(item).promise() | |
/** | |
* BatchGet | |
*/ | |
const params = { | |
RequestItems: { | |
'table-name': { | |
Keys: [ | |
{ pk: 'pk-value', sk: 'sk-value-1' }, | |
{ pk: 'pk-value', sk: 'sk-value-2' }, | |
], | |
}, | |
}, | |
} | |
const data = await dynamoDbClient.batchGet(params).promise() | |
const items = data.Responses['table-name'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment