-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathvalidate.js
117 lines (100 loc) · 4.12 KB
/
validate.js
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
/*
we want to take all the validate members from the provided wallet
and compose into a single yup schema for formik validation ...
the validate member can be on of:
- a yup schema
- a function that throws on an invalid value
- a regular expression that must match
*/
import { autowithdrawSchemaMembers, vaultEntrySchema } from '@/lib/validate'
import * as Yup from '@/lib/yup'
import { canReceive } from './common'
export default async function validateWallet (walletDef, data,
{ yupOptions = { abortEarly: true }, topLevel = true, serverSide = false, skipGenerated = false } = {}) {
let schema = composeWalletSchema(walletDef, serverSide, skipGenerated)
if (canReceive({ def: walletDef, config: data })) {
schema = schema.concat(autowithdrawSchemaMembers)
}
await schema.validate(data, yupOptions)
const casted = schema.cast(data, { assert: false })
if (topLevel && walletDef.validate) {
await walletDef.validate(casted)
}
return casted
}
function createFieldSchema (name, validate) {
if (!validate) {
throw new Error(`No validation provided for field ${name}`)
}
if (Yup.isSchema(validate)) {
// If validate is already a Yup schema, return it directly
return validate
} else if (typeof validate === 'function') {
// If validate is a function, create a custom Yup test
return Yup.mixed().test({
name,
test: (value, context) => {
try {
validate(value)
return true
} catch (error) {
return context.createError({ message: error.message })
}
}
})
} else if (validate instanceof RegExp) {
// If validate is a regular expression, use Yup.matches
return Yup.string().matches(validate, `${name} is invalid`)
} else {
throw new Error(`validate for ${name} must be a yup schema, function, or regular expression`)
}
}
function composeWalletSchema (walletDef, serverSide, skipGenerated) {
const { fields } = walletDef
const vaultEntrySchemas = { required: [], optional: [] }
const cycleBreaker = []
const schemaShape = fields.reduce((acc, field) => {
const { name, validate, optional, generated, clientOnly, requiredWithout } = field
if (generated && skipGenerated) {
return acc
}
if (clientOnly && serverSide) {
// For server-side validation, accumulate clientOnly fields as vaultEntries
vaultEntrySchemas[(optional || generated) ? 'optional' : 'required'].push(vaultEntrySchema(name))
} else {
acc[name] = createFieldSchema(name, validate)
if (!optional) {
acc[name] = acc[name].required('required')
} else if (requiredWithout) {
const myName = serverSide ? 'vaultEntries' : name
const partnerName = serverSide ? 'vaultEntries' : requiredWithout
// if a cycle breaker between this pair hasn't been added yet, add it
if (!cycleBreaker.some(pair => pair[1] === myName)) {
cycleBreaker.push([myName, partnerName])
}
// if we are the server, the pairSetting will be in the vaultEntries array
acc[name] = acc[name].when([partnerName], ([pairSetting], schema) => {
if (!pairSetting || (serverSide && !pairSetting.some(v => v.key === requiredWithout))) {
return schema.required(`required if ${requiredWithout} not set`)
}
return Yup.mixed().or([schema.test({
test: value => value !== pairSetting,
message: `${name} cannot be the same as ${requiredWithout}`
}), Yup.mixed().notRequired()])
})
}
}
return acc
}, {})
// Finalize the vaultEntries schema if it exists
if (vaultEntrySchemas.required.length > 0 || vaultEntrySchemas.optional.length > 0) {
schemaShape.vaultEntries = Yup.array().equalto(vaultEntrySchemas)
}
// we use cycleBreaker to avoid cyclic dependencies in Yup schema
// see https://github.com/jquense/yup/issues/176#issuecomment-367352042
const composedSchema = Yup.object().shape(schemaShape, cycleBreaker).concat(Yup.object({
enabled: Yup.boolean(),
priority: Yup.number().min(0, 'must be at least 0').max(100, 'must be at most 100')
}))
return composedSchema
}