UNPKG

dynamodb-toolbox

Version:

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

55 lines (54 loc) 2.22 kB
import { DynamoDBToolboxError } from '../../../errors/index.js'; import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js'; import { cloneDeep } from '../../../utils/cloneDeep.js'; import { isSet } from '../../../utils/validation/isSet.js'; import { schemaParser } from './schema.js'; import { applyCustomValidation } from './utils.js'; export function* setSchemaParser(schema, inputValue, options = {}) { const { valuePath, ...restOptions } = options; const { fill = true, transform = true } = restOptions; let parsers = []; const isInputValueSet = isSet(inputValue); if (isInputValueSet) { parsers = [...inputValue.values()].map((element, index) => 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 = cloneDeep(inputValue); yield defaultedValue; const linkedValue = defaultedValue; yield linkedValue; } } if (!isInputValueSet) { 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: inputValue, expected: type } }); } const parsedValue = new Set(parsers.map(parser => parser.next().value)); if (parsedValue !== undefined) { applyCustomValidation(schema, parsedValue, options); } if (transform) { yield parsedValue; } else { return parsedValue; } const transformedValue = new Set(parsers.map(parser => parser.next().value)); return transformedValue; }