reify.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. var buildSchemaIterator = require('./helpers/build-schema-iterator');
  6. /**
  7. * reify()
  8. *
  9. * Given an rttc type schema, strip out generics to convert it into
  10. * a more specific type which contains no "ref", "json", {}, or [] types.
  11. * In other words, this makes a type schema "strict", and the result of
  12. * this function always passes `rttc.isSpecific()`.
  13. *
  14. * @param {*} typeSchema
  15. * @return {*}
  16. */
  17. module.exports = function reify (typeSchema) {
  18. // Configure type schema iterator and use it to recursively
  19. // collapse generic types.
  20. var schemaIterator = buildSchemaIterator(
  21. function onFacetDict(facetDictionary, parentKeyOrIndex, callRecursive){
  22. var newFacetDict = _.reduce(facetDictionary, function (memo, val, key) {
  23. var facet = callRecursive(val, key);
  24. // Don't include collapsed sub-examples.
  25. if (!_.isUndefined(facet)) {
  26. memo[key] = facet;
  27. }
  28. return memo;
  29. }, {});
  30. // Just in case all of the properties were collapsed, don't inadvertently
  31. // create another generic by returning an empty {}.
  32. if (_.isEqual({}, newFacetDict)) {
  33. return undefined;
  34. }
  35. return newFacetDict;
  36. },
  37. function onPatternArray(patternArray, parentKeyOrIndex, iterateRecursive){
  38. var pattern = iterateRecursive(patternArray[0], 0);
  39. // Don't include collapsed sub-examples.
  40. if (_.isUndefined(pattern)) {
  41. return undefined;
  42. }
  43. return [ pattern ];
  44. },
  45. function onGenericDict(schema, parentKeyOrIndex){
  46. return undefined;
  47. },
  48. function onGenericArray(schema, parentKeyOrIndex){
  49. return undefined;
  50. },
  51. function onOther(schema, parentKeyOrIndex){
  52. if (schema === 'json') {
  53. return undefined;
  54. }
  55. if (schema === 'ref') {
  56. return undefined;
  57. }
  58. return schema;
  59. }
  60. );
  61. // Run the iterator to get the reified type schema.
  62. return schemaIterator(typeSchema);
  63. };