redux-devtools/packages/redux-devtools-app/src/utils/parseJSON.ts

43 lines
1.1 KiB
TypeScript
Raw Normal View History

2019-01-03 17:14:25 +03:00
import jsan from 'jsan';
import { DATA_TYPE_KEY, DATA_REF_KEY } from '../constants/dataTypes';
export function reviver(key: string, value: unknown) {
2019-01-03 17:14:25 +03:00
if (
2019-01-10 21:51:14 +03:00
typeof value === 'object' &&
value !== null &&
'__serializedType__' in value &&
typeof (value as any).data === 'object'
2019-01-03 17:14:25 +03:00
) {
const data = (value as any).data;
data[DATA_TYPE_KEY] = (value as any).__serializedType__;
2019-01-10 21:51:14 +03:00
if ('__serializedRef__' in value)
data[DATA_REF_KEY] = (value as any).__serializedRef__;
2019-01-03 17:14:25 +03:00
/*
if (Array.isArray(data)) {
data.__serializedType__ = value.__serializedType__;
} else {
Object.defineProperty(data, '__serializedType__', {
value: value.__serializedType__
});
}
*/
return data;
}
return value;
}
export default function parseJSON(
data: string | undefined,
serialize?: boolean
) {
2019-01-03 17:14:25 +03:00
if (typeof data !== 'string') return data;
try {
return serialize ? jsan.parse(data, reviver) : jsan.parse(data);
} catch (e) {
2019-01-10 21:51:14 +03:00
if (process.env.NODE_ENV !== 'production')
/* eslint-disable-next-line no-console */
console.error(data + 'is not a valid JSON', e);
2019-01-03 17:14:25 +03:00
return undefined;
}
}