UNPKG

@nerdware/ddb-single-table

Version:

A schema-based DynamoDB modeling tool, high-level API, and type-generator built to supercharge single-table designs!⚡

38 lines (37 loc) 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transformValues = void 0; const ts_type_safety_utils_1 = require("@nerdware/ts-type-safety-utils"); /** * This `IOAction` uses `transformValue` functions (if defined) to transform * attribute values before they are validated, converted to DynamoDB types, etc. */ const transformValues = function (item, { schemaEntries, ioDirection, ...ctx }) { // To avoid mutating the original item, create a new object to return const itemToReturn = { ...item }; // Iterate over schemaEntries for (let i = 0; i < schemaEntries.length; i++) { const [attrName, attrConfig] = schemaEntries[i]; // See if a transformValue fn is defined const transformValue = attrConfig.transformValue?.[ioDirection]; // If schema has transformValue toDB/fromDB, pass the existing value into the fn if (Object.hasOwn(itemToReturn, attrName) && (0, ts_type_safety_utils_1.isFunction)(transformValue)) { // Get new value; any type mismatches are caught later by the `typeChecking` method const transformedValue = transformValue(itemToReturn[attrName]); // If transformedValue is not undefined, add it to itemToReturn if (!(0, ts_type_safety_utils_1.isUndefined)(transformedValue)) itemToReturn[attrName] = transformedValue; } // Run recursively on nested attributes if parent value exists if (attrConfig.schema && Object.hasOwn(itemToReturn, attrName)) { itemToReturn[attrName] = this.recursivelyApplyIOAction(this.transformValues, itemToReturn[attrName], { parentItem: itemToReturn, ioDirection, ...ctx, schema: attrConfig.schema, // <-- overwrites ctx.schema with the nested schema }); } } return itemToReturn; }; exports.transformValues = transformValues;