@prismicio/types-internal
Version:
Prismic types for Custom Types and Prismic Data
41 lines (40 loc) • 1.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const t = (0, tslib_1.__importStar)(require("io-ts"));
const BasicTypes_1 = require("./BasicTypes");
/**
* Creates a custom runtime type for validating that a number falls within a specified range.
*
* @param min - The minimum value of the range.
* @param max - The maximum value of the range.
* @param fieldName - The name of the field being validated (used in error messages).
* @returns A runtime type representing the number range validation.
*
* * @example
* // Creating a custom runtime type for age validation
* const AgeType = numberInRange(18, 99, 'Age');
*
* // Valid age
* const validAgeResult = AgeType.decode(25);
* if (t.isRight(validAgeResult)) {
* console.log('Valid age:', validAgeResult.right); // Output: Valid age: 25
* } else {
* console.error('Invalid age:', t.left(validAgeResult).map(t.reporter.report));
* }
*
* @example
* // Invalid age
* const invalidAgeResult = AgeType.decode(15);
* if (t.isRight(invalidAgeResult)) {
* console.log('Valid age:', invalidAgeResult.right);
* } else {
* console.error('Invalid age:', t.left(invalidAgeResult).map(t.reporter.report));
* }
*/
exports.default = (min, max, fieldName) => BasicTypes_1.Number.pipe(new t.Type("numberInRange", (u) => BasicTypes_1.Number.is(u), (u, context) => {
if (u > max || u < min) {
return t.failure(u, context, `${fieldName} must be a number between ${min} and ${max}`);
}
return t.success(u);
}, t.identity));