UNPKG

dynamodb-toolbox

Version:

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

52 lines (51 loc) 2.32 kB
import { EntityAction } from '../../../entity/index.js'; import { getEntityAttrOptionValue, isEntityAttrEnabled } from '../../../entity/utils/index.js'; import { DynamoDBToolboxError } from '../../../errors/index.js'; import { Formatter } from '../../../schema/actions/format/index.js'; import { $formatter } from './constants.js'; export class EntityFormatter extends EntityAction { constructor(entity) { super(entity); this[$formatter] = new Formatter(entity.schema); } format(item, options = {}) { const { transform = true } = options; const { table, entityAttribute, entityName } = this.entity; const { entityAttributeSavedAs } = table; /** * @debt refactor "Simply use readDefault on entityAttr once available" */ const entityAttrName = transform ? entityAttributeSavedAs : getEntityAttrOptionValue(entityAttribute, 'name'); const addEntityAttr = isEntityAttrEnabled(entityAttribute) && item[entityAttrName] === undefined; try { const formatter = this[$formatter].start({ ...item, ...(addEntityAttr ? { [entityAttrName]: entityName } : {}) }, { ...options, format: true }); if (transform) { formatter.next(); // transformed } const formattedItem = formatter.next().value; return formattedItem; } catch (error) { if (!DynamoDBToolboxError.match(error, 'formatter.')) throw error; const partitionKey = item[this.entity.table.partitionKey.name]; const sortKey = this.entity.table.sortKey && item[this.entity.table.sortKey.name]; if (partitionKey === undefined && sortKey === undefined) { throw error; } const itemPrimaryKeyMessage = partitionKey && [ partitionKey && `Partition key: ${String(partitionKey)}`, sortKey && `Sort key: ${String(sortKey)}` ] .filter(Boolean) .join(' / '); error.message += ` ${itemPrimaryKeyMessage}`; error.payload.partitionKey = partitionKey; error.payload.sortKey = sortKey; throw error; } } }