ref.js 1.1 KB

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