UNPKG

betterddb

Version:

A definition-based DynamoDB wrapper library that provides a schema-driven and fully typesafe DAL.

76 lines 2.67 kB
/* eslint-disable no-unused-vars */ import {} from "../betterddb.js"; import { TransactGetCommand, GetCommand } from "@aws-sdk/lib-dynamodb"; import {} from "@aws-sdk/client-dynamodb"; export class GetBuilder { parent; key; projectionExpression; expressionAttributeNames = {}; extraTransactItems = []; constructor(parent, key) { this.parent = parent; this.key = key; } /** * Specify a projection by providing an array of attribute names. */ withProjection(attributes) { this.projectionExpression = attributes .map((attr) => `#${String(attr)}`) .join(", "); for (const attr of attributes) { this.expressionAttributeNames[`#${String(attr)}`] = String(attr); } return this; } async execute() { if (this.extraTransactItems.length > 0) { // Build our update transaction item. const myTransactItem = this.toTransactGet(); // Combine with extra transaction items. const allItems = [...this.extraTransactItems, myTransactItem]; await this.parent.getClient().send(new TransactGetCommand({ TransactItems: allItems, })); // After transaction, retrieve the updated item. const result = await this.parent.get(this.key).execute(); return result; } else { const params = { TableName: this.parent.getTableName(), Key: this.parent.buildKey(this.key), }; if (this.projectionExpression) { params.ProjectionExpression = this.projectionExpression; params.ExpressionAttributeNames = this.expressionAttributeNames; } const result = await this.parent.getClient().send(new GetCommand(params)); if (!result.Item) return null; return this.parent.getSchema().parse(result.Item); } } transactGet(ops) { if (Array.isArray(ops)) { this.extraTransactItems.push(...ops); } else { this.extraTransactItems.push(ops); } return this; } toTransactGet() { const getItem = { TableName: this.parent.getTableName(), Key: this.parent.buildKey(this.key), }; if (this.projectionExpression) { getItem.ProjectionExpression = this.projectionExpression; getItem.ExpressionAttributeNames = this.expressionAttributeNames; } return { Get: getItem }; } } //# sourceMappingURL=get-builder.js.map