detect valid JSON string to not parse twice

This commit is contained in:
Pierre Noël 2022-02-11 17:03:40 +01:00
parent 8c2251bb79
commit 8ccd3406b6
5 changed files with 48 additions and 3 deletions

View File

@ -0,0 +1,17 @@
import isValidJSONString from '../utils/isValidJSONString';
describe('CONTENT MANAGER | COMPONENTS | EditViewDataManagerProvider | isValidJSONString', () => {
it.each([
['"coucou"', true],
['"cou\\" \\"cou"', true],
['"coucou', false],
['"cou" "cou"', false],
['{}', false],
['null', false],
['', false],
['[]', false],
])('%s is a JSON string: %s', (value, expectedResult) => {
const result = isValidJSONString(value);
expect(result).toBe(expectedResult);
});
});

View File

@ -18,7 +18,12 @@ const cleanData = (retrievedData, currentSchema, componentsSchema) => {
switch (attrType) {
case 'json':
cleanedData = value;
try {
cleanedData = JSON.parse(value);
} catch (err) {
cleanedData = value;
}
break;
// TODO
// case 'date':

View File

@ -0,0 +1,15 @@
const isValidJSONString = value => {
if (typeof value === 'string' && value.startsWith('"') && value.endsWith('"')) {
try {
JSON.parse(value);
return true;
} catch {
return false;
}
}
return false;
};
export default isValidJSONString;

View File

@ -13,6 +13,8 @@ import {
import * as yup from 'yup';
import { translatedErrors as errorsTrads } from '@strapi/helper-plugin';
import isValidJSONString from './isValidJSONString';
yup.addMethod(yup.mixed, 'defined', function() {
return this.test('defined', errorsTrads.required, value => value !== undefined);
});
@ -224,7 +226,13 @@ const createYupSchemaAttribute = (type, validations, options) => {
return true;
}
if (isNumber(value) || isNull(value) || isObject(value) || isArray(value)) {
if (
isValidJSONString(value) ||
isNumber(value) ||
isNull(value) ||
isObject(value) ||
isArray(value)
) {
return true;
}

View File

@ -80,7 +80,7 @@ class InputJSON extends React.Component {
try {
if (value === null) return this.codeMirror.setValue('');
const nextValue = typeof value !== 'string' ? stringify(value, null, 2) : value;
const nextValue = stringify(value, null, 2);
return this.codeMirror.setValue(nextValue);
} catch (err) {