UNPKG

dynamodb-toolbox

Version:

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

57 lines (56 loc) 2.42 kB
import { DynamoDBToolboxError } from '../../../errors/index.js'; import { formatArrayPath } from '../../../schema/actions/utils/formatArrayPath.js'; import { anySchemaFormatter } from './any.js'; import { anyOfSchemaFormatter } from './anyOf.js'; import { listSchemaFormatter } from './list.js'; import { mapSchemaFormatter } from './map.js'; import { primitiveSchemaFormatter } from './primitive.js'; import { recordSchemaFormatter } from './record.js'; import { setSchemaFormatter } from './set.js'; export const requiringOptions = new Set(['always', 'atLeastOnce']); export const isRequired = ({ props }) => { var _a; return requiringOptions.has((_a = props.required) !== null && _a !== void 0 ? _a : 'atLeastOnce'); }; export function* schemaFormatter(schema, rawValue, options = {}) { const { format = true, transform = true, valuePath } = options; if (rawValue === undefined) { if (isRequired(schema) && options.partial !== true) { const path = valuePath !== undefined ? formatArrayPath(valuePath) : undefined; throw new DynamoDBToolboxError('formatter.missingAttribute', { message: `Missing required attribute for formatting${path !== undefined ? `: '${path}'` : ''}.`, path, payload: {} }); } if (transform) { if (format) { yield undefined; } else { return undefined; } } return undefined; } switch (schema.type) { case 'any': return yield* anySchemaFormatter(schema, rawValue, options); case 'null': case 'boolean': case 'number': case 'string': case 'binary': return yield* primitiveSchemaFormatter(schema, rawValue, { ...options, attributes: undefined }); case 'set': return yield* setSchemaFormatter(schema, rawValue, { ...options, attributes: undefined }); case 'list': return yield* listSchemaFormatter(schema, rawValue, options); case 'map': return yield* mapSchemaFormatter(schema, rawValue, options); case 'record': return yield* recordSchemaFormatter(schema, rawValue, options); case 'anyOf': return yield* anyOfSchemaFormatter(schema, rawValue, options); } }