mirror of
https://github.com/strapi/strapi.git
synced 2025-12-10 22:44:39 +00:00
detect valid JSON string to not parse twice
This commit is contained in:
parent
8c2251bb79
commit
8ccd3406b6
@ -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);
|
||||
});
|
||||
});
|
||||
@ -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':
|
||||
|
||||
@ -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;
|
||||
@ -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;
|
||||
}
|
||||
|
||||
|
||||
@ -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) {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user