Skip to content

Commit

Permalink
fix: yup 内部维护
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Aug 11, 2021
1 parent 0add09c commit a49dbdd
Show file tree
Hide file tree
Showing 35 changed files with 2,527 additions and 220 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
node_modules
lib
dist
/src/validator/yupSource/
8 changes: 4 additions & 4 deletions haoma-compile.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,25 @@ const removeIsTypePlugin = defineBabelPlugin(t => ({
export default [
getCompileConfig({
name: 'esm',
inputFiles: ['src/**/*.ts', '!**/*.{test,perf}.*', '!**/__*'],
inputFiles: ['src/**/*.{ts,js}', '!**/*.{test,perf}.*', '!**/__*'],
module: 'esm',
target: file => (/src\/(dev|x)\//.test(file) ? 'node' : 'browser'),
outDir: 'lib',
emitDts: true,
rollupDts: true,
rollupDtsFiles: ['**/index.d.ts'],
rollupDtsExcludeFiles: ['**/validator/**/*'],
rollupDtsExcludeFiles: ['**/validator/**'],
rollupDtsIncludedPackages: ['type-fest', 'ts-essentials'],
plugins: [removeIsTypePlugin],
}),
getCompileConfig({
name: 'cjs',
inputFiles: ['src/**/*.ts', '!**/*.{test,perf}.*', '!**/__*'],
inputFiles: ['src/**/*.{ts,js}', '!**/*.{test,perf}.*', '!**/__*'],
module: 'cjs',
target: file => (/src\/(dev|x)\//.test(file) ? 'node' : 'browser'),
outDir: 'lib/_cjs',
emitDts: false,
alias: {
'yup/es': 'yup/lib',
'date-fns/esm': 'date-fns',
},
plugins: [removeIsTypePlugin],
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@
"lodash-uni": "^1.1.0",
"miniprogram-api-typings": "^3.2.3",
"nanoid": "^3.1.20",
"property-expr": "^2.0.4",
"react-use": "^17.2.1",
"toposort": "^2.0.2",
"tough-cookie": "^4.0.0",
"tough-cookie-redisstore": "^0.0.4",
"uuid": "^8.3.2",
Expand Down Expand Up @@ -143,8 +145,8 @@
"eslint": "7.32.0",
"execa": "5.1.1",
"fs-extra": "10.0.0",
"globby": "12.0.0",
"haoma": "3.4.2",
"globby": "11.0.4",
"haoma": "3.4.3",
"husky": "4.3.8",
"ioredis-mock": "5.6.0",
"jest": "27.0.6",
Expand Down
2 changes: 1 addition & 1 deletion renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
":automergeBranch",
":automergeRequireAllStatusChecks"
],
"ignoreDeps": ["yup", "husky"]
"ignoreDeps": ["yup", "husky", "globby"]
}
4 changes: 4 additions & 0 deletions src/validator/yup.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import './yupTypes'
import * as yup from 'yup/es'

export { yup }
86 changes: 86 additions & 0 deletions src/validator/yup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import * as yup from './yupSource'
import {
isChineseIDCardNumber,
isPossibleChineseMobilePhoneNumber,
} from '../utils'
import { zhCN } from './locale/zhCN'

// 实现 chineseMobilePhoneNumber 验证器
yup.addMethod(
yup.string,
'chineseMobilePhoneNumber',
function (message = yup.getLocale().string.chineseMobilePhoneNumber) {
return this.test(
'chineseMobilePhoneNumber',
message,
isPossibleChineseMobilePhoneNumber,
)
},
)

// 实现 chineseIDCardNumber 验证器
yup.addMethod(
yup.string,
'chineseIDCardNumber',
function (message = yup.getLocale().string.chineseIDCardNumber) {
return this.test('chineseIDCardNumber', message, isChineseIDCardNumber)
},
)

// 实现 validateInOrder 方法
yup.addMethod(yup.object, 'validateInOrder', function (data, options) {
return Object.keys(data)
.reduce((prev, key) => {
return prev.then(() => {
let schema
try {
schema = yup.reach(this, key)
} catch (e) {}
return schema ? this.validateAt(key, data, options) : undefined
})
}, Promise.resolve())
.then(() => this.cast(data))
})

// 实现 validateInOrderSync 方法
yup.addMethod(yup.object, 'validateInOrderSync', function (data, options) {
for (const key of Object.keys(data)) {
let schema
try {
schema = yup.reach(this, key)
} catch (e) {}
if (schema) {
this.validateSyncAt(key, data, options)
}
}
return this.cast(data)
})

// 实现 validatePlus 方法
yup.addMethod(yup.mixed, 'validatePlus', function (data, options) {
return (
this.type === 'object'
? this.validateInOrder(data, options)
: this.validate(data, options)
)
.then(data => ({ data }))
.catch(error => ({ error, data }))
})

// 实现 validatePlusSync 方法
yup.addMethod(yup.mixed, 'validatePlusSync', function (data, options) {
try {
const _data =
this.type === 'object'
? this.validateInOrderSync(data, options)
: this.validateSync(data, options)
return { data: _data }
} catch (error) {
return { error, data }
}
})

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

export { yup }
116 changes: 0 additions & 116 deletions src/validator/yup.ts

This file was deleted.

55 changes: 55 additions & 0 deletions src/validator/yupSource/Condition.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { has } from '../../utils'
import isSchema from './util/isSchema'

class Condition {
constructor(refs, options) {
this.refs = refs

if (typeof options === 'function') {
this.fn = options
return
}

if (!has(options, 'is'))
throw new TypeError('`is:` is required for `when()` conditions')

if (!options.then && !options.otherwise)
throw new TypeError(
'either `then:` or `otherwise:` is required for `when()` conditions',
)

let { is, then, otherwise } = options

let check =
typeof is === 'function'
? is
: (...values) => values.every(value => value === is)

this.fn = function (...args) {
let options = args.pop()
let schema = args.pop()
let branch = check(...args) ? then : otherwise

if (!branch) return undefined
if (typeof branch === 'function') return branch(schema)
return schema.concat(branch.resolve(options))
}
}

resolve(base, options) {
let values = this.refs.map(ref =>
ref.getValue(options?.value, options?.parent, options?.context),
)

let schema = this.fn.apply(base, values.concat(base, options))

if (schema === undefined || schema === base) return base

if (!isSchema(schema))
throw new TypeError('conditions must return a schema object')

return schema.resolve(options)
}
}

export default Condition
36 changes: 36 additions & 0 deletions src/validator/yupSource/Lazy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import isSchema from './util/isSchema'

class Lazy {
constructor(mapFn) {
this._resolve = (value, options) => {
let schema = mapFn(value, options)

if (!isSchema(schema))
throw new TypeError('lazy() functions must return a valid schema')

return schema.resolve(options)
}
}
resolve(options) {
return this._resolve(options.value, options)
}
cast(value, options) {
return this._resolve(value, options).cast(value, options)
}
validate(value, options, maybeCb) {
return this._resolve(value, options).validate(value, options, maybeCb)
}
validateSync(value, options) {
return this._resolve(value, options).validateSync(value, options)
}
validateAt(path, value, options) {
return this._resolve(value, options).validateAt(path, value, options)
}
validateSyncAt(path, value, options) {
return this._resolve(value, options).validateSyncAt(path, value, options)
}
}

Lazy.prototype.__isYupSchema__ = true

export default Lazy
Loading

0 comments on commit a49dbdd

Please sign in to comment.