validator.js 2.5 KB

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