UNPKG

dynamodb-toolbox

Version:

Lightweight and type-safe query builder for DynamoDB and TypeScript.

42 lines (41 loc) 1.85 kB
import { DynamoDBToolboxError } from '../../../errors/index.js'; import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js'; import { isValidPrimitive } from '../../../utils/validation/isValidPrimitive.js'; export function* primitiveSchemaFormatter(schema, rawValue, { format = true, transform = true, valuePath } = {}) { const { props } = schema; if (!isValidPrimitive(schema, 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 } }); } let transformedValue = undefined; if (transform) { const transformer = props.transform; transformedValue = transformer !== undefined ? transformer.decode(rawValue) : rawValue; } else { transformedValue = rawValue; } if (props.enum !== undefined && !props.enum.includes(transformedValue)) { const path = valuePath !== undefined ? formatArrayPath(valuePath) : undefined; throw new DynamoDBToolboxError('formatter.invalidAttribute', { message: `Invalid attribute detected while formatting${path !== undefined ? `: '${path}'` : ''}. Should be one of: ${props.enum.map(String).join(', ')}.`, path, payload: { received: transformedValue, expected: props.enum } }); } if (transform) { if (format) { yield transformedValue; } else { return transformedValue; } } const formattedValue = transformedValue; return formattedValue; }