refactor(helper-plugin): extract params based on error type

test(helper-plugin): getYupInnerErrors
This commit is contained in:
Jamie Howard 2023-02-10 11:48:02 +00:00
parent d4e111a027
commit 6d5fd07184
2 changed files with 34 additions and 10 deletions

View File

@ -1,24 +1,24 @@
/**
* Extract relevant values from the Yup error that can be used to enhance front
* end error messaging
* @param {Object} yupErrorParams
* @returns {Object}
* @param {String} errorType
* @param {Object} errorParams
* @returns {Object} values to pass to error translation string
*/
const extractValuesFromYupError = (yupErrorParams = {}) =>
Object.keys(yupErrorParams)
.filter((key) => !['label', 'originalValue', 'path', 'value'].includes(key))
.reduce((current, key) => Object.assign(current, { [key]: yupErrorParams[key] }), {});
const extractValuesFromYupError = (errorType, errorParams = {}) =>
Object.keys(errorParams)
.filter((key) => errorType === key)
.reduce((current, key) => Object.assign(current, { [key]: errorParams[key] }), {});
const getYupInnerErrors = (error) => {
return (error?.inner || []).reduce((acc, currentError) => {
const getYupInnerErrors = (error) =>
(error?.inner || []).reduce((acc, currentError) => {
acc[currentError.path.split('[').join('.').split(']').join('')] = {
id: currentError.message,
defaultMessage: currentError.message,
values: extractValuesFromYupError(currentError?.params || {}),
values: extractValuesFromYupError(currentError.type, currentError?.params || {}),
};
return acc;
}, {});
};
export default getYupInnerErrors;

View File

@ -0,0 +1,24 @@
import getYupInnerErrors from '../index';
describe('getYupInnerErrors', () => {
test('can extract relevant parameters from an error', () => {
const maxError = {
inner: [
{
path: 'Name',
type: 'max',
params: { max: 5 },
message: 'components.Input.error.validation.maxLength',
},
],
};
expect(getYupInnerErrors(maxError)).toMatchObject({
Name: {
id: 'components.Input.error.validation.maxLength',
defaultMessage: 'components.Input.error.validation.maxLength',
values: { max: 5 },
},
});
});
});