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 | 277x 277x 278x 55x 55x 55x 55x 277x 277x 40x 40x 40x 38x 30x 40x 237x 237x 237x 237x 231x 192x 141x 141x | import { mapValues } from '../../../utils'
import Ref from '../Reference'
import ValidationError from '../ValidationError'
export default function createValidation(config) {
function validate(
{ value, path, label, options, originalValue, sync, ...rest },
cb,
) {
const { name, test, params, message } = config
let { parent, context, rootValue } = options
function resolve(item) {
return Ref.isRef(item)
? item.getValue(value, parent, context, rootValue)
: item
}
function createError(overrides = {}) {
const nextParams = mapValues(
{
value,
originalValue,
label,
path: overrides.path || path,
...params,
...overrides.params,
},
resolve,
)
const error = new ValidationError(
ValidationError.formatError(overrides.message || message, nextParams),
value,
nextParams.path,
overrides.type || name,
)
error.params = nextParams
return error
}
let ctx = {
path,
parent,
type: name,
createError,
resolve,
options,
originalValue,
...rest,
}
if (!sync) {
try {
Promise.resolve(test.call(ctx, value, ctx)).then(validOrError => {
if (ValidationError.isError(validOrError)) cb(validOrError)
else if (!validOrError) cb(createError())
else cb(null, validOrError)
})
} catch (err) {
cb(err)
}
return
}
let result
try {
result = test.call(ctx, value, ctx)
Iif (typeof result?.then === 'function') {
throw new Error(
`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` +
`This test will finish after the validate call has returned`,
)
}
} catch (err) {
cb(err)
return
}
if (ValidationError.isError(result)) cb(result)
else if (!result) cb(createError())
else cb(null, result)
}
validate.OPTIONS = config
return validate
}
|