hrms-api-kpi/src/interfaces/utils.ts
2025-10-29 09:54:37 +07:00

77 lines
2 KiB
TypeScript

import { RequestWithUser } from "../middlewares/user";
export type DataDiff = {
before: any;
after: any;
};
export type LogSequence = {
action: string;
status: "success" | "error";
description: string;
query?: any;
request?: {
method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
url?: string;
payload?: string;
response?: string;
};
};
export function setLogDataDiff(req: RequestWithUser, data: DataDiff) {
// Check if data.before and data.after are valid objects
if (
data.before &&
typeof data.before === "object" &&
data.after &&
typeof data.after === "object"
) {
req.app.locals.logData.dataDiff = {
before: safeStringify(data.before),
after: safeStringify(data.after),
};
} else {
console.error("Invalid data provided: both before and after must be valid objects.");
}
}
export function addLogSequence(req: RequestWithUser, data: LogSequence) {
if (!req?.app?.locals?.logData?.sequence) {
req.app.locals.logData.sequence = [];
}
req.app.locals.logData.sequence = req.app.locals.logData.sequence.concat(data);
}
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]";
}
}