@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
52 lines (51 loc) • 1.82 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const SpruceError_1 = __importDefault(require("../errors/SpruceError"));
const AbstractField_1 = __importDefault(require("./AbstractField"));
class NumberField extends AbstractField_1.default {
static generateTemplateDetails(options) {
return {
valueType: `number${options.definition.isArray ? '[]' : ''}`,
};
}
toValueType(value) {
const numberValue = +value;
if (!this.isNumber(numberValue)) {
throw new SpruceError_1.default({
code: 'TRANSFORMATION_ERROR',
fieldType: 'number',
incomingTypeof: typeof value,
incomingValue: value,
errors: [
this.buildNaNError(`${JSON.stringify(value)} could not be converted to a number.`),
],
name: this.name,
});
}
return numberValue;
}
buildNaNError(msg) {
return {
friendlyMessage: msg,
code: 'INVALID_PARAMETER',
name: this.name,
};
}
validate(value, options) {
const errors = super.validate(value, options);
if (errors.length === 0) {
if (!this.isNumber(value)) {
errors.push(this.buildNaNError(`"${JSON.stringify(value)}" is not a number!`));
}
}
return errors;
}
isNumber(value) {
return typeof value === 'undefined' || value === null || !isNaN(value);
}
}
NumberField.description = 'Handles all types of numbers with min/max and clamp support';
exports.default = NumberField;