Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
@aws-sdk/lib-dynamodb
Advanced tools
The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values.
The @aws-sdk/lib-dynamodb package is a library that provides a simpler interface for interacting with Amazon DynamoDB from JavaScript applications. It is part of the AWS SDK for JavaScript (v3) and offers an abstraction over the lower-level DynamoDB client, making it easier to work with DynamoDB using JavaScript objects and syntax.
Performing CRUD Operations
This feature allows you to create, read, update, and delete items in a DynamoDB table. The code sample demonstrates how to insert an item into a DynamoDB table using the PutCommand.
{"PutCommand": "const { DynamoDBDocumentClient, PutCommand } = require('@aws-sdk/lib-dynamodb'); const client = DynamoDBDocumentClient.from(new DynamoDBClient({})); const putCommand = new PutCommand({ TableName: 'MyTable', Item: { id: '1', content: 'example' } }); client.send(putCommand);"}
Querying and Scanning Tables
This feature allows you to query items using a key condition expression or scan the entire table. The code sample shows how to query items from a DynamoDB table where the 'id' attribute matches a specific value.
{"QueryCommand": "const { DynamoDBDocumentClient, QueryCommand } = require('@aws-sdk/lib-dynamodb'); const client = DynamoDBDocumentClient.from(new DynamoDBClient({})); const queryCommand = new QueryCommand({ TableName: 'MyTable', KeyConditionExpression: 'id = :id', ExpressionAttributeValues: { ':id': '1' } }); client.send(queryCommand);"}
Batch Operations
This feature allows you to perform batch operations, such as batch writes (put and delete), on multiple items across one or more tables. The code sample demonstrates how to perform a batch write operation to put and delete items in a DynamoDB table.
{"BatchWriteCommand": "const { DynamoDBDocumentClient, BatchWriteCommand } = require('@aws-sdk/lib-dynamodb'); const client = DynamoDBDocumentClient.from(new DynamoDBClient({})); const batchWriteCommand = new BatchWriteCommand({ RequestItems: { 'MyTable': [ { PutRequest: { Item: { id: '2', content: 'example2' } } }, { DeleteRequest: { Key: { id: '3' } } } ] } }); client.send(batchWriteCommand);"}
Transaction Support
This feature allows you to perform multiple put, update, and delete operations across multiple tables atomically. The code sample shows how to use the TransactWriteItemsCommand to perform atomic transactions in DynamoDB.
{"TransactWriteItemsCommand": "const { DynamoDBDocumentClient, TransactWriteItemsCommand } = require('@aws-sdk/lib-dynamodb'); const client = DynamoDBDocumentClient.from(new DynamoDBClient({})); const transactWriteItemsCommand = new TransactWriteItemsCommand({ TransactItems: [ { Put: { TableName: 'MyTable', Item: { id: '4', content: 'example4' } } }, { Delete: { TableName: 'MyTable', Key: { id: '5' } } } ] }); client.send(transactWriteItemsCommand);"}
Dynamoose is a modeling tool for Amazon DynamoDB that provides a higher-level abstraction than @aws-sdk/lib-dynamodb. It offers features like schema definition, validation, and more complex query capabilities. It is designed to be similar to Mongoose, which is a modeling tool for MongoDB.
Dynamo-types is a TypeScript library that provides a strong-typed way to define models for DynamoDB tables. It offers decorators to define table schemas and is built on top of the AWS SDK. It is more TypeScript-oriented compared to @aws-sdk/lib-dynamodb, which is more JavaScript-focused.
The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types.
The document client affords developers the use of native JavaScript types
instead of AttributeValue
s to simplify the JavaScript development
experience with Amazon DynamoDB. JavaScript objects passed in as parameters
are marshalled into AttributeValue
shapes required by Amazon DynamoDB.
Responses from DynamoDB are unmarshalled into plain JavaScript objects
by the DocumentClient
. The DocumentClient
does not accept
AttributeValue
s in favor of native JavaScript types.
JavaScript Type | DynamoDB AttributeValue |
---|---|
String | S |
Number / BigInt / NumberValue | N |
Boolean | BOOL |
null | NULL |
Array | L |
Object | M |
Set<Uint8Array, Blob, ...> | BS |
Set<Number, BigInt, NumberValue> | NS |
Set<String> | SS |
Uint8Array, Buffer, File, Blob... | B |
Here is an example list which is sent to DynamoDB client in an operation:
{ "L": [{ "NULL": true }, { "BOOL": false }, { "N": 1 }, { "S": "two" }] }
The DynamoDB document client abstracts the attribute values as follows in both input and output:
[null, false, 1, "two"]
To create document client, you need to create DynamoDB client first as follows:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // ES6 import
// const { DynamoDBClient } = require("@aws-sdk/client-dynamodb"); // CommonJS import
// Bare-bones DynamoDB Client
const client = new DynamoDBClient({});
import { DynamoDB } from "@aws-sdk/client-dynamodb"; // ES6 import
// const { DynamoDB } = require("@aws-sdk/client-dynamodb"); // CommonJS import
// Full DynamoDB Client
const client = new DynamoDB({});
The bare-bones clients are more modular. They reduce bundle size and improve loading performance over full clients as explained in blog post on modular packages in AWS SDK for JavaScript.
Once DynamoDB client is created, you can either create the bare-bones document client or full document client as follows:
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; // ES6 import
// const { DynamoDBDocumentClient } = require("@aws-sdk/lib-dynamodb"); // CommonJS import
// Bare-bones document client
const ddbDocClient = DynamoDBDocumentClient.from(client); // client is DynamoDB client
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb"; // ES6 import
// const { DynamoDBDocument } = require("@aws-sdk/lib-dynamodb"); // CommonJS import
// Full document client
const ddbDocClient = DynamoDBDocument.from(client); // client is DynamoDB client
The configuration for marshalling and unmarshalling can be sent as an optional second parameter during creation of document client as follows:
export interface marshallOptions {
/**
* Whether to automatically convert empty strings, blobs, and sets to `null`
*/
convertEmptyValues?: boolean;
/**
* Whether to remove undefined values while marshalling.
*/
removeUndefinedValues?: boolean;
/**
* Whether to convert typeof object to map attribute.
*/
convertClassInstanceToMap?: boolean;
/**
* Whether to convert the top level container
* if it is a map or list.
*
* Default is true when using the DynamoDBDocumentClient,
* but false if directly using the marshall function (backwards compatibility).
*/
convertTopLevelContainer?: boolean;
}
export interface unmarshallOptions {
/**
* Whether to return numbers as a string instead of converting them to native JavaScript numbers.
* This allows for the safe round-trip transport of numbers of arbitrary size.
*/
wrapNumbers?: boolean;
/**
* When true, skip wrapping the data in `{ M: data }` before converting.
*
* Default is true when using the DynamoDBDocumentClient,
* but false if directly using the unmarshall function (backwards compatibility).
*/
convertWithoutMapWrapper?: boolean;
}
const marshallOptions: marshallOptions = {};
const unmarshallOptions: unmarshallOptions = {};
const translateConfig = { marshallOptions, unmarshallOptions };
const client = new DynamoDBClient({});
const ddbDocClient = DynamoDBDocument.from(client, translateConfig);
You can call the document client operations using command objects on bare-bones client as follows:
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
// ... DynamoDB client creation
const ddbDocClient = DynamoDBDocumentClient.from(client);
// Call using bare-bones client and Command object.
await ddbDocClient.send(
new PutCommand({
TableName,
Item: {
id: "1",
content: "content from DynamoDBDocumentClient",
},
})
);
You can also call operations on full client as follows:
import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
// ... DynamoDB client creation
const ddbDocClient = DynamoDBDocument.from(client);
// Call using full client.
await ddbDocClient.put({
TableName,
Item: {
id: "2",
content: "content from DynamoDBDocument",
},
});
NumberValue
.On the input or marshalling side, the class NumberValue
can be used
anywhere to represent a DynamoDB number value, even small numbers.
import { DynamoDB } from "@aws-sdk/client-dynamodb";
import { NumberValue, DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
// Note, the client will not validate the acceptability of the number
// in terms of size or format.
// It is only here to preserve your precise representation.
const client = DynamoDBDocument.from(new DynamoDB({}));
await client.put({
Item: {
id: 1,
smallNumber: NumberValue.from("123"),
bigNumber: NumberValue.from("1000000000000000000000.000000000001"),
nSet: new Set([123, NumberValue.from("456"), 789]),
},
});
On the output or unmarshalling side, the class NumberValue
is used
depending on your setting for the unmarshallOptions
flag wrapnumbers
,
shown above.
import { DynamoDB } from "@aws-sdk/client-dynamodb";
import { NumberValue, DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocument.from(new DynamoDB({}));
const response = await client.get({
Key: {
id: 1,
},
});
/**
* Numbers in the response may be a number, a BigInt, or a NumberValue depending
* on how you set `wrapNumbers`.
*/
const value = response.Item.bigNumber;
NumberValue
does not provide a way to do mathematical operations on itself.
To do mathematical operations, take the string value of NumberValue
by calling
.toString()
and supply it to your chosen big number implementation.
As with other AWS SDK for JavaScript v3 clients, you can apply middleware functions
both on the client itself and individual Command
s.
For individual Command
s, here are examples of how to add middleware before and after
both marshalling and unmarshalling. We will use QueryCommand
as an example.
Others follow the same pattern.
import { DynamoDBDocumentClient, QueryCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({
/*...*/
});
const doc = DynamoDBDocumentClient.from(client);
const command = new QueryCommand({
/*...*/
});
Before and after marshalling:
command.middlewareStack.addRelativeTo(
(next) => async (args) => {
console.log("pre-marshall", args.input);
return next(args);
},
{
relation: "before",
toMiddleware: "DocumentMarshall",
}
);
command.middlewareStack.addRelativeTo(
(next) => async (args) => {
console.log("post-marshall", args.input);
return next(args);
},
{
relation: "after",
toMiddleware: "DocumentMarshall",
}
);
Before and after unmarshalling:
command.middlewareStack.addRelativeTo(
(next) => async (args) => {
const result = await next(args);
console.log("pre-unmarshall", result.output.Items);
return result;
},
{
relation: "after", // <- after for pre-unmarshall
toMiddleware: "DocumentUnmarshall",
}
);
command.middlewareStack.addRelativeTo(
(next) => async (args) => {
const result = await next(args);
console.log("post-unmarshall", result.output.Items);
return result;
},
{
relation: "before", // <- before for post-unmarshall
toMiddleware: "DocumentUnmarshall",
}
);
The destroy()
call on document client is a no-op as document client does not
create a new DynamoDB client. You need to call destroy()
on DynamoDB client to
clean resources used by it as shown below.
const client = new DynamoDBClient({});
const ddbDocClient = DynamoDBDocumentClient.from(client);
// Perform operations on document client.
ddbDocClient.destroy(); // no-op
client.destroy(); // destroys DynamoDBClient
3.614.0 (2024-07-10)
FAQs
The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values.
The npm package @aws-sdk/lib-dynamodb receives a total of 996,256 weekly downloads. As such, @aws-sdk/lib-dynamodb popularity was classified as popular.
We found that @aws-sdk/lib-dynamodb demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.