From 537a388bcb58e91141ecbe9fa1972de5fca103a2 Mon Sep 17 00:00:00 2001 From: "DESKTOP-2S5P7D1\\Windows 10" Date: Wed, 18 Dec 2024 18:59:51 +0700 Subject: [PATCH] =?UTF-8?q?=E0=B9=81=E0=B8=81=E0=B9=89=20=20throw=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/interfaces/permission.ts | 18 +++++----- src/middlewares/logs.ts | 69 ++++++++++++++++++++---------------- 2 files changed, 47 insertions(+), 40 deletions(-) diff --git a/src/interfaces/permission.ts b/src/interfaces/permission.ts index b350083..b100be3 100644 --- a/src/interfaces/permission.ts +++ b/src/interfaces/permission.ts @@ -164,12 +164,12 @@ class CheckAuth { port: process.env.REDIS_PORT, }) const getAsync = promisify(redisClient.get).bind(redisClient) - let reply = await getAsync("org_" + keycloakId) - if (reply != null) { - reply = JSON.parse(reply) - } else { - try { - if (!keycloakId) throw "Error calling API No KeycloakId" + try { + let reply = await getAsync("org_" + keycloakId) + if (reply != null) { + reply = JSON.parse(reply) + } else { + if (!keycloakId) throw new Error("No KeycloakId provided") const x = await new CallAPI().GetData( { headers: { authorization: token }, @@ -187,10 +187,10 @@ class CheckAuth { } return data - } catch (error) { - console.error("Error calling API:", error) - throw error } + } catch (error) { + console.error("Error calling API:", error) + throw error } } public async PermissionCreate(req: RequestWithUser, system: string) { diff --git a/src/middlewares/logs.ts b/src/middlewares/logs.ts index 44245fc..739d707 100644 --- a/src/middlewares/logs.ts +++ b/src/middlewares/logs.ts @@ -19,12 +19,10 @@ const LOG_LEVEL_MAP: Record = { const elasticsearch = new Client({ node: `${process.env.ELASTICSEARCH_PROTOCOL}://${process.env.ELASTICSEARCH_HOST}:${process.env.ELASTICSEARCH_PORT}`, }) - async function logMiddleware(req: Request, res: Response, next: NextFunction) { if (!req.url.startsWith("/api/")) return next() let data: any - const originalJson = res.json res.json = function (v: any) { @@ -38,41 +36,50 @@ async function logMiddleware(req: Request, res: Response, next: NextFunction) { req.app.locals.logData = {} res.on("finish", async () => { - if (!req.url.startsWith("/api/")) return + try { + if (!req.url.startsWith("/api/")) return - const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4 + const level = LOG_LEVEL_MAP[process.env.LOG_LEVEL ?? "debug"] || 4 - if (level === 1 && res.statusCode < 500) return - if (level === 2 && res.statusCode < 400) return - if (level === 3 && res.statusCode < 200) return + if (level === 1 && res.statusCode < 500) return + if (level === 2 && res.statusCode < 400) return + if (level === 3 && res.statusCode < 200) return - let token: any - token = req.headers["authorization"] + const token = req.headers["authorization"] + let rootId = null - const rootId = await new permission().checkOrg(token, req.app.locals.logData.userId) + try { + rootId = token ? await new permission().checkOrg(token, req.app.locals.logData.userId) : null + } catch (err) { + console.warn("Error fetching rootId:", err) + } - const obj = { - logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info", - ip: req.ip, - rootId: rootId ? rootId.orgRootId : null, - systemName: "probation", - startTimeStamp: timestamp, - endTimeStamp: new Date().toISOString(), - processTime: performance.now() - start, - host: req.hostname, - method: req.method, - endpoint: req.url, - responseCode: String(res.statusCode === 304 ? 200 : res.statusCode), - responseDescription: data?.message, - input: (level === 4 && JSON.stringify(req.body, null, 2)) || undefined, - output: (level === 4 && JSON.stringify(data, null, 2)) || undefined, - ...req.app.locals.logData, + const obj = { + logType: res.statusCode >= 500 ? "error" : res.statusCode >= 400 ? "warning" : "info", + ip: req.ip, + rootId: rootId?.orgRootId ?? null, + systemName: "evaluation", + startTimeStamp: timestamp, + endTimeStamp: new Date().toISOString(), + processTime: performance.now() - start, + host: req.hostname, + method: req.method, + endpoint: req.url, + responseCode: String(res.statusCode === 304 ? 200 : res.statusCode), + responseDescription: data?.message, + input: level === 4 ? JSON.stringify(req.body, null, 2) : undefined, + output: level === 4 ? JSON.stringify(data, null, 2) : undefined, + ...req.app.locals.logData, + } + + // Send log to Elasticsearch + await elasticsearch.index({ + index: ELASTICSEARCH_INDEX, + document: obj, + }) + } catch (err) { + console.error("Error in logMiddleware:", err) } - - elasticsearch.index({ - index: ELASTICSEARCH_INDEX, - document: obj, - }) }) return next()