-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathasyncValidation.js
More file actions
39 lines (36 loc) · 908 Bytes
/
asyncValidation.js
File metadata and controls
39 lines (36 loc) · 908 Bytes
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
// @flow
import isPromise from 'is-promise'
type Callback = () => Promise<void>
type StartCallback = (field: string) => void
type StopCallback = (errors: ?Object) => void
const asyncValidation = (
fn: Callback,
start: StartCallback,
stop: StopCallback,
field: string
) => {
start(field)
const promise = fn()
if (!isPromise(promise)) {
throw new Error(
'asyncValidate function passed to reduxForm must return a promise'
)
}
const handleErrors = rejected => errors => {
if (rejected) {
if (errors && Object.keys(errors).length) {
stop(errors)
return errors
} else {
stop()
throw new Error(
'Asynchronous validation promise was rejected without errors.'
)
}
}
stop()
return Promise.resolve()
}
return promise.then(handleErrors(false), handleErrors(true))
}
export default asyncValidation