test safeStringify

This commit is contained in:
Adisak 2025-10-29 09:54:37 +07:00
parent ef2476bade
commit f3e90ef955
2 changed files with 39 additions and 9 deletions

View file

@ -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]";
}
}