UNPKG

dynamodb-toolbox

Version:

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

48 lines (47 loc) 2.44 kB
import { DynamoDBToolboxError } from '../../../errors/index.js'; import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js'; import { isObject } from '../../../utils/validation/isObject.js'; import { schemaFormatter } from './schema.js'; import { matchMapProjection } from './utils.js'; export function* mapSchemaFormatter(schema, rawValue, { attributes, valuePath, ...restOptions } = {}) { const { format = true, transform = true } = restOptions; if (!isObject(rawValue)) { const { type } = schema; const path = valuePath !== undefined ? formatArrayPath(valuePath) : undefined; throw new DynamoDBToolboxError('formatter.invalidAttribute', { message: `Invalid attribute detected while formatting${path !== undefined ? `: '${path}'` : ''}. Should be a ${type}.`, path, payload: { received: rawValue, expected: type } }); } const formatters = {}; for (const [attributeName, attribute] of Object.entries(schema.attributes)) { const { props } = attribute; const { savedAs } = props; const { isProjected, childrenAttributes } = matchMapProjection(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: [...(valuePath !== null && valuePath !== void 0 ? 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; }