ref.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. const Hoek = require('@hapi/hoek');
  3. const internals = {};
  4. exports.create = function (key, options) {
  5. Hoek.assert(typeof key === 'string', 'Invalid reference key:', key);
  6. const settings = Hoek.clone(options); // options can be reused and modified
  7. const ref = function (value, validationOptions) {
  8. return Hoek.reach(ref.isContext ? validationOptions.context : value, ref.key, settings);
  9. };
  10. ref.isContext = (key[0] === ((settings && settings.contextPrefix) || '$'));
  11. ref.key = (ref.isContext ? key.slice(1) : key);
  12. ref.path = ref.key.split((settings && settings.separator) || '.');
  13. ref.depth = ref.path.length;
  14. ref.root = ref.path[0];
  15. ref.isJoi = true;
  16. ref.toString = function () {
  17. return (ref.isContext ? 'context:' : 'ref:') + ref.key;
  18. };
  19. return ref;
  20. };
  21. exports.isRef = function (ref) {
  22. return typeof ref === 'function' && ref.isJoi;
  23. };
  24. exports.push = function (array, ref) {
  25. if (exports.isRef(ref) &&
  26. !ref.isContext) {
  27. array.push(ref.root);
  28. }
  29. };