UNPKG

dynamodb-toolbox

Version:

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

45 lines (44 loc) 2.08 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.primitiveSchemaFormatter = primitiveSchemaFormatter; const index_js_1 = require("../../../errors/index.js"); const formatArrayPath_js_1 = require("../../../schema/actions/utils/formatArrayPath.js"); const isValidPrimitive_js_1 = require("../../../utils/validation/isValidPrimitive.js"); function* primitiveSchemaFormatter(schema, rawValue, { format = true, transform = true, valuePath } = {}) { const { props } = schema; if (!(0, isValidPrimitive_js_1.isValidPrimitive)(schema, rawValue)) { const { type } = schema; const path = valuePath !== undefined ? (0, formatArrayPath_js_1.formatArrayPath)(valuePath) : undefined; throw new index_js_1.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 ? (0, formatArrayPath_js_1.formatArrayPath)(valuePath) : undefined; throw new index_js_1.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; }