All files / validator/yupSource object.js

50.93% Statements 82/161
50.96% Branches 53/104
41.46% Functions 17/41
55.63% Lines 79/142

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382                      61x               30x 15x       15x                             15x   15x   15x 15x   15x 15x 19x             19x       15x 11x         3x   57x       19x     19x   19x   19x   19x 19x 51x     19x 19x           19x 19x 53x 53x   53x   51x     51x 51x   51x   51x         51x         51x 49x   2x 2x     53x 5x       19x                                                       4x             4x   4x       4x 4x 4x   4x 4x             4x         4x   11x   11x       11x   11x 11x                             10x           4x                                               15x 15x   15x 15x   15x               15x   15x                                                                                                                                                                                                 7x   15x   11x 11x   11x     3x     22x   46x 46x   46x 45x     10x      
import { camelCase, has, mapKeys, mapValues, snakeCase } from '../../utils'
 
import { getter } from 'property-expr'
import { object as locale } from './locale.js'
import MixedSchema from './mixed'
import inherits from './util/inherits'
import reach from './util/reach'
import runTests from './util/runTests'
import sortByKeyOrder from './util/sortByKeyOrder'
import sortFields from './util/sortFields'
 
let isObject = obj => Object.prototype.toString.call(obj) === '[object Object]'
 
function unknown(ctx, value) {
  let known = Object.keys(ctx.fields)
  return Object.keys(value).filter(key => known.indexOf(key) === -1)
}
 
export default function ObjectSchema(spec) {
  if (!(this instanceof ObjectSchema))
    return typeof spec === 'function'
      ? spec(new ObjectSchema())
      : new ObjectSchema(spec)
 
  MixedSchema.call(this, {
    type: 'object',
    default() {
      if (!this._nodes.length) return undefined
 
      let dft = {}
      this._nodes.forEach(key => {
        dft[key] = this.fields[key].default
          ? this.fields[key].getDefault()
          : undefined
      })
      return dft
    },
  })
 
  this.fields = Object.create(null)
 
  this._sortErrors = sortByKeyOrder([])
 
  this._nodes = []
  this._excludedEdges = []
 
  this.withMutation(() => {
    this.transform(function coerce(value) {
      Iif (typeof value === 'string') {
        try {
          value = JSON.parse(value)
        } catch (err) {
          value = null
        }
      }
      if (this.isType(value)) return value
      return null
    })
 
    if (spec) {
      this.shape(spec)
    }
  })
}
 
