test safeStringify
This commit is contained in:
parent
ef2476bade
commit
f3e90ef955
2 changed files with 39 additions and 9 deletions
|
|
@ -27,8 +27,8 @@ export function setLogDataDiff(req: RequestWithUser, data: DataDiff) {
|
|||
typeof data.after === "object"
|
||||
) {
|
||||
req.app.locals.logData.dataDiff = {
|
||||
before: JSON.stringify(data.before),
|
||||
after: JSON.stringify(data.after),
|
||||
before: safeStringify(data.before),
|
||||
after: safeStringify(data.after),
|
||||
};
|
||||
} else {
|
||||
console.error("Invalid data provided: both before and after must be valid objects.");
|
||||
|
|
@ -45,3 +45,33 @@ export function addLogSequence(req: RequestWithUser, data: LogSequence) {
|
|||
export function editLogSequence(req: RequestWithUser, index: number, data: LogSequence) {
|
||||
req.app.locals.logData.sequence[index] = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* ปลอดภัยกว่า JSON.stringify()
|
||||
* - กัน circular reference
|
||||
* - จำกัดความลึก
|
||||
* - return string แน่นอนเสมอ
|
||||
*/
|
||||
export function safeStringify(obj: any, space?: number): string {
|
||||
const cache = new WeakSet();
|
||||
|
||||
try {
|
||||
return JSON.stringify(
|
||||
obj,
|
||||
(key, value) => {
|
||||
// ป้องกัน circular reference
|
||||
if (typeof value === "object" && value !== null) {
|
||||
if (cache.has(value)) {
|
||||
return "[Circular]";
|
||||
}
|
||||
cache.add(value);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
space,
|
||||
);
|
||||
} catch (err) {
|
||||
console.error("⚠️ safeStringify error:", err);
|
||||
return "[Unserializable object]";
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue