dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
160 lines (159 loc) • 8.26 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { QueryCommand as _QueryCommand } from '@aws-sdk/lib-dynamodb';
import { EntityFormatter } from '../../../entity/actions/format/index.js';
import { getEntityAttrOptionValue, isEntityAttrEnabled } from '../../../entity/utils/index.js';
import { DynamoDBToolboxError } from '../../../errors/index.js';
import { $sentArgs } from '../../../table/constants.js';
import { interceptable } from '../../../table/decorator.js';
import { $entities, TableAction } from '../../../table/index.js';
import { isString } from '../../../utils/validation/isString.js';
import { $entity, $options, $query } from './constants.js';
import { queryParams } from './queryParams/index.js';
export class IQueryCommand extends TableAction {
constructor(table, entities = [], query, options = {}) {
super(table, entities);
this.params = () => {
return queryParams(this.table, ...this[$sentArgs]());
};
this[$query] = query;
this[$options] = options;
}
[$sentArgs]() {
if (!this[$query]) {
throw new DynamoDBToolboxError('actions.incompleteAction', {
message: 'QueryCommand incomplete: Missing "query" property'
});
}
return [
this[$entities],
this[$query],
/**
* @debt type "Make any QueryOptions<...> instance extend base QueryOptions"
*/
this[$options]
];
}
async send(documentClientOptions) {
const entityAttrSavedAs = this.table.entityAttributeSavedAs;
const queryParams = this.params();
const formattersByName = {};
this[$entities].forEach(entity => {
formattersByName[entity.entityName] = entity.build(EntityFormatter);
});
const formattedItems = [];
let lastEvaluatedKey = undefined;
let count = 0;
let scannedCount = 0;
let consumedCapacity = undefined;
let responseMetadata = undefined;
const { attributes, maxPages = 1, showEntityAttr = false, tagEntities = false, noEntityMatchBehavior = 'THROW' } = this[$options];
let pageIndex = 0;
do {
pageIndex += 1;
const pageQueryParams = {
...queryParams,
// NOTE: Important NOT to override initial exclusiveStartKey on first page
...(lastEvaluatedKey !== undefined ? { ExclusiveStartKey: lastEvaluatedKey } : {})
};
const { Items: items = [], LastEvaluatedKey: pageLastEvaluatedKey, Count: pageCount, ScannedCount: pageScannedCount, ConsumedCapacity: pageConsumedCapacity, $metadata: pageMetadata } = await this.table
.getDocumentClient()
.send(new _QueryCommand(pageQueryParams), documentClientOptions);
for (const item of items) {
if (this[$entities].length === 0) {
formattedItems.push(item);
continue;
}
const itemEntityName = item[entityAttrSavedAs];
const itemEntityFormatter = isString(itemEntityName)
? formattersByName[itemEntityName]
: undefined;
if (itemEntityFormatter === undefined) {
let hasEntityMatch = false;
// If data doesn't contain entity name (e.g. migrating to DynamoDB-Toolbox), we try all formatters
// (NOTE: Can only happen if `entityAttrFilter` is false)
for (const [entityName, formatter] of Object.entries(formattersByName)) {
try {
const formattedItem = formatter.format(item, { attributes });
const { entityAttribute } = formatter.entity;
const entityAttrName = getEntityAttrOptionValue(entityAttribute, 'name');
const addEntityAttr = showEntityAttr && isEntityAttrEnabled(entityAttribute);
formattedItems.push({
...formattedItem,
...(addEntityAttr ? { [entityAttrName]: entityName } : {}),
// $entity symbol is useful for the DeletePartition command
...(tagEntities ? { [$entity]: entityName } : {})
});
hasEntityMatch = true;
break;
}
catch {
continue;
}
}
if (!hasEntityMatch && noEntityMatchBehavior === 'THROW') {
throw new DynamoDBToolboxError('queryCommand.noEntityMatched', {
message: 'Unable to match item of unidentified entity to the QueryCommand entities',
payload: { item }
});
}
continue;
}
const formattedItem = itemEntityFormatter.format(item, { attributes });
const { entityAttribute, entityName } = itemEntityFormatter.entity;
const entityAttrName = getEntityAttrOptionValue(entityAttribute, 'name');
const addEntityAttr = showEntityAttr && isEntityAttrEnabled(entityAttribute);
formattedItems.push({
...formattedItem,
...(addEntityAttr ? { [entityAttrName]: entityName } : {}),
// $entity symbol is useful for the DeletePartition command
...(tagEntities ? { [$entity]: entityName } : {})
});
}
lastEvaluatedKey = pageLastEvaluatedKey;
if (count !== undefined) {
count = pageCount !== undefined ? count + pageCount : undefined;
}
if (scannedCount !== undefined) {
scannedCount = pageScannedCount !== undefined ? scannedCount + pageScannedCount : undefined;
}
consumedCapacity = pageConsumedCapacity;
responseMetadata = pageMetadata;
} while (pageIndex < maxPages && lastEvaluatedKey !== undefined);
return {
Items: formattedItems,
...(lastEvaluatedKey !== undefined ? { LastEvaluatedKey: lastEvaluatedKey } : {}),
...(count !== undefined ? { Count: count } : {}),
...(scannedCount !== undefined ? { ScannedCount: scannedCount } : {}),
// return ConsumedCapacity & $metadata only if one page has been fetched
...(pageIndex === 1
? {
...(consumedCapacity !== undefined ? { ConsumedCapacity: consumedCapacity } : {}),
...(responseMetadata !== undefined ? { $metadata: responseMetadata } : {})
}
: {})
};
}
}
IQueryCommand.actionName = 'query';
__decorate([
interceptable()
], IQueryCommand.prototype, "send", null);
export class QueryCommand extends IQueryCommand {
constructor(table, entities = [], query, options = {}) {
super(table, entities, query, options);
}
entities(...nextEntities) {
return new QueryCommand(this.table, nextEntities, this[$query], this[$options]);
}
query(nextQuery) {
return new QueryCommand(this.table, this[$entities], nextQuery, this[$options]);
}
options(nextOptions) {
return new QueryCommand(this.table, this[$entities], this[$query], typeof nextOptions === 'function' ? nextOptions(this[$options]) : nextOptions);
}
}