@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
53 lines (52 loc) • 2.08 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const selectChoicesToHash_1 = require("../utilities/selectChoicesToHash");
const AbstractField_1 = __importDefault(require("./AbstractField"));
class SelectField extends AbstractField_1.default {
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 = (0, selectChoicesToHash_1.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.';
exports.default = SelectField;