validator.js 2.3 KB

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