UNPKG

@nerdware/ddb-single-table

Version:

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

43 lines (42 loc) 2.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.typeChecking = void 0; const ts_type_safety_utils_1 = require("@nerdware/ts-type-safety-utils"); const index_js_1 = require("../utils/index.js"); /** * This `IOAction` ensures item values conform with their `"type"` as defined in the schema. * * @throws {ItemInputError} If an attribute's value does not match the expected `"type"`. */ const typeChecking = function (item, { schemaEntries, modelName, ...ctx }) { // Iterate over schemaEntries for (let i = 0; i < schemaEntries.length; i++) { const [attrName, attrConfig] = schemaEntries[i]; // If the item does not have the attribute, or if its value is nullish, skip it if (!(0, index_js_1.hasDefinedProperty)(item, attrName)) continue; // Check the type of its value (can't check unknown attributes if schema allows for them) if (!index_js_1.isType[attrConfig.type](item[attrName], attrConfig.oneOf ?? attrConfig.schema ?? [])) { // Throw error if there's a type mismatch throw new index_js_1.ItemInputError(`Invalid type of value provided for ${(0, index_js_1.getAttrErrID)(modelName, attrName, attrConfig)}.` + `\nExpected: ${attrConfig.type} ` + (attrConfig.type === "enum" ? `(oneOf: ${(0, ts_type_safety_utils_1.safeJsonStringify)(attrConfig.oneOf)})` : ["map", "array", "tuple"].includes(attrConfig.type) ? `(schema: ${(0, index_js_1.stringifyNestedSchema)(attrConfig.schema)})` : "") + `\nReceived: ${(0, ts_type_safety_utils_1.safeJsonStringify)(item[attrName])}`); } // Run recursively on nested attributes if (attrConfig.schema) { this.recursivelyApplyIOAction(this.typeChecking, item[attrName], { parentItem: item, modelName, ...ctx, schema: attrConfig.schema, // <-- overwrites ctx.schema with the nested schema }); } } return item; }; exports.typeChecking = typeChecking;