-
Notifications
You must be signed in to change notification settings - Fork 5
/
useCaptcha.ts
56 lines (53 loc) · 2.02 KB
/
useCaptcha.ts
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
import { T$, Tupd$, TuseFlag$, TuseMemorizedCallback$, T_$, T_exp$ } from '@/framework/type';
import { buildErrorMsg, createAssert, newInstance } from '@/helper';
import { falseValue, PromiseCls, trueValue, undefinedValue } from '@/helper/variables';
import { AlovaMethodHandler, Method, useRequest } from 'alova';
import { CaptchaHookConfig } from '~/typings/general';
const hookPrefix = 'useCaptcha';
const captchaAssert = createAssert(hookPrefix);
export default <S, E, R, T, RC, RE, RH, ARG extends any[]>(
handler: Method<S, E, R, T, RC, RE, RH> | AlovaMethodHandler<S, E, R, T, RC, RE, RH, ARG>,
config: CaptchaHookConfig<S, E, R, T, RC, RE, RH, ARG>,
$: T$,
upd$: Tupd$,
_$: T_$,
_exp$: T_exp$,
useFlag$: TuseFlag$,
useMemorizedCallback$: TuseMemorizedCallback$
) => {
const { initialCountdown, middleware } = config;
captchaAssert(initialCountdown === undefinedValue || initialCountdown > 0, 'initialCountdown must be greater than 0');
const countdown = $(0, trueValue);
const requestReturned = useRequest(handler, {
...config,
immediate: falseValue,
middleware: middleware ? (ctx, next) => middleware({ ...ctx, send }, next) : undefinedValue
});
const timer = useFlag$(undefinedValue as NodeJS.Timeout | undefined);
const send = useMemorizedCallback$((...args: any[]) =>
newInstance(PromiseCls, (resolve, reject) => {
if (_$(countdown) <= 0) {
requestReturned
.send(...(args as any))
.then(result => {
upd$(countdown, config.initialCountdown || 60);
timer.current = setInterval(() => {
upd$(countdown, val => val - 1);
if (_$(countdown) <= 0) {
clearInterval(timer.current);
}
}, 1000);
resolve(result);
})
.catch(reason => reject(reason));
} else {
reject(new Error(buildErrorMsg(hookPrefix, 'the countdown is not over yet')));
}
})
);
return {
...requestReturned,
send,
countdown: _exp$(countdown)
};
};