@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
71 lines (70 loc) • 2.6 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 TextField extends AbstractField_1.default {
static generateTemplateDetails(options) {
const { definition } = options;
return {
valueType: `string${definition.isArray ? '[]' : ''}`,
};
}
validate(value, options) {
const errors = super.validate(value, options);
if (errors.length === 0) {
if (value && typeof this.convertToString(value) !== 'string') {
errors.push({
code: 'INVALID_PARAMETER',
name: this.name,
label: this.label,
friendlyMessage: `${this.name} should be a string!`,
});
}
if (this.isRequired && `${value}`.length === 0) {
errors.push({
code: 'MISSING_PARAMETER',
label: this.label,
name: this.name,
});
}
}
return errors;
}
toValueType(value, options) {
let transformed = this.convertToString(value);
if (typeof transformed === 'string') {
const maxLength = options?.maxLength ?? 0;
if (maxLength > 0 && transformed.length > maxLength) {
transformed = transformed.substr(0, maxLength);
}
return transformed;
}
throw new SpruceError_1.default({
code: 'TRANSFORMATION_ERROR',
fieldType: 'text',
incomingTypeof: typeof value,
incomingValue: value,
errors: [
{
friendlyMessage: `${JSON.stringify(value)} could not be converted to a string.`,
code: 'INVALID_PARAMETER',
name: this.name,
},
],
name: this.name,
});
}
convertToString(value) {
return typeof value === 'string'
? value
: typeof value === 'number' &&
value &&
value.toString &&
value.toString();
}
}
TextField.description = 'A text field. Converts non-strings into strings by calling toString(). Size set by options.';
exports.default = TextField;