betterddb
Version:
A definition-based DynamoDB wrapper library that provides a schema-driven and fully typesafe DAL.
76 lines • 2.98 kB
JavaScript
/* eslint-disable no-unused-vars */
import { ScanCommand, } from "@aws-sdk/lib-dynamodb";
import {} from "../betterddb.js";
import { getOperatorExpression } from "../operator.js";
import {} from "../types/paginated-result.js";
export class ScanBuilder {
parent;
filters = [];
expressionAttributeNames = {};
expressionAttributeValues = {};
limit;
lastKey;
constructor(parent) {
this.parent = parent;
}
where(attribute, operator, values) {
const attrStr = String(attribute);
const nameKey = `#attr_${attrStr}`;
this.expressionAttributeNames[nameKey] = attrStr;
if (operator === "between") {
if (!Array.isArray(values) || values.length !== 2) {
throw new Error(`For 'between' operator, values must be a tuple of two items`);
}
const valueKeyStart = `:val_start_${attrStr}`;
const valueKeyEnd = `:val_end_${attrStr}`;
this.expressionAttributeValues[valueKeyStart] = values[0];
this.expressionAttributeValues[valueKeyEnd] = values[1];
this.filters.push(`${nameKey} BETWEEN ${valueKeyStart} AND ${valueKeyEnd}`);
}
else if (operator === "begins_with" || operator === "contains") {
const valueKey = `:val_${attrStr}`;
this.expressionAttributeValues[valueKey] = values;
this.filters.push(`${operator}(${nameKey}, ${valueKey})`);
}
else {
const valueKey = `:val_${attrStr}`;
this.expressionAttributeValues[valueKey] = values;
const condition = getOperatorExpression(operator, nameKey, valueKey);
this.filters.push(condition);
}
return this;
}
limitResults(limit) {
this.limit = limit;
return this;
}
startFrom(lastKey) {
this.lastKey = lastKey;
return this;
}
/**
* Executes the scan and returns a Promise that resolves with an array of items.
*/
async execute() {
const params = {
TableName: this.parent.getTableName(),
ExpressionAttributeNames: this.expressionAttributeNames,
ExpressionAttributeValues: this.expressionAttributeValues,
Limit: this.limit,
ExclusiveStartKey: this.lastKey,
};
if (this.parent.getEntityType()) {
this.filters.push(`#entity = :entity_value`);
this.expressionAttributeNames["#entity"] = "entityType";
this.expressionAttributeValues[":entity_value"] =
this.parent.getEntityType();
}
params.FilterExpression = this.filters.join(" AND ");
const result = await this.parent.getClient().send(new ScanCommand(params));
return {
items: this.parent.getSchema().array().parse(result.Items),
lastKey: result.LastEvaluatedKey ?? undefined,
};
}
}
//# sourceMappingURL=scan-builder.js.map