2019-01-03 17:14:25 +03:00
|
|
|
import jsan from 'jsan';
|
|
|
|
import { DATA_TYPE_KEY, DATA_REF_KEY } from '../constants/dataTypes';
|
|
|
|
|
2020-10-26 02:32:04 +03:00
|
|
|
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 &&
|
2020-10-26 02:32:04 +03:00
|
|
|
typeof (value as any).data === 'object'
|
2019-01-03 17:14:25 +03:00
|
|
|
) {
|
2020-10-26 02:32:04 +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)
|
2020-10-26 02:32:04 +03:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2020-10-26 02:32:04 +03:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|