mirror of
https://github.com/n8n-io/n8n.git
synced 2025-03-05 20:50:17 -08:00
fix(core): Handle Date and RegExp correctly in jsonStringify (#5812)
This commit is contained in:
parent
522c790817
commit
4f91525022
|
@ -67,17 +67,16 @@ type JSONStringifyOptions = {
|
||||||
};
|
};
|
||||||
|
|
||||||
const replaceCircularReferences = <T>(value: T, knownObjects = new WeakSet()): T => {
|
const replaceCircularReferences = <T>(value: T, knownObjects = new WeakSet()): T => {
|
||||||
if (value && typeof value === 'object') {
|
if (typeof value !== 'object' || value === null || value instanceof RegExp) return value;
|
||||||
if (knownObjects.has(value)) return '[Circular Reference]' as T;
|
if ('toJSON' in value && typeof value.toJSON === 'function') return value.toJSON() as T;
|
||||||
knownObjects.add(value);
|
if (knownObjects.has(value)) return '[Circular Reference]' as T;
|
||||||
const copy = (Array.isArray(value) ? [] : {}) as T;
|
knownObjects.add(value);
|
||||||
for (const key in value) {
|
const copy = (Array.isArray(value) ? [] : {}) as T;
|
||||||
copy[key] = replaceCircularReferences(value[key], knownObjects);
|
for (const key in value) {
|
||||||
}
|
copy[key] = replaceCircularReferences(value[key], knownObjects);
|
||||||
knownObjects.delete(value);
|
|
||||||
return copy;
|
|
||||||
}
|
}
|
||||||
return value;
|
knownObjects.delete(value);
|
||||||
|
return copy;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const jsonStringify = (obj: unknown, options: JSONStringifyOptions = {}): string => {
|
export const jsonStringify = (obj: unknown, options: JSONStringifyOptions = {}): string => {
|
||||||
|
|
|
@ -18,7 +18,7 @@ describe('jsonParse', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('jsonStringify', () => {
|
describe('jsonStringify', () => {
|
||||||
const source: any = { a: 1, b: 2 };
|
const source: any = { a: 1, b: 2, d: new Date(1680089084200), r: new RegExp('^test$', 'ig') };
|
||||||
source.c = source;
|
source.c = source;
|
||||||
|
|
||||||
it('should throw errors on circular references by default', () => {
|
it('should throw errors on circular references by default', () => {
|
||||||
|
@ -27,7 +27,7 @@ describe('jsonStringify', () => {
|
||||||
|
|
||||||
it('should break circular references when requested', () => {
|
it('should break circular references when requested', () => {
|
||||||
expect(jsonStringify(source, { replaceCircularRefs: true })).toEqual(
|
expect(jsonStringify(source, { replaceCircularRefs: true })).toEqual(
|
||||||
'{"a":1,"b":2,"c":"[Circular Reference]"}',
|
'{"a":1,"b":2,"d":"2023-03-29T11:24:44.200Z","r":{},"c":"[Circular Reference]"}',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue