dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
46 lines (45 loc) • 1.99 kB
JavaScript
import { DynamoDBToolboxError } from '../../../errors/index.js';
import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js';
import { cloneDeep } from '../../../utils/cloneDeep.js';
import { isValidPrimitive } from '../../../utils/validation/isValidPrimitive.js';
import { applyCustomValidation } from './utils.js';
export function* primitiveSchemaParser(schema, inputValue, options = {}) {
const { fill = true, transform = true, valuePath } = options;
const linkedValue = inputValue;
if (fill) {
const defaultedValue = cloneDeep(inputValue);
yield defaultedValue;
const linkedValue = defaultedValue;
yield linkedValue;
}
if (!isValidPrimitive(schema, linkedValue)) {
const { type } = schema;
const path = valuePath !== undefined ? formatArrayPath(valuePath) : undefined;
throw new 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 ? formatArrayPath(valuePath) : undefined;
throw new 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;
applyCustomValidation(schema, parsedValue, options);
if (transform) {
yield parsedValue;
}
else {
return parsedValue;
}
const transformedValue = props.transform !== undefined
? props.transform.encode(parsedValue)
: parsedValue;
return transformedValue;
}