dynamodb-toolbox
Version:
Lightweight and type-safe query builder for DynamoDB and TypeScript.
34 lines (33 loc) • 1.58 kB
JavaScript
import { DynamoDBToolboxError } from '../../../errors/index.js';
import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js';
import { isSet } from '../../../utils/validation/isSet.js';
import { schemaFormatter } from './schema.js';
export function* setSchemaFormatter(schema, rawValue, { valuePath, ...options } = {}) {
const { format = true, transform = true } = options;
if (!isSet(rawValue)) {
const { type } = schema;
const path = valuePath !== undefined ? formatArrayPath(valuePath) : undefined;
throw new DynamoDBToolboxError('formatter.invalidAttribute', {
message: `Invalid attribute detected while formatting${path !== undefined ? `: '${path}'` : ''}. Should be a ${type}.`,
path,
payload: { received: rawValue, expected: type }
});
}
// TODO: Remove this cast
const formatters = [...rawValue.values()].map((value, index) => schemaFormatter(schema.elements, value, {
...options,
valuePath: [...(valuePath !== null && valuePath !== void 0 ? valuePath : []), index],
attributes: undefined
}));
if (transform) {
const transformedValue = new Set(formatters.map(formatter => formatter.next().value).filter(value => value !== undefined));
if (format) {
yield transformedValue;
}
else {
return transformedValue;
}
}
const formattedValue = new Set(formatters.map(formatter => formatter.next().value).filter(value => value !== undefined));
return formattedValue;
}