UNPKG

dynamodb-toolbox

Version:

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

46 lines (45 loc) 2.22 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.itemFormatter = itemFormatter; const index_js_1 = require("../../../errors/index.js"); const isObject_js_1 = require("../../../utils/validation/isObject.js"); const schema_js_1 = require("./schema.js"); const utils_js_1 = require("./utils.js"); function* itemFormatter(schema, rawValue, { attributes, ...restOptions } = {}) { const { format = true, transform = true } = restOptions; if (!(0, isObject_js_1.isObject)(rawValue)) { throw new index_js_1.DynamoDBToolboxError('formatter.invalidItem', { message: 'Invalid item detected while formatting. Should be an object.', payload: { received: rawValue, expected: 'Object' } }); } const formatters = {}; for (const [attributeName, attribute] of Object.entries(schema.attributes)) { const { savedAs } = attribute.props; const { isProjected, childrenAttributes } = (0, utils_js_1.matchItemProjection)(attributeName, attributes); if (!isProjected) { continue; } const attributeSavedAs = transform ? savedAs !== null && savedAs !== void 0 ? savedAs : attributeName : attributeName; formatters[attributeName] = (0, schema_js_1.schemaFormatter)(attribute, rawValue[attributeSavedAs], { attributes: childrenAttributes, valuePath: [attributeSavedAs], ...restOptions }); } if (transform) { const transformedValue = Object.fromEntries(Object.entries(formatters) .map(([attrName, formatter]) => [attrName, formatter.next().value]) .filter(([, attrValue]) => attrValue !== undefined)); if (format) { yield transformedValue; } else { return transformedValue; } } const formattedValue = Object.fromEntries(Object.entries(formatters) .map(([attrName, formatter]) => [attrName, formatter.next().value]) .filter(([attrName, attrValue]) => { var _a; return ((_a = schema.attributes[attrName]) === null || _a === void 0 ? void 0 : _a.props.hidden) !== true && attrValue !== undefined; })); return formattedValue; }