UNPKG

@sprucelabs/schema

Version:

Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓

47 lines (46 loc) • 1.9 kB
"use strict"; 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 } = options; const { isArray, options: { choices }, } = definition; return { valueType: `(${choices .map((choice) => `${typeof choice.value === 'number' ? choice.value : `"${choice.value}"`}`) .join(' | ')})${isArray ? '[]' : ''}`, }; } getChoices() { return this.definition.options.choices; } } SelectField.description = 'Stored as string, lets user select between available options.'; exports.default = SelectField;