All files / vae VaeObjectSchema.ts

86.05% Statements 37/43
78.26% Branches 36/46
93.75% Functions 15/16
86.05% Lines 37/43

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                                                27x       27x         27x 22x               27x 27x 27x 118x             27x             2x 6x       2x       2x             2x 6x       2x 2x                       2x 6x         3x     2x                           2x 6x         3x     2x                           2x 2x 28x         15x     2x                   2x   5x 10x 6x   4x                                   4x   1x                    
import { Nullable, PartialBy, RequiredBy } from '../types'
import {
  difference,
  find,
  includes,
  intersection,
  isPlainObject,
  startsWith,
} from '../utils'
import { VaeLocale, VaeLocaleMessage } from './VaeLocale'
import { VaeSchema, VaeSchemaOf } from './VaeSchema'
 
export type VaeObjectSchemaShapeOf<T> = {
  [K in keyof T]: VaeSchemaOf<T[K]>
}
 
export class VaeObjectSchema<
  T0 extends Nullable<Record<any, any>> = Record<any, any>,
  T extends NonNullable<T0> = NonNullable<T0>,
> extends VaeSchema<T0> {
  constructor(
    shape?: VaeObjectSchemaShapeOf<T>,
    message: VaeLocaleMessage = VaeLocale.object.type,
  ) {
    super({
      type: 'object',
    })
 
    this.check({
      fn: isPlainObject,
      message: message,
    })
 
    if (shape) {
      this.shape(shape)
    }
  }
 
  /**
   * 对象定义
   */
  shape(shape: VaeObjectSchemaShapeOf<T>) {
    const keys = Object.keys(shape)
    this._options.objectKeys = keys
    keys.forEach(key => {
      this.check({
        fn: (shape as any)[key],
        path: [key],
        message: '',
        tag: `field_${key}`,
      })
    })
    return this
  }
 
  /**
   * 原地挑选给定字段
   */
  pickFields<K extends keyof T>(keys: K[]): VaeObjectSchema<Pick<T, K>> {
    this._options.processors = this._options.processors.filter(item =>
      typeof item === 'object' && startsWith(item.tag, 'field_')
        ? includes(keys as any, item.path![0])
        : true,
    )
    this._options.objectKeys = intersection(
      this._options.objectKeys,
      keys as any,
    )
    return this as any
  }
 
  /**
   * 原地剔除给定字段
   */
  omitFields<K extends keyof T>(keys: K[]): VaeObjectSchema<Omit<T, K>> {
    this._options.processors = this._options.processors.filter(item =>
      typeof item === 'object' && startsWith(item.tag, 'field_')
        ? !includes(keys as any, item.path![0])
        : true,
    )
    this._options.objectKeys = difference(this._options.objectKeys, keys as any)
    return this as any
  }
 
  /**
   * 原地将给定字段设为可选
   */
  optionalFields<K extends keyof T>(keys: K[]): VaeObjectSchema<PartialBy<T, K>>
  /**
   * 原地将所有字段设为可选
   */
  optionalFields(): VaeObjectSchema<Partial<T>>
  optionalFields(keys?: string[]): any {
    this._options.processors.forEach(item => {
      if (
        typeof item === 'object' &&
        startsWith(item.tag, 'field_') &&
        (keys ? includes(keys as any, item.path![0]) : true)
      ) {
        ;(item.fn as VaeSchema).optional()
      }
    })
    return this
  }
 
  /**
   * 原地将给定字段设为必填
   */
  requiredFields<K extends keyof T>(
    keys: K[],
  ): VaeObjectSchema<RequiredBy<T, K>>
  /**
   * 原地将所有字段设为必填
   */
  requiredFields(): VaeObjectSchema<Required<T>>
  requiredFields(keys?: string[]): any {
    this._options.processors.forEach(item => {
      if (
        typeof item === 'object' &&
        startsWith(item.tag, 'field_') &&
        (keys ? includes(keys as any, item.path![0]) : true)
      ) {
        ;(item.fn as VaeSchema).required()
      }
    })
    return this
  }
 
  /**
   * 返回给定字段的定义
   */
  shapeOfFields<K extends keyof T>(
    keys: K[],
  ): VaeObjectSchemaShapeOf<Pick<T, K>>
  /**
   * 返回全部字段的定义
   */
  shapeOfFields(): VaeObjectSchemaShapeOf<T>
  shapeOfFields(keys?: string[]) {
    const shape: Record<any, any> = {}
    this._options.processors.forEach(item => {
      if (
        typeof item === 'object' &&
        startsWith(item.tag, 'field_') &&
        (keys ? includes(keys as any, item.path![0]) : true)
      ) {
        shape[item.path![0]] = item.fn
      }
    })
    return shape
  }
 
  /**
   * 给定字段中至少有一个必填
   */
  requiredFieldsAtLeastOne<K extends keyof T>(
    keys: K[],
    message: VaeLocaleMessage = VaeLocale.object.requiredFieldsAtLeastOne,
  ) {
    return this.check({
      fn: (v: any) => {
        for (const key of keys) {
          if (v[key] == null) {
            continue
          }
          Iif (v[key] === '') {
            const schema: VaeSchema | undefined = find(
              this._options.processors,
              item =>
                typeof item === 'object' &&
                startsWith(item.tag, 'field_') &&
                item.path![0] === key,
            ) as any
            if (!schema) {
              continue
            }
            if (
              schema.options.type === 'string' &&
              !schema.options.stringEmptyable
            ) {
              continue
            }
          }
          return true
        }
        return false
      },
      message: message,
      messageParams: {
        keys: keys,
      },
      tag: 'requiredFieldsAtLeastOne',
    })
  }
}