get-pattern-from-exemplar.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Module dependencies
  3. */
  4. var _ = require('@sailshq/lodash');
  5. /**
  6. * getPatternFromExemplar()
  7. *
  8. * Determine the pattern from the specified array exemplar.
  9. *
  10. * @param {Array} arrayExemplar
  11. * The array exemplar whose pattern should be deduced.
  12. * (must be a valid RTTC exemplar!)
  13. *
  14. * @returns {JSON}
  15. * An RTTC exemplar.
  16. *
  17. * @throws {Error} If `arrayExemplar` is not actually an array.
  18. * @throws {Error} If `arrayExemplar` is not actually an exemplar because it has >1 items.
  19. */
  20. module.exports = function getPatternFromExemplar(arrayExemplar){
  21. if (!_.isArray(arrayExemplar)) {
  22. throw new Error('Provided "array exemplar" is not actually an array (it is a `'+typeof arrayExemplar+'`).');
  23. }
  24. // Generic arrays (`[]`) are the same thing as generic JSON arrays (`['*']`),
  25. // so as you might expect, they have a `*` pattern.
  26. if (arrayExemplar.length === 0) {
  27. return '*';
  28. }
  29. // If there is only one single item, just use that.
  30. else if (arrayExemplar.length === 1){
  31. return arrayExemplar[0];
  32. }
  33. // Otherwise, this isn't actually an exemplar because it has >1 items.
  34. else {
  35. throw new Error('Provided "array exemplar" is not actually an exemplar because it has too many items ('+arrayExemplar.length+').');
  36. }
  37. };