All files / validator/yupSource array.js

56.79% Statements 46/81
39.39% Branches 26/66
41.67% Functions 10/24
62.5% Lines 45/72

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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                      4x 2x       2x       2x 2x   2x 2x 6x             6x     2x       3x   21x       6x     6x   6x 6x 2x       2x 2x     2x     6x       3x 3x 3x 3x 3x 3x     3x   3x         3x           3x         3x     3x 3x 1x 1x     1x                 1x 1x         3x                               2x   2x             2x 2x   2x                                                                                                                                  
import { array as locale } from './locale'
import MixedSchema from './mixed'
import inherits from './util/inherits'
import isAbsent from './util/isAbsent'
import isSchema from './util/isSchema'
import printValue from './util/printValue'
import runTests from './util/runTests'
 
export default ArraySchema
 
function ArraySchema(type) {
  if (!(this instanceof ArraySchema))
    return typeof type === 'function'
      ? type(new ArraySchema())
      : new ArraySchema(type)
 
  MixedSchema.call(this, { type: 'array' })
 
  // `undefined` specifically means uninitialized, as opposed to
  // "no subtype"
  this._subType = undefined
  this.innerType = undefined
 
  this.withMutation(() => {
    this.transform(function (values) {
      Iif (typeof values === 'string')
        try {
          values = JSON.parse(values)
        } catch (err) {
          values = null
        }
 
      return this.isType(values) ? values : null
    })
 
    Iif (type) this.of(type)
  })
}
 
inherits(ArraySchema, MixedSchema, {
  _typeCheck(v) {
    return Array.isArray(v)
  },
 
  _cast(_value, _opts) {
    const value = MixedSchema.prototype._cast.call(this, _value, _opts)
 
    //should ignore nulls here
    Iif (!this._typeCheck(value) || !this.innerType) return value
 
    let isChanged = false
    const castArray = value.map((v, idx) => {
      const castElement = this.innerType.cast(v, {
        ..._opts,
        path: `${_opts.path || ''}[${idx}]`,
      })
      if (castElement !== v) {
        isChanged = true
      }
 
      return castElement
    })
 
    return isChanged ? castArray : value
  },
 
  _validate(_value, options = {}, callback) {
    let errors = []
    let sync = options.sync
    let path = options.path
    let innerType = this.innerType
    let endEarly = this._option('abortEarly', options)
    let recursive = this._option('recursive', options)
 
    let originalValue =
      options.originalValue != null ? options.originalValue : _value
 
    MixedSchema.prototype._validate.call(
      this,
      _value,
      options,
      (err, value) => {
        Iif (err) {
          if (endEarly) return void callback(err)
          errors.push(err)
          value = err.value
        }
 
        Iif (!recursive || !innerType || !this._typeCheck(value)) {
          callback(errors[0] || null, value)
          return
        }
 
        originalValue = originalValue || value
 
        // #950 Ensure that sparse array empty slots are validated
        let tests = new Array(value.length)
        for (let idx = 0; idx < value.length; idx++) {
          let item = value[idx]
          let path = `${options.path || ''}[${idx}]`
 
          // object._validate note for isStrict explanation
          let innerOptions = {
            ...options,
            path,
            strict: true,
            parent: value,
            index: idx,
            originalValue: originalValue[idx],
          }
 
          tests[idx] = (_, cb) =>
            innerType.validate
              ? innerType.validate(item, innerOptions, cb)
              : cb(null)
        }
 
        runTests(
          {
            sync,
            path,
            value,
            errors,
            endEarly,
            tests,
          },
          callback,
        )
      },
    )
  },
 
  of(schema) {
    var next = this.clone()
 
    Iif (schema !== false && !isSchema(schema))
      throw new TypeError(
        '`array.of()` sub-schema must be a valid yup schema, or `false` to negate a current sub-schema. ' +
          'not: ' +
          printValue(schema),
      )
 
    next._subType = schema
    next.innerType = schema
 
    return next
  },
 
  min(min, message) {
    message = message || locale.min
 
    return this.test({
      message,
      name: 'min',
      exclusive: true,
      params: { min },
      test(value) {
        return isAbsent(value) || value.length >= this.resolve(min)
      },
    })
  },
 
  max(max, message) {
    message = message || locale.max
    return this.test({
      message,
      name: 'max',
      exclusive: true,
      params: { max },
      test(value) {
        return isAbsent(value) || value.length <= this.resolve(max)
      },
    })
  },
 
  length(length, message) {
    message = message || locale.length
    return this.test({
      message,
      name: 'length',
      exclusive: true,
      params: { length },
      test(value) {
        return isAbsent(value) || value.length === this.resolve(length)
      },
    })
  },
 
  ensure() {
    return this.default(() => []).transform((val, original) => {
      // We don't want to return `null` for nullable schema
      if (this._typeCheck(val)) return val
      return original == null ? [] : [].concat(original)
    })
  },
 
  compact(rejector) {
    let reject = !rejector ? v => !!v : (v, i, a) => !rejector(v, i, a)
 
    return this.transform(values =>
      values != null ? values.filter(reject) : values,
    )
  },
 
  describe() {
    let base = MixedSchema.prototype.describe.call(this)
    if (this.innerType) base.innerType = this.innerType.describe()
    return base
  },
})