UNPKG

dynamodb-toolbox

Version:

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

56 lines (55 loc) 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EntityFormatter = void 0; const index_js_1 = require("../../../entity/index.js"); const index_js_2 = require("../../../entity/utils/index.js"); const index_js_3 = require("../../../errors/index.js"); const index_js_4 = require("../../../schema/actions/format/index.js"); const constants_js_1 = require("./constants.js"); class EntityFormatter extends index_js_1.EntityAction { constructor(entity) { super(entity); this[constants_js_1.$formatter] = new index_js_4.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 : (0, index_js_2.getEntityAttrOptionValue)(entityAttribute, 'name'); const addEntityAttr = (0, index_js_2.isEntityAttrEnabled)(entityAttribute) && item[entityAttrName] === undefined; try { const formatter = this[constants_js_1.$formatter].start({ ...item, ...(addEntityAttr ? { [entityAttrName]: entityName } : {}) }, { ...options, format: true }); if (transform) { formatter.next(); // transformed } const formattedItem = formatter.next().value; return formattedItem; } catch (error) { if (!index_js_3.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; } } } exports.EntityFormatter = EntityFormatter;