Skip to content

Commit a6d09fa

Browse files
fix: stringify 循环引用使用标准库实现 (#28)
Co-authored-by: 刘宇阳 <myronliu347@gmail.com>
1 parent e8b8f61 commit a6d09fa

3 files changed

Lines changed: 2157 additions & 2144 deletions

File tree

packages/basic/package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@
4242
"mockjs": "1.1.0",
4343
"moment": "2.30.1",
4444
"moment-timezone": "0.5.45",
45-
"qs": "6.11.2"
45+
"qs": "6.11.2",
46+
"safe-json-stringify": "^1.2.0"
4647
},
4748
"devDependencies": {
4849
"@jest/globals": "^29.7.0",
@@ -53,6 +54,7 @@
5354
"@types/jest": "^29.5.12",
5455
"@types/lodash": "^4.17.13",
5556
"@types/node": "^20.11.16",
57+
"@types/safe-json-stringify": "^1.1.5",
5658
"fast-check": "^3.14.0",
5759
"jest": "^29.7.0",
5860
"jest-environment-jsdom": "^29.7.0",

packages/basic/src/utils/create/utils.ts

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import safeJSONStringify from 'safe-json-stringify';
2+
13
type Nil = null | undefined;
24
/**
35
* 若有定义errorMessage为string,且data中包含errorMsg字段,则直接写入字段尝试替换错误信息
@@ -8,8 +10,8 @@ export function overwriteErrorMsgFieldIfSpecified(
810
data: (Record<string, unknown> & { errorMsg?: string | Nil }) | Nil,
911
errorMessage: string | Nil,
1012
) {
11-
if (typeof errorMessage === "string" && data) {
12-
if ("errorMsg" in data) {
13+
if (typeof errorMessage === 'string' && data) {
14+
if ('errorMsg' in data) {
1315
data.errorMsg = errorMessage;
1416
}
1517
}
@@ -18,26 +20,19 @@ export function overwriteErrorMsgFieldIfSpecified(
1820
/**
1921
* stringfy 过滤掉 function 和循环引用
2022
* */
21-
export function stringifyWithLoopProtection(obj, replacer?, space?) {
22-
const seen = new WeakSet();
23+
export function stringifyWithLoopProtection(obj: any, replacer?: any, space?: any) {
2324
let hasCircleProp = false;
24-
const result = JSON.stringify(
25+
26+
const result = safeJSONStringify(
2527
obj,
26-
function (key, value) {
27-
if (typeof value === "object" && value !== null) {
28-
if (seen.has(value)) {
29-
hasCircleProp = true;
30-
// 如果已经见过该对象,则返回undefined;
31-
return undefined;
32-
}
33-
seen.add(value);
34-
}
35-
// 使用用户提供的replacer函数(如果有的话)
36-
if (replacer) {
37-
return replacer(key, value);
38-
} else {
39-
return value;
28+
(key, value) => {
29+
if (value === '[Circular]') {
30+
// 循环引用
31+
hasCircleProp = true;
32+
return undefined;
4033
}
34+
35+
return replacer(key, value);
4136
},
4237
space,
4338
);

0 commit comments

Comments
 (0)