| 1 |
import {Gateway, isFormResponseGatewayError, isFormResponseValidationError} from '@givewp/forms/types'; |
| 2 |
import generateRequestErrors from '../utilities/generateRequestErrors'; |
| 3 |
import FormRequestError from '../errors/FormRequestError'; |
| 4 |
|
| 5 |
import {__} from '@wordpress/i18n'; |
| 6 |
import {FieldValues, UseFormSetError} from 'react-hook-form'; |
| 7 |
import postFormData from '@givewp/forms/app/utilities/postFormData'; |
| 8 |
import convertValuesToFormData from '@givewp/forms/app/utilities/convertValuesToFormData'; |
| 9 |
import {getAuthToken} from '@givewp/forms/app/utilities/authToken'; |
| 10 |
|
| 11 |
/** |
| 12 |
* @since 4.17.0 Send the auth token so embedded forms stay signed in without cookies |
| 13 |
* @since 3.0.0 |
| 14 |
*/ |
| 15 |
export default async function handleValidationRequest( |
| 16 |
validateUrl: string, |
| 17 |
values: FieldValues, |
| 18 |
setError: UseFormSetError<FieldValues>, |
| 19 |
gateway?: Gateway |
| 20 |
) { |
| 21 |
if (gateway !== undefined && values?.donationType === 'subscription' && !gateway.supportsSubscriptions) { |
| 22 |
return setError('FORM_ERROR', { |
| 23 |
message: __( |
| 24 |
'This payment gateway does not support recurring payments, please try selecting another payment gateway.', |
| 25 |
'give' |
| 26 |
), |
| 27 |
}); |
| 28 |
} |
| 29 |
|
| 30 |
try { |
| 31 |
const formData = convertValuesToFormData({...values, authToken: getAuthToken()}); |
| 32 |
|
| 33 |
const {response} = await postFormData(validateUrl, formData); |
| 34 |
|
| 35 |
const formResponse = await response.json(); |
| 36 |
|
| 37 |
if (isFormResponseGatewayError(formResponse) || isFormResponseValidationError(formResponse)) { |
| 38 |
throw new FormRequestError(formResponse.data.errors.errors); |
| 39 |
} else { |
| 40 |
return true; |
| 41 |
} |
| 42 |
} catch (error) { |
| 43 |
if (error instanceof FormRequestError) { |
| 44 |
return generateRequestErrors(values, error.errors, setError); |
| 45 |
} |
| 46 |
|
| 47 |
return setError('FORM_ERROR', { |
| 48 |
message: error?.message ?? __('Something went wrong, please try again or contact support.', 'give'), |
| 49 |
}); |
| 50 |
} |
| 51 |
} |
| 52 |
|