UNPKG

dynamodb-toolbox

Version:

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

48 lines (47 loc) 2.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.tupleSchemaFormatter = tupleSchemaFormatter; const index_js_1 = require("../../../errors/index.js"); const formatArrayPath_js_1 = require("../../../schema/actions/utils/formatArrayPath.js"); const isArray_js_1 = require("../../../utils/validation/isArray.js"); const schema_js_1 = require("./schema.js"); const utils_js_1 = require("./utils.js"); function* tupleSchemaFormatter(schema, rawValue, { attributes, valuePath, ...restOptions } = {}) { const { format = true, transform = true } = restOptions; if (!(0, isArray_js_1.isArray)(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 } }); } const formatters = []; let projectedIndex = 0; schema.elements.forEach((element, elementIndex) => { const { isProjected, childrenAttributes } = (0, utils_js_1.matchTupleProjection)(elementIndex, attributes); if (isProjected) { formatters.push(isProjected ? (0, schema_js_1.schemaFormatter)(element, rawValue[projectedIndex], { attributes: childrenAttributes, valuePath: [...(valuePath !== null && valuePath !== void 0 ? valuePath : []), elementIndex], ...restOptions, ...(!isProjected ? { defined: false } : {}) }) : undefined); projectedIndex++; } }); if (transform) { const transformedValue = formatters.map(formatter => formatter === null || formatter === void 0 ? void 0 : formatter.next().value); if (format) { yield transformedValue; } else { return transformedValue; } } const formattedValue = formatters.map(formatter => formatter === null || formatter === void 0 ? void 0 : formatter.next().value); return formattedValue; }