@vitruvius-labs/ts-predicate
Version:
TypeScript predicates library
34 lines (33 loc) • 1.44 kB
JavaScript
import { buildStructuredDataOptions } from "../utils/build-structured-data-options.mjs";
import { assertRecord } from "./assert-record.mjs";
import { validateProperty } from "./utils/validate-property.mjs";
import { ValidationError } from "./_index.mjs";
import { rethrowUnexpectedError } from "../utils/rethrow-unexpected-error.mjs";
import { getStructuredDataPropertyDescriptor } from "../utils/get-structured-data-property-descriptor.mjs";
function assertStructuredData(value, descriptor, options) {
assertRecord(value);
const OPTIONS = buildStructuredDataOptions(options);
const DESCRIPTOR_KEYS = Object.keys(descriptor);
const ERRORS = [];
if (!OPTIONS.allowExtraneousProperties) {
Object.keys(value).forEach((key) => {
if (!DESCRIPTOR_KEYS.includes(key)) {
ERRORS.push(new ValidationError(`The value has an extraneous property "${key}".`));
}
});
}
DESCRIPTOR_KEYS.forEach((key) => {
const PROPERTY_DESCRIPTOR = getStructuredDataPropertyDescriptor(descriptor, key);
try {
validateProperty(value, key, PROPERTY_DESCRIPTOR);
}
catch (error) {
rethrowUnexpectedError(error);
ERRORS.push(error);
}
});
if (ERRORS.length > 0) {
throw new ValidationError("The value is an object, but some properties are incorrect.", ERRORS);
}
}
export { assertStructuredData };