datasquirel/package-shared/functions/backend/serverError.js

91 lines
2.6 KiB
JavaScript
Raw Normal View History

2024-11-06 06:26:23 +00:00
// @ts-check
const fs = require("fs");
2024-12-06 10:31:24 +00:00
const { IncomingMessage } = require("http");
2024-11-06 06:26:23 +00:00
/**
2024-12-08 08:58:57 +00:00
* # Server Error
*
2024-11-06 06:26:23 +00:00
* @param {{
* user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *,
* message: string,
* component?: string,
* noMail?: boolean,
2024-12-06 10:31:24 +00:00
* req?: import("next").NextApiRequest & IncomingMessage,
2024-11-06 06:26:23 +00:00
* }} params - user id
*
* @returns {Promise<void>}
*/
module.exports = async function serverError({
user,
message,
component,
noMail,
2024-12-06 10:31:24 +00:00
req,
2024-11-06 06:26:23 +00:00
}) {
2024-12-06 10:31:24 +00:00
const date = new Date();
const reqIp = (() => {
if (!req) return null;
try {
const forwarded = req.headers["x-forwarded-for"];
const realIp = req.headers["x-real-ip"];
const cloudflareIp = req.headers["cf-connecting-ip"];
// Convert forwarded IPs to string and get the first IP if multiple exist
const forwardedIp = Array.isArray(forwarded)
? forwarded[0]
: forwarded?.split(",")[0];
const clientIp =
cloudflareIp ||
forwardedIp ||
realIp ||
req.socket.remoteAddress;
if (!clientIp) return null;
return String(clientIp);
} catch (error) {
return null;
}
})();
try {
let log = `🚀 SERVER ERROR ===========================\nError Message: ${message}\nComponent: ${component}`;
if (user?.id && user?.first_name && user?.last_name && user?.email) {
log += `\nUser Id: ${user?.id}\nUser Name: ${user?.first_name} ${user?.last_name}\nUser Email: ${user?.email}`;
}
2024-11-06 06:26:23 +00:00
2024-12-06 10:31:24 +00:00
if (req?.url) {
log += `\nURL: ${req.url}`;
}
2024-11-06 06:26:23 +00:00
2024-12-06 10:31:24 +00:00
if (req?.body) {
log += `\nRequest Body: ${JSON.stringify(req.body, null, 4)}`;
}
if (reqIp) {
log += `\nIP: ${reqIp}`;
}
log += `\nDate: ${date.toDateString()}`;
log += "\n========================================";
if (!fs.existsSync(`./.tmp/error.log`)) {
fs.writeFileSync(`./.tmp/error.log`, "", "utf-8");
}
const initialText = fs.readFileSync(`./.tmp/error.log`, "utf-8");
fs.writeFileSync(`./.tmp/error.log`, log);
fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
} catch (/** @type {any} */ error) {
console.log("Server Error Reporting Error:", error.message);
}
2024-11-06 06:26:23 +00:00
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////