parameter-validator.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var cJSON = require('circular-json')
  2. , _ = require('lodash') // Don't require Utils here, as it creates a circular dependency
  3. var ParameterValidator = module.exports = {
  4. check: function(value, expectation, options) {
  5. options = _.extend({
  6. throwError: true,
  7. deprecated: false,
  8. deprecationWarning: generateDeprecationWarning(value, expectation, options),
  9. onDeprecated: function(s) { console.log('DEPRECATION WARNING:', s) },
  10. index: null,
  11. method: null,
  12. optional: false
  13. }, options || {})
  14. if (options.optional && ((value === undefined) || (value === null)) ) {
  15. return true
  16. }
  17. if (value === undefined) {
  18. throw new Error('No value has been passed.')
  19. }
  20. if (expectation === undefined) {
  21. throw new Error('No expectation has been passed.')
  22. }
  23. return false
  24. || validateDeprication(value, expectation, options)
  25. || validate(value, expectation, options)
  26. }
  27. }
  28. var generateDeprecationWarning = function(value, expectation, options) {
  29. options = options || {}
  30. if (options.method && options.index) {
  31. return [
  32. 'The',
  33. {1:'first',2:'second',3:'third',4:'fourth',5:'fifth'}[options.index],
  34. 'parameter of',
  35. options.method,
  36. 'should be a',
  37. extractClassName(expectation) + '!'
  38. ].join(" ")
  39. } else {
  40. return ["Expected", cJSON.stringify(value), "to be", extractClassName(expectation) + '!'].join(" ")
  41. }
  42. }
  43. var matchesExpectation = function(value, expectation) {
  44. if (typeof expectation === 'string') {
  45. return (typeof value === expectation.toString())
  46. } else {
  47. return (value instanceof expectation)
  48. }
  49. }
  50. var validateDeprication = function(value, expectation, options) {
  51. if (options.deprecated) {
  52. if (matchesExpectation(value, options.deprecated)) {
  53. options.onDeprecated(options.deprecationWarning)
  54. return true
  55. }
  56. }
  57. }
  58. var validate = function(value, expectation, options) {
  59. var result = matchesExpectation(value, expectation)
  60. if (result) {
  61. return result
  62. } else if (!options.throwError) {
  63. return false
  64. } else {
  65. var _value = (value === null) ? 'null' : value.toString()
  66. , _expectation = extractClassName(expectation)
  67. throw new Error('The parameter (value: ' + _value + ') is no ' + _expectation + '.')
  68. }
  69. }
  70. var extractClassName = function(o) {
  71. if (typeof o === 'string') {
  72. return o
  73. } else if (!!o) {
  74. return o.toString().match(/function ([^\(]+)/)[1]
  75. } else {
  76. return 'undefined'
  77. }
  78. }