@moicky/dynamodb
Version:
Contains a collection of convenience functions for working with AWS DynamoDB
71 lines (70 loc) • 2.91 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.transactGetItems = void 0;
const client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
const lib_1 = require("../lib");
/**
* Performs a TransactGetItems operation against DynamoDB. This allows you to retrieve many items at once.
* @param keys - Array of items to retrieve. Each item requires a `key` property, with at least the partition and the sort key (according to the table definition).
* @param args - The additional arguments to override or specify for {@link TransactGetItemsCommandInput}
* @returns A promise that resolves to an unmarshalled items array
*
* @example
* Get items from the default-table
* ```javascript
* const items = await transactGetItems([
* { key: { PK: "User/1", SK: "Book/1", title: "The Great Gatsby", released: 1925 }},
* { key: { PK: "User/1", SK: "Book/2" }},
* { key: { PK: "User/1", SK: "Book/3" }},
* ]);
* ```
* @example
* Get items from a different tables
* ```javascript
* const items = await transactGetItems([
* { TableName: "yourTable", key: { PK: "User/1", SK: "Book/2" }},
* { TableName: "yourOtherTable", key: { PK: "User/1", SK: "Book/3" }},
* ]);
* ```
* @example
* Get all items from a non-default table
* ```javascript
* const items = await transactGetItems(
* [
* { key: { PK: "User/1", SK: "Book/2" } },
* { key: { PK: "User/1", SK: "Book/3" } },
* ],
* { TableName: "yourTable" }
* );
* ```
*/
function transactGetItems(keys, args) {
return new Promise(async (resolve, reject) => {
args = (0, lib_1.withDefaults)(args, "transactGetItems");
const { TableName, ...otherArgs } = args;
const defaultTable = TableName || (0, lib_1.getDefaultTable)();
const batches = (0, lib_1.splitEvery)(keys, 100);
const results = [];
for (const batch of batches) {
await (0, lib_1.getClient)()
.send(new client_dynamodb_1.TransactGetItemsCommand({
TransactItems: batch.map((item) => {
const table = item.TableName || defaultTable;
return {
Get: {
Key: (0, lib_1.stripKey)(item.key, { TableName: table }),
TableName: table,
ExpressionAttributeNames: item.ExpressionAttributeNames,
ProjectionExpression: item.ProjectionExpression,
},
};
}),
...otherArgs,
}))
.then((res) => results.push(res))
.catch(reject);
}
resolve(results.flatMap((result) => result.Responses?.map((item) => item?.Item ? (0, lib_1.unmarshallWithOptions)(item.Item) : undefined) || []));
});
}
exports.transactGetItems = transactGetItems;