dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
71 lines (70 loc) • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.anyOfSchemaFormatter = anyOfSchemaFormatter;
const index_js_1 = require("../../../errors/index.js");
const formatArrayPath_js_1 = require("../../../schema/actions/utils/formatArrayPath.js");
const constants_js_1 = require("../../../schema/anyOf/constants.js");
const isObject_js_1 = require("../../../utils/validation/isObject.js");
const isString_js_1 = require("../../../utils/validation/isString.js");
const schema_js_1 = require("./schema.js");
function* anyOfSchemaFormatter(schema, rawValue, options = {}) {
const { discriminator } = schema.props;
const { format = true, transform = true, valuePath } = options;
let formatter = undefined;
let _transformedValue = undefined;
let _formattedValue = undefined;
const discriminatorSavedAs = discriminator && transform ? schema[constants_js_1.$discriminators][discriminator] : discriminator;
if (discriminatorSavedAs !== undefined &&
(0, isObject_js_1.isObject)(rawValue) &&
discriminatorSavedAs in rawValue) {
const discriminatorValue = rawValue[discriminatorSavedAs];
const matchingElement = (0, isString_js_1.isString)(discriminatorValue)
? schema.match(discriminatorValue)
: undefined;
if (matchingElement !== undefined) {
formatter = (0, schema_js_1.schemaFormatter)(matchingElement, rawValue, options);
if (transform) {
_transformedValue = formatter.next().value;
}
if (format) {
_formattedValue = formatter.next().value;
}
}
}
if (formatter === undefined) {
for (const element of schema.elements) {
try {
formatter = (0, schema_js_1.schemaFormatter)(element, rawValue, options);
if (transform) {
_transformedValue = formatter.next().value;
}
if (format) {
_formattedValue = formatter.next().value;
}
break;
}
catch (error) {
continue;
}
}
}
const transformedValue = _transformedValue;
const formattedValue = _formattedValue;
if ((transform && transformedValue === undefined) || (format && formattedValue === undefined)) {
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. Attribute does not match any of the possible sub-types${path !== undefined ? `: '${path}'` : ''}.`,
path,
payload: { received: rawValue }
});
}
if (transform) {
if (format) {
yield transformedValue;
}
else {
return transformedValue;
}
}
return formattedValue;
}