2023-01-19 16:40:52 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { ApiErrorResponse, isApiErrorResponse } from '@woocommerce/types';
|
2023-01-30 15:12:17 +00:00
|
|
|
import { createNotice } from '@woocommerce/base-utils';
|
2023-01-19 16:40:52 +00:00
|
|
|
import { decodeEntities } from '@wordpress/html-entities';
|
|
|
|
import { dispatch } from '@wordpress/data';
|
|
|
|
|
|
|
|
/**
|
2024-08-14 14:24:44 +00:00
|
|
|
* This function is used to normalize errors into an array of valid ApiErrorResponse objects.
|
|
|
|
*/
|
|
|
|
const filterValidErrors = ( errors: ApiErrorResponse[] ) => {
|
|
|
|
return errors.filter( isApiErrorResponse );
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This function is used to notify the user of errors/conflicts from an API error response object.
|
|
|
|
*/
|
|
|
|
const createNoticesFromErrors = ( errors: ApiErrorResponse[] ) => {
|
|
|
|
errors.forEach( ( error ) => {
|
|
|
|
createNotice( 'error', decodeEntities( error.message ), {
|
|
|
|
id: error.code,
|
|
|
|
context: error?.data?.context || 'wc/cart',
|
|
|
|
} );
|
|
|
|
} );
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This function is used to dismiss old errors from the store.
|
|
|
|
*/
|
|
|
|
const dismissNoticesFromErrors = ( errors: ApiErrorResponse[] ) => {
|
|
|
|
errors.forEach( ( error ) => {
|
|
|
|
dispatch( 'core/notices' ).removeNotice(
|
|
|
|
error.code,
|
|
|
|
error?.data?.context || 'wc/cart'
|
|
|
|
);
|
|
|
|
} );
|
|
|
|
};
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This function is used to notify the user of cart errors/conflicts.
|
2023-01-19 16:40:52 +00:00
|
|
|
*/
|
|
|
|
export const notifyCartErrors = (
|
|
|
|
errors: ApiErrorResponse[] | null = null,
|
|
|
|
oldErrors: ApiErrorResponse[] | null = null
|
|
|
|
) => {
|
2024-08-14 14:24:44 +00:00
|
|
|
if ( oldErrors !== null ) {
|
|
|
|
dismissNoticesFromErrors( filterValidErrors( oldErrors ) );
|
2023-01-19 16:40:52 +00:00
|
|
|
}
|
|
|
|
if ( errors !== null ) {
|
2024-08-14 14:24:44 +00:00
|
|
|
createNoticesFromErrors( filterValidErrors( errors ) );
|
2023-01-19 16:40:52 +00:00
|
|
|
}
|
|
|
|
};
|