inherits(ObjectSchema, MixedSchema, {
  _typeCheck(value) {
    return isObject(value) || typeof value === 'function'
  },
 
  _cast(_value, options = {}) {
    let value = MixedSchema.prototype._cast.call(this, _value)
 
    //should ignore nulls here
    Iif (value === undefined) return this.getDefault()
 
    Iif (!this._typeCheck(value)) return value
 
    let fields = this.fields
 
    let strip = this._option('stripUnknown', options) === true
    let props = this._nodes.concat(
      Object.keys(value).filter(v => this._nodes.indexOf(v) === -1),
    )
 
    let intermediateValue = {} // is filled during the transform below
    let innerOptions = {
      ...options,
      parent: intermediateValue,
      __validating: options.__validating || false,
    }
 
    let isChanged = false
    for (const prop of props) {
      let field = fields[prop]
      let exists = has(value, prop)
 
      if (field) {
        let fieldValue
        let strict = field._options && field._options.strict
 
        // safe to mutate since this is fired in sequence
        innerOptions.path = (options.path ? `${options.path}.` : '') + prop
        innerOptions.value = value[prop]
 
        field = field.resolve(innerOptions)
 
        Iif (field._strip === true) {
          isChanged = isChanged || prop in value
          continue
        }
 
        fieldValue =
          !options.__validating || !strict
            ? field.cast(value[prop], innerOptions)
            : value[prop]
 
        if (fieldValue !== undefined) {
          intermediateValue[prop] = fieldValue
        }
      } else if (exists && !strip) {
        intermediateValue[prop] = value[prop]
      }
 
      if (intermediateValue[prop] !== value[prop]) {
        isChanged = true
      }
    }
 
    return isChanged ? intermediateValue : value
  },
 
  /**
   * @typedef {Object} Ancestor
   * @property {Object} schema - a string property of SpecialType
   * @property {*} value - a number property of SpecialType
   */
 
  /**
   *
   * @param {*} _value
   * @param {Object}       opts
   * @param {string=}      opts.path
   * @param {*=}           opts.parent
   * @param {Object=}      opts.context
   * @param {boolean=}     opts.sync
   * @param {boolean=}     opts.stripUnknown
   * @param {boolean=}     opts.strict
   * @param {boolean=}     opts.recursive
   * @param {boolean=}     opts.abortEarly
   * @param {boolean=}     opts.__validating
   * @param {Object=}      opts.originalValue
   * @param {Ancestor[]=}  opts.from
   * @param {Object}       [opts.from]
   * @param {Function}     callback
   */
  _validate(_value, opts = {}, callback) {
    let errors = []
    let {
      sync,
      from = [],
      originalValue = _value,
      abortEarly = this._options.abortEarly,
      recursive = this._options.recursive,
    } = opts
 
    from = [{ schema: this, value: originalValue }, ...from]
 
    // this flag is needed for handling `strict` correctly in the context of
    // validation vs just casting. e.g strict() on a field is only used when validating
    opts.__validating = true
    opts.originalValue = originalValue
    opts.from = from
 
    MixedSchema.prototype._validate.call(this, _value, opts, (err, value) => {
      Iif (err) {
        if (abortEarly) return void callback(err)
 
        errors.push(err)
        value = err.value
      }
 
      Iif (!recursive || !isObject(value)) {
        callback(errors[0] || null, value)
        return
      }
 
      originalValue = originalValue || value
 
      let tests = this._nodes.map(key => (_, cb) => {
        let path =
          key.indexOf('.') === -1
            ? (opts.path ? `${opts.path}.` : '') + key
            : `${opts.path || ''}["${key}"]`
 
        let field = this.fields[key]
 
        if (field && field.validate) {
          field.validate(
            value[key],
            {
              ...opts,
              path,
              from,
              // inner fields are always strict:
              // 1. this isn't strict so the casting will also have cast inner values
              // 2. this is strict in which case the nested values weren't cast either
              strict: true,
              parent: value,
              originalValue: originalValue[key],
            },
            cb,
          )
          return
        }
 
        cb(null)
      })
 
      runTests(
        {
          sync,
          tests,
          value,
          errors,
          endEarly: abortEarly,
          sort: this._sortErrors,
          path: opts.path,
        },
        callback,
      )
    })
  },
 
  concat(schema) {
    var next = MixedSchema.prototype.concat.call(this, schema)
 
    next._nodes = sortFields(next.fields, next._excludedEdges)
 
    return next
  },
 
  shape(schema, excludes = []) {
    let next = this.clone()
    let fields = Object.assign(next.fields, schema)
 
    next.fields = fields
    next._sortErrors = sortByKeyOrder(Object.keys(fields))
 
    Iif (excludes.length) {
      if (!Array.isArray(excludes[0])) excludes = [excludes]
 
      let keys = excludes.map(([first, second]) => `${first}-${second}`)
 
      next._excludedEdges = next._excludedEdges.concat(keys)
    }
 
    next._nodes = sortFields(fields, next._excludedEdges)
 
    return next
  },
 
  pick(keys) {
    const picked = {}
    for (const key of keys) {
      if (this.fields[key]) picked[key] = this.fields[key]
    }
 
    return this.clone().withMutation(next => {
      next.fields = {}
      return next.shape(picked)
    })
  },
 
  omit(keys) {
    const next = this.clone()
    const fields = next.fields
    next.fields = {}
    for (const key of keys) {
      delete fields[key]
    }
 
    return next.withMutation(next => next.shape(fields))
  },
 
  from(from, to, alias) {
    let fromGetter = getter(from, true)
 
    return this.transform(obj => {
      if (obj == null) return obj
      let newObj = obj
      if (has(obj, from)) {
        newObj = { ...obj }
        if (!alias) delete newObj[from]
 
        newObj[to] = fromGetter(obj)
      }
 
      return newObj
    })
  },
 
  noUnknown(noAllow = true, message = locale.noUnknown) {
    if (typeof noAllow === 'string') {
      message = noAllow
      noAllow = true
    }
 
    let next = this.test({
      name: 'noUnknown',
      exclusive: true,
      message: message,
      test(value) {
        if (value == null) return true
        const unknownKeys = unknown(this.schema, value)
        return (
          !noAllow ||
          unknownKeys.length === 0 ||
          this.createError({ params: { unknown: unknownKeys.join(', ') } })
        )
      },
    })
 
    next._options.stripUnknown = noAllow
 
    return next
  },
 
  unknown(allow = true, message = locale.noUnknown) {
    return this.noUnknown(!allow, message)
  },
 
  transformKeys(fn) {
    return this.transform(obj => obj && mapKeys(obj, (_, key) => fn(key)))
  },
 
  camelCase() {
    return this.transformKeys(camelCase)
  },
 
  snakeCase() {
    return this.transformKeys(snakeCase)
  },
 
  constantCase() {
    return this.transformKeys(key => snakeCase(key).toUpperCase())
  },
 
  describe() {
    let base = MixedSchema.prototype.describe.call(this)
    base.fields = mapValues(this.fields, value => value.describe())
    return base
  },
 
  // 新增
  validateInOrder(data, options) {
    return Object.keys(data)
      .reduce((prev, key) => {
        return prev.then(() => {
          let schema
          try {
            schema = reach(this, key)
          } catch (e) {}
          return schema ? this.validateAt(key, data, options) : undefined
        })
      }, Promise.resolve())
      .then(() => this.cast(data))
  },
  validateInOrderSync(data, options) {
    for (const key of Object.keys(data)) {
      let schema
      try {
        schema = reach(this, key)
      } catch (e) {}
      if (schema) {
        this.validateSyncAt(key, data, options)
      }
    }
    return this.cast(data)
  },
})