{"size": 1502, "ext": "js", "max_stars_repo_path": "hc-widget/src/modules/widget-options/validate/types/index.js", "max_stars_repo_name": "FDA/Healthy-Citizen-Code", "max_stars_repo_stars_event_min_datetime": "2018-08-22T21:08:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T03:01:23.000Z", "max_issues_repo_path": "hc-widget/src/modules/widget-options/validate/types/index.js", "max_issues_repo_name": "FDA/Healthy-Citizen-Code", "max_issues_repo_issues_event_min_datetime": "2018-11-26T18:17:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T15:43:41.000Z", "max_forks_repo_path": "hc-widget/src/modules/widget-options/validate/types/index.js", "max_forks_repo_name": "FDA/Healthy-Citizen-Code", "max_forks_repo_forks_event_min_datetime": "2020-04-10T18:58:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T19:12:55.000Z"}
{"max_stars_count": 5, "max_issues_count": 57, "max_forks_count": 2, "avg_line_length": 23.46875, "max_line_length": 99, "alphanum_fraction": 0.690412783}
import { throwOptionValidationError } from '../../utils/error.utils';
import {
  isString,
  isArray,
  isNumber
} from '../../../../lib/utils/utils';
import {ConfigurationError} from '../../../../lib/exceptions';

const types = {
  'String': checkString,
  'String[]': checkArrayOfStrings,
  'Number': checkNumber,
  'Boolean': checkBoolean
};

export function validateType(optionParams) {
  const { type } = optionParams.schema;
  if (type === undefined) {
    throw new ConfigurationError(`Property "type" is missing from option "${optionParams.name}".`);
  }
  const validator = types[type];

  validator(optionParams);
}

function checkString(optionParams) {
  const { value } = optionParams;
  const notString = !isString(value);

  if (notString || value === '') {
    throwOptionValidationError(optionParams, 'not empty String');
  }
}

function checkArrayOfStrings(optionParams) {
  const { value } = optionParams;

  if (!isArray(value)) {
    throwOptionValidationError(optionParams, 'Array');
  }

  const hasOnlyStringsInside = value.every(isString);

  if (!hasOnlyStringsInside) {
    throwOptionValidationError(optionParams, 'Array of strings');
  }
}

function checkNumber(optionParams) {
  const { value } = optionParams;

  if (!isNumber(value)) {
    throwOptionValidationError(optionParams, 'Number');
  }
}

function checkBoolean(optionParams) {
  const { value } = optionParams;

  if (typeof value !== 'boolean') {
    throwOptionValidationError(optionParams, 'Boolean');
  }
}
