UNPKG

dynamodb-toolbox

Version:

Lightweight and type-safe query builder for DynamoDB and TypeScript.

149 lines (148 loc) 7.61 kB
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 { ScanCommand as _ScanCommand } 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 { $options } from './constants.js'; import { scanParams } from './scanParams/index.js'; export class IScanCommand extends TableAction { constructor(table, entities = [], options = {}) { super(table, entities); this[$options] = options; } [$sentArgs]() { return [ this[$entities], /** * @debt type "Make any ScanOptions<...> instance extend base ScanOptions" */ this[$options] ]; } params() { return scanParams(this.table, ...this[$sentArgs]()); } async send(documentClientOptions) { const entityAttrSavedAs = this.table.entityAttributeSavedAs; const scanParams = 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; // NOTE: maxPages has been validated by this.params() const { attributes, maxPages = 1, showEntityAttr = false, noEntityMatchBehavior = 'THROW' } = this[$options]; let pageIndex = 0; do { pageIndex += 1; const pageScanParams = { ...scanParams, // 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 _ScanCommand(pageScanParams), 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 } : {}) }); hasEntityMatch = true; break; } catch { continue; } } if (!hasEntityMatch && noEntityMatchBehavior === 'THROW') { throw new DynamoDBToolboxError('scanCommand.noEntityMatched', { message: 'Unable to match item of unidentified entity to the ScanCommand 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 } : {}) }); } 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 } : {}) } : {}) }; } } IScanCommand.actionName = 'scan'; __decorate([ interceptable() ], IScanCommand.prototype, "send", null); export class ScanCommand extends IScanCommand { constructor(table, entities = [], options = {}) { super(table, entities, options); } entities(...nextEntities) { return new ScanCommand(this.table, nextEntities, // For some reason we can't do the same as Query (cast OPTIONS) as it triggers an infinite type compute this[$options]); } options(nextOptions) { return new ScanCommand(this.table, this[$entities], typeof nextOptions === 'function' ? nextOptions(this[$options]) : nextOptions); } }