woocommerce/plugins/woocommerce-blocks/assets/js/data/utils/process-error-response.ts

149 lines
3.7 KiB
TypeScript
Raw Normal View History

New contexts for `StoreNoticesContainer` and notice grouping (https://github.com/woocommerce/woocommerce-blocks/pull/7711) * Refactor Store Notices Move snackbar hiding filter before notice creation Implements showApplyCouponNotice Refactor context providers Use STORE_NOTICE_CONTEXTS use refs to track notice containers Refactor ref usage Use existing noticeContexts * Move new notice code to checkout package * Combine store and snackbars * Update noticeContexts imports * Remove context provider * Update data store * Fix 502 * Add new error contexts * Force types * Unnecessary reorder of imports * Fix global handling * Document forceType * Optional props are undefined * Remove function name * Missing condition * Remove context prop * Define ACTION_TYPES * Remove controls * Update assets/js/base/context/event-emit/utils.ts Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * CONTACT_INFORMATION * Remove ref from registerContainer * Abstract container locating methods * pass context correctly when displaying notices * Remove debugging buttons * Update filter usage - remove useMemo so filter can work inline * Refactor existing error notices from the API (https://github.com/woocommerce/woocommerce-blocks/pull/7728) * Update API type defs * Move create notice utils * Replace useCheckoutNotices with new contexts * processCheckoutResponseHeaders should check headers are defined * Scroll to error notices only if we're not editing a field * Error handling utils * processErrorResponse when pushing changes * processErrorResponse when processing checkout * remove formatStoreApiErrorMessage * Add todo for cart errors * Remove unused deps * unused imports * Fix linting warnings * Unused dep * Update assets/js/types/type-defs/api-response.ts Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Add todo * Use generic * remove const * Update array types * Phone should be in address blocks Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com> * Update store name to wc/store/store-notices * Fix assertResponseIsValid * Funnel woocommerce_rest_invalid_email_address to the correct place * woocommerce_rest_missing_email_address * Move comments around * Move data back into const * Spacing * Remove spacing * Remove forced snack bar and styling * Move notices within wrapper * Remove type * hasStoreNoticesContainer rename * Group by status/context * Remove global context * Remove white space * remove changes to simplify diff * white space * Move comment to typescript * List style * showApplyCouponNotice docs * See if scrollIntoView exists * fix notice tests Co-authored-by: Thomas Roberts <5656702+opr@users.noreply.github.com>
2022-12-19 15:30:13 +00:00
/**
* External dependencies
*/
import {
createNotice,
createNoticeIfVisible,
DEFAULT_ERROR_MESSAGE,
} from '@woocommerce/base-utils';
import { decodeEntities } from '@wordpress/html-entities';
import { isObject, objectHasProp, ApiErrorResponse } from '@woocommerce/types';
import { noticeContexts } from '@woocommerce/base-context/event-emit/utils';
type ApiParamError = {
param: string;
id: string;
code: string;
message: string;
};
const isApiResponse = ( response: unknown ): response is ApiErrorResponse => {
return (
isObject( response ) &&
objectHasProp( response, 'code' ) &&
objectHasProp( response, 'message' ) &&
objectHasProp( response, 'data' )
);
};
/**
* Flattens error details which are returned from the API when multiple params are not valid.
*
* - Codes will be prefixed with the param. For example, `invalid_email` becomes `billing_address_invalid_email`.
* - Additional error messages will be flattened alongside the main error message.
* - Supports 1 level of nesting.
* - Decodes HTML entities in error messages.
*/
const getErrorDetails = ( response: ApiErrorResponse ): ApiParamError[] => {
const errorDetails = objectHasProp( response.data, 'details' )
? Object.entries( response.data.details )
: null;
if ( ! errorDetails ) {
return [];
}
return errorDetails.reduce(
(
acc,
[
param,
{ code, message, additional_errors: additionalErrors = [] },
]
) => {
return [
...acc,
{
param,
id: `${ param }_${ code }`,
code,
message: decodeEntities( message ),
},
...( Array.isArray( additionalErrors )
? additionalErrors.flatMap( ( additionalError ) => {
if (
! objectHasProp( additionalError, 'code' ) ||
! objectHasProp( additionalError, 'message' )
) {
return [];
}
return [
{
param,
id: `${ param }_${ additionalError.code }`,
code: additionalError.code,
message: decodeEntities(
additionalError.message
),
},
];
} )
: [] ),
];
},
[] as ApiParamError[]
);
};
/**
* Processes the response for an invalid param error, with response code rest_invalid_param.
*/
const processInvalidParamResponse = ( response: ApiErrorResponse ) => {
const errorDetails = getErrorDetails( response );
errorDetails.forEach( ( { code, message, id, param } ) => {
switch ( code ) {
case 'invalid_email':
createNotice( 'error', message, {
id,
context: noticeContexts.CONTACT_INFORMATION,
} );
return;
}
switch ( param ) {
case 'billing_address':
createNoticeIfVisible( 'error', message, {
id,
context: noticeContexts.BILLING_ADDRESS,
} );
break;
case 'shipping_address':
createNoticeIfVisible( 'error', message, {
id,
context: noticeContexts.SHIPPING_ADDRESS,
} );
break;
}
} );
};
/**
* Takes an API response object and creates error notices to display to the customer.
*
* This is where we can handle specific error codes and display notices in specific contexts.
*/
const processErrorResponse = ( response: ApiErrorResponse ) => {
if ( ! isApiResponse( response ) ) {
return;
}
switch ( response.code ) {
case 'woocommerce_rest_missing_email_address':
case 'woocommerce_rest_invalid_email_address':
createNotice( 'error', response.message, {
id: response.code,
context: noticeContexts.CONTACT_INFORMATION,
} );
break;
case 'rest_invalid_param':
processInvalidParamResponse( response );
break;
default:
createNotice( 'error', response.message || DEFAULT_ERROR_MESSAGE, {
id: response.code,
context: noticeContexts.CHECKOUT,
} );
}
};
export default processErrorResponse;