infer.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. var types = require('./helpers/types');
  6. var inferPrimitive = require('./helpers/infer-primitive');
  7. /**
  8. * Infer the type schema of the provided RTTC exemplar (aka example).
  9. *
  10. * @param {JSON} eg [an rttc exemplar]
  11. * @return {JSON} [a type schema]
  12. */
  13. module.exports = function infer(eg) {
  14. // If the exemplar isn't a dictionary or array, we will infer
  15. // its type without messing around with any kind of recursion.
  16. if(!types.dictionary.is(eg) && !types.array.is(eg)) {
  17. return inferPrimitive(eg);
  18. }
  19. // If the exemplar is an array...
  20. else if(types.array.is(eg)) {
  21. // If this array is empty, that means it's a generic array exemplar.
  22. // (we do not parse generic array exemplars recursively.)
  23. if (eg.length === 0) {
  24. return eg;
  25. }
  26. // Otherwise this is pattern array- which we do infer recursively.
  27. else {
  28. // << Recursive step >>
  29. return [ infer(eg[0]) ];
  30. }//</pattern array>
  31. }
  32. // If the exemplar is a dictionary...
  33. else {
  34. // If this dictionary is empty, that means it's a generic
  35. // dictionary exemplar (we do not parse generic dictionary
  36. // exemplars recursively.)
  37. if (_.keys(eg).length === 0) {
  38. return eg;
  39. }//</generic dictionary>
  40. // Otherwise, this is a faceted dictionary exemplar.
  41. // So we infer its type schema recursively.
  42. else {
  43. var dictionaryTypeSchema = {};
  44. _.each(_.keys(eg), function(key) {
  45. // << Recursive step >>
  46. dictionaryTypeSchema[key] = infer(eg[key]);
  47. });
  48. return dictionaryTypeSchema;
  49. }//</faceted dictionary>
  50. }
  51. };