All files / validator/yupSource Reference.js

82.14% Statements 23/28
78.13% Branches 25/32
57.14% Functions 4/7
84% Lines 21/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95    3x               3x 1x         3x     3x   3x   3x 3x 3x 3x   3x               3x 3x 3x       6x               6x   6x   6x                                                             1x       334x       3x  
import { getter } from 'property-expr'
 
const prefixes = {
  context: '$',
  value: '.',
  rootValue: '@',
}
 
export default class Reference {
  constructor(key, options = {}) {
    if (typeof options === 'function') {
      options = {
        map: options,
      }
    }
 
    Iif (typeof key !== 'string')
      throw new TypeError('ref must be a string, got: ' + key)
 
    this.key = key.trim()
 
    Iif (key === '') throw new TypeError('ref must be a non-empty string')
 
    this.isContext = this.key[0] === prefixes.context
    this.isValue = this.key[0] === prefixes.value
    this.isRootValue = this.key[0] === prefixes.rootValue
    this.isSibling = !this.isContext && !this.isValue && !this.isRootValue
 
    let prefix = this.isContext
      ? prefixes.context
      : this.isValue
      ? prefixes.value
      : this.isRootValue
      ? prefixes.rootValue
      : ''
 
    this.path = this.key.slice(prefix.length)
    this.getter = this.path && getter(this.path, true)
    this.map = options.map
  }
 
  getValue(value, parent, context, rootValue) {
    let result = this.isContext
      ? context
      : this.isValue
      ? value
      : this.isRootValue
      ? rootValue
      : parent
 
    if (this.getter) result = this.getter(result || {})
 
    if (this.map) result = this.map(result)
 
    return result
  }
 
  /**
   *
   * @param {*} value
   * @param {Object} options
   * @param {Object=} options.context
   * @param {Object=} options.parent
   */
  cast(value, options) {
    return this.getValue(
      value,
      options?.parent,
      options?.context,
      options?.rootValue,
    )
  }
 
  resolve() {
    return this
  }
 
  describe() {
    return {
      type: 'ref',
      key: this.key,
    }
  }
 
  toString() {
    return `Ref(${this.key})`
  }
 
  static isRef(value) {
    return value && value.__isYupRef
  }
}
 
Reference.prototype.__isYupRef = true