normalizeRefPath.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. module.exports = function normalizeRefPath(refPath, doc, populatedPath) {
  3. if (refPath == null) {
  4. return refPath;
  5. }
  6. if (typeof refPath === 'function') {
  7. refPath = refPath.call(doc, doc, populatedPath);
  8. }
  9. // If populated path has numerics, the end `refPath` should too. For example,
  10. // if populating `a.0.b` instead of `a.b` and `b` has `refPath = a.c`, we
  11. // should return `a.0.c` for the refPath.
  12. const hasNumericProp = /(\.\d+$|\.\d+\.)/g;
  13. if (hasNumericProp.test(populatedPath)) {
  14. const chunks = populatedPath.split(hasNumericProp);
  15. if (chunks[chunks.length - 1] === '') {
  16. throw new Error('Can\'t populate individual element in an array');
  17. }
  18. let _refPath = '';
  19. let _remaining = refPath;
  20. // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]`
  21. for (let i = 0; i < chunks.length; i += 2) {
  22. const chunk = chunks[i];
  23. if (_remaining.startsWith(chunk + '.')) {
  24. _refPath += _remaining.substr(0, chunk.length) + chunks[i + 1];
  25. _remaining = _remaining.substr(chunk.length + 1);
  26. } else if (i === chunks.length - 1) {
  27. _refPath += _remaining;
  28. _remaining = '';
  29. break;
  30. } else {
  31. throw new Error('Could not normalize ref path, chunk ' + chunk + ' not in populated path');
  32. }
  33. }
  34. return _refPath;
  35. }
  36. return refPath;
  37. };