@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
70 lines (69 loc) • 2.54 kB
JavaScript
import SpruceError from '../errors/SpruceError.js';
import AbstractField from './AbstractField.js';
class TextField extends AbstractField {
static generateTemplateDetails(options) {
const { definition, language } = options;
const valueType = language === 'go'
? `${definition.isArray ? '[]' : ''}string`
: `string${definition.isArray ? '[]' : ''}`;
return {
valueType,
};
}
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) {
var _a;
let transformed = this.convertToString(value);
if (typeof transformed === 'string') {
const maxLength = (_a = options === null || options === void 0 ? void 0 : options.maxLength) !== null && _a !== void 0 ? _a : 0;
if (maxLength > 0 && transformed.length > maxLength) {
transformed = transformed.substr(0, maxLength);
}
return transformed;
}
throw new SpruceError({
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.';
export default TextField;