validator.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. 'use strict';
  2. import {VERSION} from '../env/data.js';
  3. import AxiosError from '../core/AxiosError.js';
  4. const validators = {};
  5. // eslint-disable-next-line func-names
  6. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
  7. validators[type] = function validator(thing) {
  8. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  9. };
  10. });
  11. const deprecatedWarnings = {};
  12. /**
  13. * Transitional option validator
  14. *
  15. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  16. * @param {string?} version - deprecated version / removed since version
  17. * @param {string?} message - some message with additional info
  18. *
  19. * @returns {function}
  20. */
  21. validators.transitional = function transitional(validator, version, message) {
  22. function formatMessage(opt, desc) {
  23. return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
  24. }
  25. // eslint-disable-next-line func-names
  26. return (value, opt, opts) => {
  27. if (validator === false) {
  28. throw new AxiosError(
  29. formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
  30. AxiosError.ERR_DEPRECATED
  31. );
  32. }
  33. if (version && !deprecatedWarnings[opt]) {
  34. deprecatedWarnings[opt] = true;
  35. // eslint-disable-next-line no-console
  36. console.warn(
  37. formatMessage(
  38. opt,
  39. ' has been deprecated since v' + version + ' and will be removed in the near future'
  40. )
  41. );
  42. }
  43. return validator ? validator(value, opt, opts) : true;
  44. };
  45. };
  46. /**
  47. * Assert object's properties type
  48. *
  49. * @param {object} options
  50. * @param {object} schema
  51. * @param {boolean?} allowUnknown
  52. *
  53. * @returns {object}
  54. */
  55. function assertOptions(options, schema, allowUnknown) {
  56. if (typeof options !== 'object') {
  57. throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
  58. }
  59. const keys = Object.keys(options);
  60. let i = keys.length;
  61. while (i-- > 0) {
  62. const opt = keys[i];
  63. const validator = schema[opt];
  64. if (validator) {
  65. const value = options[opt];
  66. const result = value === undefined || validator(value, opt, options);
  67. if (result !== true) {
  68. throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
  69. }
  70. continue;
  71. }
  72. if (allowUnknown !== true) {
  73. throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
  74. }
  75. }
  76. }
  77. export default {
  78. assertOptions,
  79. validators
  80. };