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) 2.06 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setDefaults = void 0; const ts_type_safety_utils_1 = require("@nerdware/ts-type-safety-utils"); const hasDefinedProperty_js_1 = require("../utils/hasDefinedProperty.js"); /** * This `IOAction` applies any `"default"`s defined in the schema. Attribute * defaults are applied to an item when it either does not contain the attribute * as an own-property, or the attribute value is `null`/`undefined`. */ const setDefaults = function (item, { schemaEntries, parentItem = item, ...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]; // If a default is defined, and itemToReturn[attrName] is null/undefined, use the default if ((0, ts_type_safety_utils_1.hasKey)(attrConfig, "default") && !(0, hasDefinedProperty_js_1.hasDefinedProperty)(itemToReturn, attrName)) { const attrDefault = attrConfig.default; // Check if "default" is a function, and if so, call it to get the "default" value const attrDefaultValue = (0, ts_type_safety_utils_1.isFunction)(attrDefault) ? attrDefault(parentItem) : attrDefault; // Set the default value on the itemToReturn and parentItem itemToReturn[attrName] = attrDefaultValue; parentItem[attrName] = attrDefaultValue; } // Run recursively on nested attributes if parent value exists if (attrConfig.schema && (0, ts_type_safety_utils_1.hasKey)(itemToReturn, attrName)) { itemToReturn[attrName] = this.recursivelyApplyIOAction(this.setDefaults, itemToReturn[attrName], { parentItem, ...ctx, schema: attrConfig.schema, // <-- overwrites ctx.schema with the nested schema }); } } return itemToReturn; }; exports.setDefaults = setDefaults;