@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
48 lines (47 loc) • 1.81 kB
JavaScript
import { selectChoicesToHash } from '../utilities/selectChoicesToHash.js';
import AbstractField from './AbstractField.js';
class SelectField extends AbstractField {
constructor(name, definition) {
super(name, definition);
if (!definition.options || !definition.options.choices) {
throw new Error('Select field is missing choices.');
}
}
static generateTypeDetails() {
return {
valueTypeMapper: 'SelectFieldValueTypeMapper<F extends SelectFieldDefinition ? F: SelectFieldDefinition>',
};
}
validate(value) {
const validChoices = selectChoicesToHash(this.definition.options.choices);
const errors = super.validate(value);
if (value && !validChoices[value]) {
errors.push({
code: 'INVALID_PARAMETER',
name: this.name,
friendlyMessage: `'${value}' is not valid! Valid choices are: '${Object.keys(validChoices).join("','")}'`,
});
}
return errors;
}
static generateTemplateDetails(options) {
const { definition, language } = options;
const { isArray, options: { choices }, } = definition;
const arrayNotation = isArray ? '[]' : '';
if (language === 'go') {
return {
valueType: `${arrayNotation}string`,
};
}
return {
valueType: `(${choices
.map((choice) => `${typeof choice.value === 'number' ? choice.value : `"${choice.value}"`}`)
.join(' | ')})${arrayNotation}`,
};
}
getChoices() {
return this.definition.options.choices;
}
}
SelectField.description = 'Stored as string, lets user select between available options.';
export default SelectField;