dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
49 lines (48 loc) • 2.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.primitiveSchemaParser = primitiveSchemaParser;
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 isValidPrimitive_js_1 = require("../../../utils/validation/isValidPrimitive.js");
const utils_js_1 = require("./utils.js");
function* primitiveSchemaParser(schema, inputValue, options = {}) {
const { fill = true, transform = true, valuePath } = options;
const linkedValue = inputValue;
if (fill) {
const defaultedValue = (0, cloneDeep_js_1.cloneDeep)(inputValue);
yield defaultedValue;
const linkedValue = defaultedValue;
yield linkedValue;
}
if (!(0, isValidPrimitive_js_1.isValidPrimitive)(schema, linkedValue)) {
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: linkedValue, expected: type }
});
}
const { props } = schema;
if (props.enum !== undefined && !props.enum.includes(linkedValue)) {
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 one of: ${props.enum.map(String).join(', ')}.`,
path,
payload: { received: linkedValue, expected: props.enum }
});
}
const parsedValue = linkedValue;
(0, utils_js_1.applyCustomValidation)(schema, parsedValue, options);
if (transform) {
yield parsedValue;
}
else {
return parsedValue;
}
const transformedValue = props.transform !== undefined
? props.transform.encode(parsedValue)
: parsedValue;
return transformedValue;
}