object-shape-tester
Version:
Test object properties and value types.
66 lines (65 loc) • 1.99 kB
JavaScript
import { ShapeMismatchError } from '../errors/shape-mismatch.error.js';
import { defineShape } from '../shape/shape.js';
/**
* Checks if the given value matches the given shape and returns `true` or `false` as a type guard.
*
* @category Check
* @returns `true` or `false`
*/
export function checkValidShape(value, shape, options = {}) {
return getCompiledSchema(shape, options).Check(value);
}
/**
* Checks if the given value matches the given shape. If it does, returns the value. If not, returns
* `undefined`.
*
* @category Check
* @returns The original `value` or `undefined.
*/
export function checkWrapValidShape(value, shape, options = {}) {
if (checkValidShape(value, shape, options)) {
return value;
}
else {
return undefined;
}
}
/**
* Asserts that the given value matches the given shape.
*
* @category Check
* @throws `ShapeMismatchError` if `value` does not match the shape.
*/
export function assertValidShape(value, shape, options = {}, failureMessage) {
if (checkValidShape(value, shape, options)) {
return;
}
const errors = Array.from(getCompiledSchema(shape, options).Errors(value));
if (errors.length) {
throw new ShapeMismatchError(value, errors, failureMessage);
}
}
/**
* Asserts that the given value matches the given shape and returns the original `value` if so.
*
* @category Check
* @throws `ShapeMismatchError` if `value` does not match the shape.
*/
export function assertWrapValidShape(value, shape, options = {}, failureMessage) {
assertValidShape(value, shape, options, failureMessage);
return value;
}
function getCompiledSchema(shape, options) {
shape = ensureShape(shape);
return options.allowExtraKeys
? shape.$_compiledSchemaExtraKeys
: shape.$_compiledSchemaNoExtraKeys;
}
/**
* Ensures that the given shape or schema is a shape.
*
* @category Internal
*/
export function ensureShape(shape) {
return defineShape(shape);
}