61 lines
1.8 KiB
TypeScript
Raw Normal View History

import type { Dispatch, SetStateAction } from 'react'
import { useCallback, useState } from 'react'
import debounce from 'lodash-es/debounce'
import type { DebouncedFunc } from 'lodash-es'
2023-05-15 08:51:32 +08:00
import { validateProviderKey } from '@/service/common'
export enum ValidatedStatus {
Success = 'success',
Error = 'error',
Exceed = 'exceed',
2023-05-15 08:51:32 +08:00
}
export type ValidatedStatusState = {
status?: ValidatedStatus
message?: string
}
// export type ValidatedStatusState = ValidatedStatus | undefined | ValidatedError
export type SetValidatedStatus = Dispatch<SetStateAction<ValidatedStatusState>>
2023-05-23 14:15:33 +08:00
export type ValidateFn = DebouncedFunc<(token: any, config: ValidateFnConfig) => void>
type ValidateTokenReturn = [
boolean,
ValidatedStatusState,
2023-05-23 14:15:33 +08:00
SetValidatedStatus,
ValidateFn,
2023-05-23 14:15:33 +08:00
]
export type ValidateFnConfig = {
beforeValidating: (token: any) => boolean
}
2023-05-15 08:51:32 +08:00
2023-05-23 14:15:33 +08:00
const useValidateToken = (providerName: string): ValidateTokenReturn => {
2023-05-15 08:51:32 +08:00
const [validating, setValidating] = useState(false)
const [validatedStatus, setValidatedStatus] = useState<ValidatedStatusState>({})
2023-05-23 14:15:33 +08:00
const validate = useCallback(debounce(async (token: string, config: ValidateFnConfig) => {
if (!config.beforeValidating(token))
2023-05-23 14:15:33 +08:00
return false
2023-05-15 08:51:32 +08:00
setValidating(true)
try {
const res = await validateProviderKey({ url: `/workspaces/current/providers/${providerName}/token-validate`, body: { token } })
setValidatedStatus(
res.result === 'success'
? { status: ValidatedStatus.Success }
: { status: ValidatedStatus.Error, message: res.error })
}
catch (e: any) {
setValidatedStatus({ status: ValidatedStatus.Error, message: e.message })
}
finally {
2023-05-15 08:51:32 +08:00
setValidating(false)
}
}, 500), [])
return [
validating,
validatedStatus,
2023-05-23 14:15:33 +08:00
setValidatedStatus,
validate,
2023-05-15 08:51:32 +08:00
]
}
export default useValidateToken