From e69fd7b33bae4d5705a2c22059a7099b8098c6c5 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Thu, 6 Mar 2025 16:33:47 +0700 Subject: [PATCH 1/4] test --- src/app.ts | 56 ++++++++++++++--------------- src/controllers/ReportController.ts | 18 ++++++++-- 2 files changed, 43 insertions(+), 31 deletions(-) diff --git a/src/app.ts b/src/app.ts index cd0edf5e..80bfa448 100644 --- a/src/app.ts +++ b/src/app.ts @@ -13,18 +13,16 @@ import { OrganizationController } from "./controllers/OrganizationController"; import logMiddleware from "./middlewares/logs"; import { CommandController } from "./controllers/CommandController"; import { ProfileSalaryController } from "./controllers/ProfileSalaryController"; -import { WebSocketServer } from "ws"; + import http from "http"; -export const wss = new WebSocketServer({ noServer: true, - path: "/api/v1/org/socket", - }); +import { WebSocketServer } from "ws"; + +export const wss = new WebSocketServer({ noServer: true, path: "/api/v1/org/socket" }); async function main() { await AppDataSource.initialize(); - + const app = express(); - // สร้างเซิร์ฟเวอร์ HTTP - const server = http.createServer(app); app.use( cors({ @@ -64,7 +62,7 @@ async function main() { console.error("Error executing function from controller:", error); } }); - + const cronTime_Oct = "0 0 1 10 *"; cron.schedule(cronTime_Oct, async () => { try { @@ -74,7 +72,7 @@ async function main() { console.error("Error executing function from controller:", error); } }); - + const cronTime_Tenure = "0 0 * * *"; cron.schedule(cronTime_Tenure, async () => { try { @@ -108,38 +106,38 @@ async function main() { runMessageQueue(); - // การจัดการคำขออัปเกรดจาก HTTP เป็น WebSocket - server.on("upgrade", (request:any, socket:any, head:any) => { - console.log("🔹 Handling upgrade request..."); - wss.handleUpgrade(request, socket, head, (ws:any) => { - console.log("🔹 WebSocket connection established"); - wss.emit("connection", ws, request); - }); - }); + // สร้างเซิร์ฟเวอร์ HTTP + const server = http.createServer(app); - wss.on("connection", (ws:any) => { - console.log("✅ Client connected to WebSocket"); + // ✅ WebSocket Handling + wss.on("connection", (ws) => { + console.log("✅ WebSocket Client Connected"); + // clients.add(ws); // เก็บ client ไว้ + + // ✅ ตั้ง Heartbeat (ping/pong) + + ws.on("message", (message) => { + console.log("📩 Received:", message.toString()); + ws.send("📡 Server Received: " + message.toString()); + }); ws.on("close", () => { - console.log("❌ Client disconnected"); - }); - - ws.on("error", (error:any) => { - console.error("WebSocket error:", error); + console.log("❌ WebSocket Client Disconnected"); }); }); - // ตั้งค่า Express routes - app.get('/', (req, res) => { - res.send('Hello from Express!'); + // ✅ อัปเกรด HTTP เป็น WebSocket + server.on("upgrade", (req, socket, head) => { + wss.handleUpgrade(req, socket, head, (ws) => { + wss.emit("connection", ws, req); + }); }); - + server.listen(APP_PORT, APP_HOST, () => { console.log(`[APP] Application is running on: http://${APP_HOST}:${APP_PORT}`); console.log(`[APP] Swagger on: http://${APP_HOST}:${APP_PORT}/api-docs`); console.log("[APP] HTTP Server is listening on current port"); }); - } main(); diff --git a/src/controllers/ReportController.ts b/src/controllers/ReportController.ts index 59748800..a8adbc38 100644 --- a/src/controllers/ReportController.ts +++ b/src/controllers/ReportController.ts @@ -32,6 +32,9 @@ import { viewRegistryOfficer } from "../entities/view/viewRegistryOfficer"; import { viewRegistryEmployee } from "../entities/view/viewRegistryEmployee"; import { EmployeeTempPosMaster } from "../entities/EmployeeTempPosMaster"; +import { WebSocket } from "ws"; +import { wss } from "../app"; // ✅ Import clients + @Route("api/v1/org/report") @Tags("Report") @Security("bearerAuth") @@ -3537,8 +3540,19 @@ export class ReportController extends Controller { } } } - - return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); + + // ✅ ส่งข้อมูลไปยังทุกไคลเอนต์ที่เชื่อมต่อ WebSocket + wss.clients.forEach((client) => { + if (client.readyState === WebSocket.OPEN) { + if (client.readyState === 1) { + client.send( + JSON.stringify({ template: "report2", reportName: "report2", data: { data } }), + ); + } + } + }); + + // return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); } /** From cfcf63b9aa3e8a9e5473a11d6f4d91c6c1c74b04 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Thu, 6 Mar 2025 16:42:19 +0700 Subject: [PATCH 2/4] fix --- src/app.ts | 33 +---------------------------- src/controllers/ReportController.ts | 18 ++-------------- 2 files changed, 3 insertions(+), 48 deletions(-) diff --git a/src/app.ts b/src/app.ts index 80bfa448..2151acec 100644 --- a/src/app.ts +++ b/src/app.ts @@ -13,12 +13,8 @@ import { OrganizationController } from "./controllers/OrganizationController"; import logMiddleware from "./middlewares/logs"; import { CommandController } from "./controllers/CommandController"; import { ProfileSalaryController } from "./controllers/ProfileSalaryController"; - -import http from "http"; import { WebSocketServer } from "ws"; -export const wss = new WebSocketServer({ noServer: true, path: "/api/v1/org/socket" }); - async function main() { await AppDataSource.initialize(); @@ -106,34 +102,7 @@ async function main() { runMessageQueue(); - // สร้างเซิร์ฟเวอร์ HTTP - const server = http.createServer(app); - - // ✅ WebSocket Handling - wss.on("connection", (ws) => { - console.log("✅ WebSocket Client Connected"); - // clients.add(ws); // เก็บ client ไว้ - - // ✅ ตั้ง Heartbeat (ping/pong) - - ws.on("message", (message) => { - console.log("📩 Received:", message.toString()); - ws.send("📡 Server Received: " + message.toString()); - }); - - ws.on("close", () => { - console.log("❌ WebSocket Client Disconnected"); - }); - }); - - // ✅ อัปเกรด HTTP เป็น WebSocket - server.on("upgrade", (req, socket, head) => { - wss.handleUpgrade(req, socket, head, (ws) => { - wss.emit("connection", ws, req); - }); - }); - - server.listen(APP_PORT, APP_HOST, () => { + app.listen(APP_PORT, APP_HOST, () => { console.log(`[APP] Application is running on: http://${APP_HOST}:${APP_PORT}`); console.log(`[APP] Swagger on: http://${APP_HOST}:${APP_PORT}/api-docs`); console.log("[APP] HTTP Server is listening on current port"); diff --git a/src/controllers/ReportController.ts b/src/controllers/ReportController.ts index a8adbc38..59748800 100644 --- a/src/controllers/ReportController.ts +++ b/src/controllers/ReportController.ts @@ -32,9 +32,6 @@ import { viewRegistryOfficer } from "../entities/view/viewRegistryOfficer"; import { viewRegistryEmployee } from "../entities/view/viewRegistryEmployee"; import { EmployeeTempPosMaster } from "../entities/EmployeeTempPosMaster"; -import { WebSocket } from "ws"; -import { wss } from "../app"; // ✅ Import clients - @Route("api/v1/org/report") @Tags("Report") @Security("bearerAuth") @@ -3540,19 +3537,8 @@ export class ReportController extends Controller { } } } - - // ✅ ส่งข้อมูลไปยังทุกไคลเอนต์ที่เชื่อมต่อ WebSocket - wss.clients.forEach((client) => { - if (client.readyState === WebSocket.OPEN) { - if (client.readyState === 1) { - client.send( - JSON.stringify({ template: "report2", reportName: "report2", data: { data } }), - ); - } - } - }); - - // return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); + + return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); } /** From fa073242b836aa7012e01b23d72e64ae08195290 Mon Sep 17 00:00:00 2001 From: AdisakKanthawilang Date: Thu, 6 Mar 2025 18:25:27 +0700 Subject: [PATCH 3/4] test ws --- src/app.ts | 34 ++++++++++++++++++++++--- src/controllers/PermissionController.ts | 5 +++- src/controllers/ReportController.ts | 6 ++++- src/services/webSocket.ts | 16 ++++++++++++ 4 files changed, 56 insertions(+), 5 deletions(-) create mode 100644 src/services/webSocket.ts diff --git a/src/app.ts b/src/app.ts index 2151acec..8e105830 100644 --- a/src/app.ts +++ b/src/app.ts @@ -13,7 +13,12 @@ import { OrganizationController } from "./controllers/OrganizationController"; import logMiddleware from "./middlewares/logs"; import { CommandController } from "./controllers/CommandController"; import { ProfileSalaryController } from "./controllers/ProfileSalaryController"; + import { WebSocketServer } from "ws"; +import http from "http"; +export const wss = new WebSocketServer({ noServer: true, + path: "/api/vi/org/socket", + }); async function main() { await AppDataSource.initialize(); @@ -102,9 +107,32 @@ async function main() { runMessageQueue(); - app.listen(APP_PORT, APP_HOST, () => { - console.log(`[APP] Application is running on: http://${APP_HOST}:${APP_PORT}`); - console.log(`[APP] Swagger on: http://${APP_HOST}:${APP_PORT}/api-docs`); + const server = http.createServer(app); + + // การจัดการคำขออัปเกรดจาก HTTP เป็น WebSocket + server.on("upgrade", (request:any, socket:any, head:any) => { + console.log("🔹 Handling upgrade request..."); + wss.handleUpgrade(request, socket, head, (ws:any) => { + console.log("🔹 WebSocket connection established"); + wss.emit("connection", ws, request); + }); + }); + + wss.on("connection", (ws:any) => { + console.log("✅ Client connected to WebSocket"); + + ws.on("close", () => { + console.log("❌ Client disconnected"); + }); + + ws.on("error", (error:any) => { + console.error("WebSocket error:", error); + }); + }); + + server.listen(APP_PORT, APP_HOST, () => { + console.log(`[APP] Application is running on: http://localhost:${APP_PORT}`); + console.log(`[APP] Swagger on: http://localhost:${APP_PORT}/api-docs`); console.log("[APP] HTTP Server is listening on current port"); }); } diff --git a/src/controllers/PermissionController.ts b/src/controllers/PermissionController.ts index 77cc61d0..852b3beb 100644 --- a/src/controllers/PermissionController.ts +++ b/src/controllers/PermissionController.ts @@ -55,6 +55,7 @@ export class PermissionController extends Controller { } let reply = await getAsync("role_" + profile.id); + console.log(">>>reply",reply); if (reply != null) { reply = JSON.parse(reply); } else { @@ -84,11 +85,13 @@ export class PermissionController extends Controller { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลสิทธิ์"); } } - + console.log(">>>posMaster",posMaster); const getDetail = await this.authRoleRepo.findOne({ select: ["id", "roleName", "roleDescription"], where: { id: posMaster.authRoleId }, }); + console.log(">>>detail",getDetail); + if (!getDetail) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); } diff --git a/src/controllers/ReportController.ts b/src/controllers/ReportController.ts index 59748800..ea0130cc 100644 --- a/src/controllers/ReportController.ts +++ b/src/controllers/ReportController.ts @@ -31,6 +31,7 @@ import { Profile } from "../entities/Profile"; import { viewRegistryOfficer } from "../entities/view/viewRegistryOfficer"; import { viewRegistryEmployee } from "../entities/view/viewRegistryEmployee"; import { EmployeeTempPosMaster } from "../entities/EmployeeTempPosMaster"; +import { sendWebSocket } from "../services/webSocket"; @Route("api/v1/org/report") @Tags("Report") @@ -1369,6 +1370,7 @@ export class ReportController extends Controller { } } } + return new HttpSuccess({ template: "report1", reportName: "report1", data: { data } }); } @@ -3537,8 +3539,10 @@ export class ReportController extends Controller { } } } + const metaData = { template: "report2", reportName: "report2", data: { data } }; + sendWebSocket(metaData) - return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); + // return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); } /** diff --git a/src/services/webSocket.ts b/src/services/webSocket.ts new file mode 100644 index 00000000..5dd006f0 --- /dev/null +++ b/src/services/webSocket.ts @@ -0,0 +1,16 @@ +import { WebSocket } from "ws"; +import { wss } from "../app"; + +export async function sendWebSocket(data:any){ + wss.clients.forEach((client: any) => { + if (client.readyState === WebSocket.OPEN) { + const message = JSON.stringify(data); + console.log("📤 Sending data to client:", message); + client.send(message, (err:any) => { + if (err) { + console.error("❌ Error sending message:", err); + } + }); + } + }); +} \ No newline at end of file From b24a900198a2e83d621975fe9d657157de8ffccf Mon Sep 17 00:00:00 2001 From: AdisakKanthawilang Date: Thu, 6 Mar 2025 18:39:17 +0700 Subject: [PATCH 4/4] reverse --- src/controllers/PermissionController.ts | 3 --- src/controllers/ReportController.ts | 8 +++---- src/services/webSocket.ts | 30 ++++++++++++------------- 3 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/controllers/PermissionController.ts b/src/controllers/PermissionController.ts index 852b3beb..72b7d671 100644 --- a/src/controllers/PermissionController.ts +++ b/src/controllers/PermissionController.ts @@ -55,7 +55,6 @@ export class PermissionController extends Controller { } let reply = await getAsync("role_" + profile.id); - console.log(">>>reply",reply); if (reply != null) { reply = JSON.parse(reply); } else { @@ -85,12 +84,10 @@ export class PermissionController extends Controller { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูลสิทธิ์"); } } - console.log(">>>posMaster",posMaster); const getDetail = await this.authRoleRepo.findOne({ select: ["id", "roleName", "roleDescription"], where: { id: posMaster.authRoleId }, }); - console.log(">>>detail",getDetail); if (!getDetail) { throw new HttpError(HttpStatus.NOT_FOUND, "ไม่พบข้อมูล"); diff --git a/src/controllers/ReportController.ts b/src/controllers/ReportController.ts index ea0130cc..9fab9ebb 100644 --- a/src/controllers/ReportController.ts +++ b/src/controllers/ReportController.ts @@ -31,7 +31,7 @@ import { Profile } from "../entities/Profile"; import { viewRegistryOfficer } from "../entities/view/viewRegistryOfficer"; import { viewRegistryEmployee } from "../entities/view/viewRegistryEmployee"; import { EmployeeTempPosMaster } from "../entities/EmployeeTempPosMaster"; -import { sendWebSocket } from "../services/webSocket"; +// import { sendWebSocket } from "../services/webSocket"; @Route("api/v1/org/report") @Tags("Report") @@ -3539,10 +3539,10 @@ export class ReportController extends Controller { } } } - const metaData = { template: "report2", reportName: "report2", data: { data } }; - sendWebSocket(metaData) + // const metaData = { template: "report2", reportName: "report2", data: { data } }; + // sendWebSocket(metaData) - // return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); + return new HttpSuccess({ template: "report2", reportName: "report2", data: { data } }); } /** diff --git a/src/services/webSocket.ts b/src/services/webSocket.ts index 5dd006f0..23062aba 100644 --- a/src/services/webSocket.ts +++ b/src/services/webSocket.ts @@ -1,16 +1,16 @@ -import { WebSocket } from "ws"; -import { wss } from "../app"; +// import { WebSocket } from "ws"; +// import { wss } from "../app"; -export async function sendWebSocket(data:any){ - wss.clients.forEach((client: any) => { - if (client.readyState === WebSocket.OPEN) { - const message = JSON.stringify(data); - console.log("📤 Sending data to client:", message); - client.send(message, (err:any) => { - if (err) { - console.error("❌ Error sending message:", err); - } - }); - } - }); -} \ No newline at end of file +// export async function sendWebSocket(data:any){ +// wss.clients.forEach((client: any) => { +// if (client.readyState === WebSocket.OPEN) { +// const message = JSON.stringify(data); +// console.log("📤 Sending data to client:", message); +// client.send(message, (err:any) => { +// if (err) { +// console.error("❌ Error sending message:", err); +// } +// }); +// } +// }); +// } \ No newline at end of file