@moicky/dynamodb
Version:
Contains a collection of convenience functions for working with AWS DynamoDB
63 lines (62 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeAttributes = exports.updateItem = void 0;
const client_dynamodb_1 = require("@aws-sdk/client-dynamodb");
const lib_1 = require("../lib");
async function updateItem(key, data, args) {
const argsWithDefaults = (0, lib_1.withDefaults)(args || {}, "updateItem");
if (!Object.keys(data).includes("updatedAt")) {
data = { ...data, updatedAt: Date.now() };
}
const valuesInCondition = (0, lib_1.getAttributesFromExpression)(argsWithDefaults?.ConditionExpression || "", ":");
const namesInCondition = (0, lib_1.getAttributesFromExpression)(argsWithDefaults?.ConditionExpression || "");
const attributesToUpdate = Object.keys(data).filter((key) => !valuesInCondition.includes(key));
const UpdateExpression = "SET " + attributesToUpdate.map((key) => `#${key} = :${key}`).join(", ");
// @ts-ignore
return (0, lib_1.getClient)()
.send(new client_dynamodb_1.UpdateItemCommand({
Key: (0, lib_1.stripKey)(key, argsWithDefaults),
UpdateExpression,
ExpressionAttributeValues: (0, lib_1.getAttributeValues)(data, {
attributesToGet: [...attributesToUpdate, ...valuesInCondition],
}),
ExpressionAttributeNames: (0, lib_1.getAttributeNames)(data, {
attributesToGet: [...attributesToUpdate, ...namesInCondition],
}),
...argsWithDefaults,
TableName: argsWithDefaults?.TableName || (0, lib_1.getDefaultTable)(),
}))
.then((res) => argsWithDefaults?.ReturnValues
? (0, lib_1.unmarshallWithOptions)(res.Attributes)
: undefined);
}
exports.updateItem = updateItem;
/**
* Removes specified attributes from an item in DynamoDB.
*
* @param key - The primary key of the item from which attributes should be removed
* @param {string[]} attributes - Array of attribute names to be removed
* @param args - Optional parameters for the {@link UpdateItemCommand}
* @returns Promise object representing the output of the DynamoDB UpdateItem command
*
* @example
* Remove a specific attribute from an item
* ```javascript
* await removeAttributes({ PK: "User/1", SK: "Book/1" }, ["description"]);
* ```
*/
async function removeAttributes(key, attributes, args = {}) {
args = (0, lib_1.withDefaults)(args, "removeAttributes");
const UpdateExpression = "REMOVE " + attributes.map((att) => `#${String(att)}`).join(", ");
return (0, lib_1.getClient)().send(new client_dynamodb_1.UpdateItemCommand({
Key: (0, lib_1.stripKey)(key, args),
UpdateExpression,
ExpressionAttributeNames: (0, lib_1.getAttributeNames)(attributes.reduce((acc, att) => {
acc[att] = att;
return acc;
}, {})),
...args,
TableName: args?.TableName || (0, lib_1.getDefaultTable)(),
}));
}
exports.removeAttributes = removeAttributes;