validate-recursive.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /**
  2. * Module dependencies
  3. */
  4. var util = require('util');
  5. var _ = require('@sailshq/lodash');
  6. var types = require('./types');
  7. var rebuildSanitized = require('./sanitize');
  8. var compile = require('../compile');
  9. var getDisplayType = require('../get-display-type');
  10. /**
  11. *
  12. * @param {===} expected
  13. * @param {===} actual
  14. * @param {Array} errors [errors encountered along the way are pushed here]
  15. * @param {Array} hops [used in error messages]
  16. * @param {Boolean} strict [if set, validation will be strict]
  17. * @return {===} coerced value
  18. */
  19. module.exports = function _validateRecursive (expected, actual, errors, hops, strict){
  20. // Look up expected type from `types` object using `expected`.
  21. var expectedType;
  22. var isExpectingArray;
  23. var isExpectingDictionary;
  24. var isExpectingAnything;
  25. var allowAnyArray;
  26. var allowAnyDictionary;
  27. var allowAnyJSONCompatible;
  28. // console.log('validating',actual,'against',expected,'...');
  29. //
  30. // Set special flags about what to allow/expect for the type:
  31. //
  32. // Flag [] (allow any array)
  33. if (_.isArray(expected) && expected.length === 0) {
  34. allowAnyArray = true;
  35. }
  36. // Flag {} (allow any dictionary)
  37. else if (_.isPlainObject(expected) && _.keys(expected).length === 0) {
  38. allowAnyDictionary = true;
  39. }
  40. // Flag 'ref' (allow anything that's not undefined)
  41. else if (expected === 'ref') {
  42. isExpectingAnything = true;
  43. }
  44. // Flag 'json' (allow anything that's JSON compatible)
  45. else if (expected === 'json') {
  46. allowAnyJSONCompatible = true;
  47. }
  48. //
  49. // Now look up the proper type validation/coercion strategy:
  50. //
  51. // Arrays
  52. if (_.isArray(expected)) {
  53. expectedType = types.array;
  54. isExpectingArray = true;
  55. }
  56. // Dictionaries
  57. else if (_.isObject(expected)) {
  58. expectedType = types.dictionary;
  59. isExpectingDictionary = true;
  60. }
  61. // everything else (i.e. 'string', 'boolean', 'number', 'ref', 'lamda', 'json')
  62. else {
  63. expectedType = types[expected];
  64. // If this refers to an unknown type, default
  65. // to a string's base type and remember the error.
  66. if (_.isUndefined(expectedType)) {
  67. errors.push((function (){
  68. var err = new Error('Unknown type: '+expected);
  69. err.code = 'E_UNKNOWN_TYPE';
  70. return err;
  71. })());
  72. return types.string.getBase();
  73. }
  74. }
  75. // Default the coercedValue to the actual value.
  76. var coercedValue = actual;
  77. // If the actual value is undefined, fill in with the
  78. // appropriate base value for the type.
  79. if(_.isUndefined(actual)) {
  80. coercedValue = expectedType.getBase();
  81. }
  82. // Check `actual` value using `expectedType.is()`
  83. if (!expectedType.is(actual)){
  84. // Build an E_NOT_STRICTLY_VALID error
  85. var newErr = (function (){
  86. var msg = '';
  87. if (_.isUndefined(actual)) {
  88. msg += 'Expecting ' + compile(expected) + ' (but got `undefined`)';
  89. }
  90. else {
  91. msg += 'Specified value (a ' + getDisplayType(actual) + ': '+((actual===Infinity||actual===-Infinity||_.isNaN(actual))?actual:compile(actual))+') ';
  92. msg += 'doesn\'t match the expected '+(_.isObject(expected)?getDisplayType(expected)+' ':'')+'type'+(_.isObject(expected)?' schema ':'')+ ': ' + compile(expected) + '';
  93. }
  94. if (hops.length > 0) {
  95. msg = '@ `'+hops.join('.')+'`: ' + msg;
  96. }
  97. var err = new Error(msg);
  98. err.hops = hops;
  99. err.actual = actual;
  100. err.expected = expected;
  101. err.code = 'E_NOT_STRICTLY_VALID';
  102. // This is considered a "minor" error if it can be coerced without
  103. // causing any errors.
  104. try {
  105. expectedType.to(actual);
  106. err.minor = true;
  107. }
  108. catch (e) {}
  109. return err;
  110. })();
  111. // Don't bother tracking minor errors unless we're in `strict` mode.
  112. if (!newErr.minor || (strict && newErr.minor)) {
  113. errors.push(newErr);
  114. }
  115. // Invalid expected type. Try to coerce:
  116. try {
  117. coercedValue = expectedType.to(actual);
  118. }
  119. catch (e) {
  120. // If that doesn't work, use the base type:
  121. coercedValue = expectedType.getBase();
  122. // But also push an `E_NOT_EVEN_CLOSE` error
  123. errors.push((function (){
  124. var msg = '';
  125. if (_.isUndefined(actual)) {
  126. msg += 'Expecting ' + compile(expected) + ' (but got `undefined`)';
  127. }
  128. else {
  129. msg += 'Specified value (a ' + getDisplayType(actual) + ': '+compile(actual)+ ') ';
  130. msg += 'doesn\'t match the expected '+(_.isObject(expected)?getDisplayType(expected)+' ':'')+'type'+(_.isObject(expected)?' schema ':'')+ ': ' + compile(expected) + '';
  131. }
  132. msg += ' Attempted to coerce the specified value to match, but it wasn\'t similar enough to the expected value.';
  133. if (hops.length > 0) {
  134. msg = '@ `'+hops.join('.')+'`: ' + msg;
  135. }
  136. var err = new Error(msg);
  137. err.hops = hops;
  138. err.actual = actual;
  139. err.expected = expected;
  140. err.code = 'E_NOT_EVEN_CLOSE';
  141. return err;
  142. })());
  143. }
  144. }
  145. // Build partial result
  146. // (taking recursive step if necessary)
  147. // ...expecting ANYTHING ('===')
  148. if (isExpectingAnything) {
  149. // Note that, in this case, we return a mutable reference.
  150. return coercedValue;
  151. }
  152. // ...expecting ANY json-compatible value (`"*"`)
  153. if (allowAnyJSONCompatible) {
  154. // (run rebuildSanitized with `allowNull` enabled)
  155. return rebuildSanitized(coercedValue, true);
  156. }
  157. if (isExpectingArray) {
  158. // ...expecting ANY array (`[]`)
  159. if (allowAnyArray) {
  160. return rebuildSanitized(coercedValue, true);
  161. }
  162. // ...expecting a specific array example
  163. var arrayItemTpl = expected[0];
  164. return _.reduce(coercedValue, function (memo, coercedVal, i){
  165. // Never consider `undefined` a real array item. Because things cannot be and also not be.
  166. if (_.isUndefined(coercedVal)) {
  167. return memo;
  168. }
  169. memo.push(_validateRecursive(arrayItemTpl, coercedVal, errors, hops.concat(i), strict));
  170. return memo;
  171. }, []);
  172. }
  173. if (isExpectingDictionary) {
  174. // ...expecting ANY dictionary (`{}`)
  175. if (allowAnyDictionary){
  176. return rebuildSanitized(coercedValue, true);
  177. }
  178. // ...expecting a specific dictionary example
  179. return _.reduce(expected, function (memo, expectedVal, expectedKey) {
  180. memo[expectedKey] = _validateRecursive(expected[expectedKey], coercedValue[expectedKey], errors, hops.concat(expectedKey), strict);
  181. return memo;
  182. }, {});
  183. }
  184. // ...expecting a primitive
  185. return coercedValue;
  186. };