This commit is contained in:
DESKTOP-1R2VSQH\Lenovo ThinkPad E490 2025-03-06 16:57:43 +07:00
parent a95439f055
commit c1b7c65c9c
2 changed files with 3 additions and 50 deletions

View file

@ -10,15 +10,6 @@ import { RegisterRoutes } from "./routes";
import logMiddleware from "./middlewares/logs";
import axios from "axios";
import http from "http";
import { WebSocket, WebSocketServer } from "ws"; // ✅ Import WebSocket
// ✅ สร้าง WebSocket Server โดยใช้ HTTP Server เดียวกัน
export const wss = new WebSocketServer({
noServer: true,
path: "/api/v1/probation/ws",
});
async function main() {
await AppDataSource.initialize();
@ -84,38 +75,10 @@ async function main() {
RegisterRoutes(app);
app.use(error);
// app.use(cors());
const APP_HOST = process.env.APP_HOST || "0.0.0.0";
const APP_PORT = +(process.env.APP_PORT || 3000);
// ✅ สร้าง HTTP Server และเชื่อม Express
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.listen(
APP_PORT,
APP_HOST,
() => (

View file

@ -32,8 +32,7 @@ import Extension from "../interfaces/extension";
import { Appoint } from "../entities/Appoint";
import { AppointDirector } from "../entities/AppointDirector";
import { AssignOutput } from "../entities/AssignOutput";
import { WebSocket } from "ws";
import { wss } from "../app"; // ✅ Import clients
@Route("api/v1/probation/report")
@Tags("Report")
@Security("bearerAuth")
@ -210,16 +209,7 @@ export class ReportController extends Controller {
where: { probation_status: 7 },
});
// ✅ ส่งข้อมูลไปยังทุกไคลเอนต์ที่เชื่อมต่อ WebSocket
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
if (client.readyState === 1) {
client.send(JSON.stringify({ name: "test" }));
}
}
});
// return new HttpSuccess(data);
return new HttpSuccess(data);
}
/**