Skip to content

Commit

Permalink
fix(validator): 修复 yup.GetSchema 的一些问题
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jul 13, 2023
1 parent 6d576f8 commit 094bf83
Show file tree
Hide file tree
Showing 10 changed files with 164 additions and 24 deletions.
34 changes: 34 additions & 0 deletions src/validator/__snapshots__/yup.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,39 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`yup GetSchema 1`] = `
Object {
"data": Object {
"id": 1,
"name": "ddd",
"posts": Array [],
"role": "vip",
},
}
`;

exports[`yup GetSchema 2`] = `
Object {
"data": Object {
"id": 1,
"name": "ddd",
"posts": Array [],
"role": "vip",
},
}
`;

exports[`yup GetSchema 3`] = `
Object {
"data": Object {
"id": false,
"name": "ddd",
"posts": Array [],
"role": "vip",
},
"error": [ValidationError: 此项必须是一个数字],
}
`;

exports[`yup allowEmptyString 正常 1`] = `
Object {
"data": "",
Expand Down
30 changes: 29 additions & 1 deletion src/validator/yup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as yup from './yupSource'
import { zhCN } from './locale/zhCN'
import * as yup from './yupSource'

// 实现 validateInOrder 方法
yup.addMethod(yup.object, 'validateInOrder', function (data, options) {
Expand Down Expand Up @@ -54,6 +54,34 @@ yup.addMethod(yup.mixed, 'validatePlusSync', function (data, options) {
}
})

// 支持函数参数增强类型支持
Object.keys(yup).forEach(key => {
if (
key === 'mixed' ||
key === 'string' ||
key === 'number' ||
key === 'bool' ||
key === 'boolean' ||
key === 'date' ||
key === 'object' ||
key === 'array'
) {
const raw = yup[key]
// eslint-disable-next-line no-import-assign
Object.defineProperty(yup, key, {
enumerable: true,
writable: false,
configurable: false,
value: payload => {
if (typeof payload === 'function') {
return payload(raw())
}
return raw(payload)
},
})
}
})

// 设置中文为默认语言
yup.setLocale(zhCN)

Expand Down
66 changes: 63 additions & 3 deletions src/validator/yup.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { enUS } from './locale/enUS'
import { expectType } from '../dev'
import { run } from '../utils'
import { yup } from './yup'
import { enUS } from './locale/enUS'
import { zhCN } from './locale/zhCN'
import { yup } from './yup'

describe('yup', () => {
test('默认语言为中文', async () => {
Expand Down Expand Up @@ -174,7 +174,7 @@ describe('yup', () => {
X,
{
disabled: yup.BooleanSchema<boolean>
gender: yup.StringSchema<string>
gender: yup.StringSchema<'male' | 'female'>
}
>()
})
Expand Down Expand Up @@ -304,4 +304,64 @@ describe('yup', () => {
// @ts-expect-error
expect(rule2.validatePlusSync('')).toMatchSnapshot()
})

test('GetSchema', () => {
type User = {
id: number
name: string
role: 'normal' | 'vip'
posts: Array<{
id: number
content: string
image?: string
tags: string[]
createdAt: Date
isTop: boolean
}>
}
const _ = yup
const userSchema: yup.GetSchema<User> = _.object({
id: _.number().required(),
name: _.string().required(),
role: _.string($ => $.required()),
posts: _.array($ =>
$.of(
_.object({
id: _.number().required(),
content: _.string().required(),
image: _.string(),
tags: _.array($ => $.of(_.string()).required()),
createdAt: _.date().required(),
isTop: _.boolean().required(),
}),
),
),
})
expect(
userSchema.validatePlusSync({
id: 1,
name: 'ddd',
role: 'vip',
posts: [],
}),
).toMatchSnapshot()
expect(
userSchema.validatePlusSync({
// @ts-expect-error
id: '1',
name: 'ddd',
role: 'vip',
posts: [],
}),
).toMatchSnapshot()
expect(
userSchema.validatePlusSync({
// @ts-expect-error
id: false,
name: 'ddd',
role: 'vip',
posts: [],
}),
).toMatchSnapshot()
})
})
4 changes: 3 additions & 1 deletion src/validator/yupTypes/array.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,6 @@ export interface ArraySchema<T extends any = any> extends MixedSchema<T[]> {
compact(rejector: (value: T) => boolean): this
}

export declare function array<T extends any = any>(): ArraySchema<T>
export declare function array<T extends any = any>(
payload?: (schema: ArraySchema<T>) => ArraySchema<T>,
): ArraySchema<T>
4 changes: 3 additions & 1 deletion src/validator/yupTypes/boolean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ import { MixedSchema } from './mixed'
export interface BooleanSchema<T extends boolean = boolean>
extends MixedSchema<T> {}

export declare function boolean<T extends boolean = boolean>(): BooleanSchema<T>
export declare function boolean<T extends boolean = boolean>(
payload?: (schema: BooleanSchema<T>) => BooleanSchema<T>,
): BooleanSchema<T>
4 changes: 3 additions & 1 deletion src/validator/yupTypes/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ export interface DateSchema<T extends Date = Date> extends MixedSchema<T> {
max(limit: Date | Ref<Date>, message?: DateLocale['max']): this
}

export declare function date<T extends Date = Date>(): DateSchema<T>
export declare function date<T extends Date = Date>(
payload?: (schema: DateSchema<T>) => DateSchema<T>,
): DateSchema<T>
32 changes: 20 additions & 12 deletions src/validator/yupTypes/mixed.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ArraySchema } from './array'
import { BooleanSchema } from './boolean'
import { DateSchema } from './date'
import { LocaleValue, MixedLocale } from './Locale'
import { NumberSchema } from './number'
import { ObjectSchema } from './object'
Expand Down Expand Up @@ -160,20 +161,27 @@ export interface MixedSchema<T = any> {
): this
}

export type GetSchema<T> = T extends string
? StringSchema<string>
: T extends number
? NumberSchema<number>
: T extends boolean
? BooleanSchema<boolean>
: T extends Array<infer X>
? ArraySchema<X>
: T extends {}
? ObjectSchema<T>
: MixedSchema<T>
export type GetSchema<T> =
// 为何要加 []
// https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
[T] extends [string]
? StringSchema<T>
: [T] extends [number]
? NumberSchema<T>
: [T] extends [boolean]
? BooleanSchema<T>
: T extends Date
? DateSchema<T>
: T extends Array<infer X>
? ArraySchema<X>
: T extends {}
? ObjectSchema<T>
: MixedSchema<T>

export type GetObjectSchema<T extends {}> = {
[K in keyof T]: GetSchema<T[K]>
}

export declare function mixed<T = any>(): MixedSchema<T>
export declare function mixed<T = any>(
payload?: (schema: MixedSchema<T>) => MixedSchema<T>,
): MixedSchema<T>
6 changes: 4 additions & 2 deletions src/validator/yupTypes/number.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MixedSchema } from './mixed'
import { NumberLocale } from './Locale'
import { MixedSchema } from './mixed'
import { Ref } from './ref'

export interface NumberSchema<T extends number = number>
Expand Down Expand Up @@ -37,4 +37,6 @@ export interface NumberSchema<T extends number = number>
round(type?: 'floor' | 'ceil' | 'trunc' | 'round'): this
}

export declare function number<T extends number = number>(): NumberSchema<T>
export declare function number<T extends number = number>(
payload?: (schema: NumberSchema<T>) => NumberSchema<T>,
): NumberSchema<T>
4 changes: 2 additions & 2 deletions src/validator/yupTypes/object.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { GetObjectSchema, MixedSchema, SchemaValidateOptions } from './mixed'
import { ObjectLocale } from './Locale'
import { GetObjectSchema, MixedSchema, SchemaValidateOptions } from './mixed'

export interface ObjectSchema<T extends {} = {}> extends MixedSchema<T> {
shape(fields: GetObjectSchema<T>, noSortEdges?: Array<[string, string]>): this
Expand All @@ -18,5 +18,5 @@ export interface ObjectSchema<T extends {} = {}> extends MixedSchema<T> {
}

export declare function object<T extends {} = {}>(
fields?: GetObjectSchema<T>,
fields?: GetObjectSchema<T> | ((schema: ObjectSchema<T>) => ObjectSchema<T>),
): ObjectSchema<T>
4 changes: 3 additions & 1 deletion src/validator/yupTypes/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,6 @@ export interface StringSchema<T extends string = string>
chineseIDCardNumber(message?: StringLocale['chineseIDCardNumber']): this
}

export declare function string<T extends string = string>(): StringSchema<T>
export declare function string<T extends string = string>(
payload?: (schema: StringSchema<T>) => StringSchema<T>,
): StringSchema<T>

0 comments on commit 094bf83

Please sign in to comment.