All files / vae VaeArraySchema.ts

69.23% Statements 9/13
71.43% Branches 5/7
60% Functions 6/10
69.23% Lines 9/13

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                                  8x       8x         8x 3x               8x                                           2x 2x                         1x 1x                                              
import { Nullable } from '../types'
import { isArray } from '../utils'
import { VaeLocale, VaeLocaleMessage } from './VaeLocale'
import { VaeSchema, VaeSchemaOf } from './VaeSchema'
 
export type VaeArraySchemaElementOf<T> = T extends Array<infer X>
  ? VaeSchemaOf<X>
  : never
 
export class VaeArraySchema<
  T0 extends Nullable<any[]> = any[],
  T extends NonNullable<T0> = NonNullable<T0>,
> extends VaeSchema<T0> {
  constructor(
    element?: VaeArraySchemaElementOf<T>,
    message: VaeLocaleMessage = VaeLocale.array.type,
  ) {
    super({
      type: 'array',
    })
 
    this.check({
      fn: isArray,
      message: message,
    })
 
    if (element) {
      this.element(element)
    }
  }
 
  /**
   * 数组元素定义
   */
  element(element: VaeArraySchemaElementOf<T>) {
    return this.check({
      fn: element,
      message: '',
      tag: 'element',
    })
  }
 
  /**
   * 数组非空,即长度应大于 0
   */
  nonempty(message: VaeLocaleMessage = VaeLocale.array.nonempty) {
    return this.check({
      fn: v => v.length > 0,
      message: message,
      tag: 'nonempty',
    })
  }
 
  /**
   * 数组最小长度
   */
  min(value: number, message: VaeLocaleMessage = VaeLocale.array.min) {
    return this.check({
      fn: v => v.length >= value,
      message: message,
      messageParams: {
        min: value,
      },
      tag: 'min',
    })
  }
 
  /**
   * 数组最大长度
   */
  max(value: number, message: VaeLocaleMessage = VaeLocale.array.max) {
    return this.check({
      fn: v => v.length <= value,
      message: message,
      messageParams: {
        max: value,
      },
      tag: 'max',
    })
  }
 
  /**
   * 数组固定长度
   */
  length(value: number, message: VaeLocaleMessage = VaeLocale.array.length) {
    return this.check({
      fn: v => v.length === value,
      message: message,
      messageParams: {
        length: value,
      },
      tag: 'length',
    })
  }
}