@nerdware/ddb-single-table
Version:
A schema-based DynamoDB modeling tool, high-level API, and type-generator built to supercharge single-table designs!⚡
36 lines (35 loc) • 1.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = void 0;
const index_js_1 = require("../utils/index.js");
/**
* This `IOAction` validates an item's individual properties using
* attribute's respective `"validate"` functions defined in the schema.
*
* @throws {ItemInputError} If any attribute's `"validate"` function returns `false`.
*/
const validate = 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;
// Run "validate" fn if defined in the schema
if (!!attrConfig.validate && !attrConfig.validate(item[attrName])) {
// Throw error if validation fails
throw new index_js_1.ItemInputError(`Invalid value for ${(0, index_js_1.getAttrErrID)(modelName, attrName, attrConfig)}.`);
}
// Run recursively on nested attributes
if (attrConfig.schema) {
this.recursivelyApplyIOAction(this.validate, item[attrName], {
parentItem: item,
modelName,
...ctx,
schema: attrConfig.schema, // <-- overwrites ctx.schema with the nested schema
});
}
}
return item;
};
exports.validate = validate;