UNPKG

dynamodb-toolbox

Version:

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

43 lines (42 loc) 2.06 kB
import { DynamoDBToolboxError } from '../../../errors/index.js'; import { isObject } from '../../../utils/validation/isObject.js'; import { schemaFormatter } from './schema.js'; import { matchItemProjection } from './utils.js'; export function* itemFormatter(schema, rawValue, { attributes, ...restOptions } = {}) { const { format = true, transform = true } = restOptions; if (!isObject(rawValue)) { throw new 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 } = matchItemProjection(attributeName, attributes); if (!isProjected) { continue; } const attributeSavedAs = transform ? savedAs !== null && savedAs !== void 0 ? savedAs : attributeName : attributeName; formatters[attributeName] = 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; }