UNPKG

@moicky/dynamodb

Version:

Contains a collection of convenience functions for working with AWS DynamoDB

87 lines (86 loc) 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.putItems = exports.putItem = void 0; const client_dynamodb_1 = require("@aws-sdk/client-dynamodb"); const lib_1 = require("../lib"); async function putItem(item, args) { const argsWithDefaults = (0, lib_1.withDefaults)(args || {}, "putItem"); if (!Object.keys(item).includes("createdAt")) { item = { ...item, createdAt: Date.now() }; } const { ReturnValues, ...otherArgs } = argsWithDefaults; return (0, lib_1.getClient)() .send(new client_dynamodb_1.PutItemCommand({ Item: (0, lib_1.marshallWithOptions)(item), ...otherArgs, ...(ReturnValues && ReturnValues !== "ALL_NEW" && { ReturnValues }), TableName: otherArgs?.TableName || (0, lib_1.getDefaultTable)(), })) .then((res) => ReturnValues ? ReturnValues === "ALL_NEW" ? item : (0, lib_1.unmarshallWithOptions)(res?.Attributes) : res); } exports.putItem = putItem; /** * Inserts multiple items into the DynamoDB table. * @param items - The items to insert into the table. * @param args - The additional arguments to override or specify for {@link PutItemsArgs} * @returns A promise that resolves to an array of {@link BatchWriteItemCommandOutput} * * @example * Put multiple items into DynamoDB * ```javascript * await putItems([ * { * PK: "User/1", * SK: "Book/1", * title: "The Great Gatsby", * author: "F. Scott Fitzgerald", * released: 1925, * }, * // ... infinite more items (will be grouped into batches of 25 due to aws limit) * ]); * ``` */ async function putItems(items, args = {}, retry = 0) { if (retry > 3) return; args = (0, lib_1.withDefaults)(args, "putItems"); return new Promise(async (resolve, reject) => { const now = Date.now(); const batches = (0, lib_1.splitEvery)(items.map((item) => ({ ...item, createdAt: item?.createdAt ?? now, }))); const results = []; const table = args?.TableName || (0, lib_1.getDefaultTable)(); for (const batch of batches) { await (0, lib_1.getClient)() .send(new client_dynamodb_1.BatchWriteItemCommand({ RequestItems: { [table]: batch.map((item) => ({ PutRequest: { Item: (0, lib_1.marshallWithOptions)(item), }, })), }, ...args, })) .then((res) => { results.push(res); if (res?.UnprocessedItems?.[table]?.length) { if (retry + 1 < 3) { reject(res); return; } return putItems(res.UnprocessedItems[table].map((item) => (0, lib_1.unmarshallWithOptions)(item.PutRequest.Item)), { ...args, TableName: table }, retry + 1); } }) .catch(reject); } resolve(results); }); } exports.putItems = putItems;