dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
51 lines (50 loc) • 2.64 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapSchemaFormatter = mapSchemaFormatter;
const index_js_1 = require("../../../errors/index.js");
const formatArrayPath_js_1 = require("../../../schema/actions/utils/formatArrayPath.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* mapSchemaFormatter(schema, rawValue, { attributes, valuePath, ...restOptions } = {}) {
const { format = true, transform = true } = restOptions;
if (!(0, isObject_js_1.isObject)(rawValue)) {
const { type } = schema;
const path = valuePath !== undefined ? (0, formatArrayPath_js_1.formatArrayPath)(valuePath) : undefined;
throw new index_js_1.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 } = (0, utils_js_1.matchMapProjection)(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: [...(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;
}