dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
58 lines (57 loc) • 2.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.setSchemaParser = setSchemaParser;
const index_js_1 = require("../../../errors/index.js");
const formatArrayPath_js_1 = require("../../../schema/actions/utils/formatArrayPath.js");
const cloneDeep_js_1 = require("../../../utils/cloneDeep.js");
const isSet_js_1 = require("../../../utils/validation/isSet.js");
const schema_js_1 = require("./schema.js");
const utils_js_1 = require("./utils.js");
function* setSchemaParser(schema, inputValue, options = {}) {
const { valuePath, ...restOptions } = options;
const { fill = true, transform = true } = restOptions;
let parsers = [];
const isInputValueSet = (0, isSet_js_1.isSet)(inputValue);
if (isInputValueSet) {
parsers = [...inputValue.values()].map((element, index) => (0, schema_js_1.schemaParser)(schema.elements, element, {
...restOptions,
valuePath: [...(valuePath !== null && valuePath !== void 0 ? valuePath : []), index],
defined: false
}));
}
if (fill) {
if (isInputValueSet) {
const defaultedValue = new Set(parsers.map(parser => parser.next().value));
yield defaultedValue;
const linkedValue = new Set(parsers.map(parser => parser.next().value));
yield linkedValue;
}
else {
const defaultedValue = (0, cloneDeep_js_1.cloneDeep)(inputValue);
yield defaultedValue;
const linkedValue = defaultedValue;
yield linkedValue;
}
}
if (!isInputValueSet) {
const { type } = schema;
const path = valuePath !== undefined ? (0, formatArrayPath_js_1.formatArrayPath)(valuePath) : undefined;
throw new index_js_1.DynamoDBToolboxError('parsing.invalidAttributeInput', {
message: `Attribute${path !== undefined ? ` '${path}'` : ''} should be a ${type}.`,
path,
payload: { received: inputValue, expected: type }
});
}
const parsedValue = new Set(parsers.map(parser => parser.next().value));
if (parsedValue !== undefined) {
(0, utils_js_1.applyCustomValidation)(schema, parsedValue, options);
}
if (transform) {
yield parsedValue;
}
else {
return parsedValue;
}
const transformedValue = new Set(parsers.map(parser => parser.next().value));
return transformedValue;
}