UNPKG

dynamodb-toolbox

Version:

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

84 lines (83 loc) 3.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.itemParser = itemParser; const index_js_1 = require("../../../errors/index.js"); const cloneDeep_js_1 = require("../../../utils/cloneDeep.js"); const isObject_js_1 = require("../../../utils/validation/isObject.js"); const schema_js_1 = require("./schema.js"); function* itemParser(schema, inputValue, options = {}) { const { mode = 'put', fill = true, transform = true } = options; const parsers = {}; let restEntries = []; const isInputValueObject = (0, isObject_js_1.isObject)(inputValue); if (isInputValueObject) { const additionalAttributeNames = new Set(Object.keys(inputValue)); Object.entries(schema.attributes) .filter(([, attr]) => mode !== 'key' || attr.props.key) .forEach(([attrName, attr]) => { parsers[attrName] = (0, schema_js_1.schemaParser)(attr, inputValue[attrName], { ...options, valuePath: [attrName], defined: false }); additionalAttributeNames.delete(attrName); }); restEntries = [...additionalAttributeNames.values()].map(attributeName => [ attributeName, (0, cloneDeep_js_1.cloneDeep)(inputValue[attributeName]) ]); } if (fill) { if (isInputValueObject) { const defaultedValue = Object.fromEntries([ ...Object.entries(parsers) .map(([attrName, attr]) => [attrName, attr.next().value]) .filter(([, defaultedAttrValue]) => defaultedAttrValue !== undefined), ...restEntries ]); yield defaultedValue; const linkedValue = Object.fromEntries([ ...Object.entries(parsers) .map(([attrName, parser]) => [attrName, parser.next(defaultedValue).value]) .filter(([, linkedAttrValue]) => linkedAttrValue !== undefined), ...restEntries ]); yield linkedValue; } else { const defaultedValue = (0, cloneDeep_js_1.cloneDeep)(inputValue); yield defaultedValue; const linkedValue = defaultedValue; yield linkedValue; } } if (!isInputValueObject) { throw new index_js_1.DynamoDBToolboxError('parsing.invalidItem', { message: 'Items should be objects', payload: { received: inputValue, expected: 'object' } }); } const parsedValue = Object.fromEntries(Object.entries(parsers) .map(([attrName, attr]) => [attrName, attr.next().value]) .filter(([, attrValue]) => attrValue !== undefined)); if (transform) { yield parsedValue; } else { return parsedValue; } const transformedValue = Object.fromEntries(Object.entries(parsers) .map(([attrName, attr]) => { var _a; return [ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion (_a = schema.attributes[attrName].props.savedAs) !== null && _a !== void 0 ? _a : attrName, attr.next().value ]; }) .filter(([, attrValue]) => attrValue !== undefined)); return transformedValue; }