This commit is contained in:
Bright 2025-03-31 17:36:21 +07:00
commit 97c1f07a6a
5 changed files with 317 additions and 41 deletions

View file

@ -14,12 +14,12 @@ import logMiddleware from "./middlewares/logs";
import { CommandController } from "./controllers/CommandController";
import { ProfileSalaryController } from "./controllers/ProfileSalaryController";
// import { initWebSocket } from "./services/webSocket";
import { initWebSocket } from "./services/webSocket";
async function main() {
await AppDataSource.initialize();
// initWebSocket();
initWebSocket();
const app = express();

View file

@ -24,6 +24,7 @@ import { Position } from "../entities/Position";
import { In, Not } from "typeorm";
import { PosMasterAct } from "../entities/PosMasterAct";
import { PermissionOrg } from "../entities/PermissionOrg";
import { sendWebSocket } from "./webSocket";
export let sendToQueue: (payload: any) => void;
export let sendToQueueOrg: (payload: any) => void;
@ -122,6 +123,14 @@ async function handler(msg: amqp.ConsumeMessage): Promise<boolean> {
relations: ["commandType", "commandRecives"],
});
if (!command) return true;
sendWebSocket(
"send-command-notification",
{
message: `ระบบทำการออกคำสั่งเลขที่ ${command.commandNo}/${command.commandYear + 543}`,
payload: command,
},
{ userId: user.sub },
).catch(console.error);
const path = commandTypePath(command.commandType.code);
if (path == null) throw new HttpError(HttpStatusCode.NOT_FOUND, "ไม่พบประเภทคำสั่งนี้ในระบบ");
return await new CallAPI()
@ -156,8 +165,17 @@ async function handler(msg: amqp.ConsumeMessage): Promise<boolean> {
console.log("[AMQ] Excecute Command Success");
Object.assign(command, { status, lastUpdateUserId, lastUpdateFullName, lastUpdatedAt });
const result = await repo.save(command).catch((e) => console.log(e));
if (result) return true;
return false;
sendWebSocket(
"send-command-notification",
{
message: `ระบบออกคำสั่งเลขที่ ${command.commandNo}/${command.commandYear + 543} เสร็จสิ้น`,
payload: command,
},
{ userId: user.sub },
).catch(console.error);
return !!result;
})
.catch((e) => {
console.error(e);

View file

@ -1,43 +1,72 @@
// import { WebSocketServer } from "ws";
import { Server } from "socket.io";
// let wss: WebSocketServer;
let io: Server;
// export function initWebSocket() {
// wss = new WebSocketServer({ port: 13002, path: "/api/v1/org-socket" });
export function initWebSocket() {
if (io) return;
// // การจัดการคำขออัปเกรดจาก HTTP เป็น WebSocket
// wss.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);
// });
// });
io = new Server({ cors: { origin: "*" }, path: "/api/v1/org-socket" });
// wss.on("connection", (ws: any) => {
// console.log("✅ Client connected to WebSocket");
io.use(async (socket, next) => {
const token = socket.handshake.auth.token;
// ws.on("close", () => {
// console.log("❌ Client disconnected");
// });
const res = await fetch(`${process.env.AUTH_REALM_URL}/protocol/openid-connect/userinfo`, {
headers: { authorization: `Bearer ${token}` },
}).catch((e) => console.error(e));
// ws.on("error", (error: any) => {
// console.error("WebSocket error:", error);
// });
// });
// }
if (res?.ok) {
socket.data.user = await res.json();
}
// export async function sendWebSocket(data: any) {
// if (!wss) initWebSocket();
// 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);
// }
// });
// }
// });
// }
next();
});
io.on("connection", (ws) => {
console.log("✅ Client connected to WebSocket");
ws.on("close", () => {
console.log("❌ Client disconnected");
});
ws.on("error", (error: any) => {
console.error("WebSocket error:", error);
});
});
io.listen(13002);
}
export async function sendWebSocket(
event: string,
data: any,
opts?: {
roles?: string | string[];
userId?: string | string[];
},
) {
if (!io) initWebSocket();
for (let [id, session] of io.of("/").sockets) {
const user: {
sub: string;
name: string;
given_name: string;
family_name: string;
preferred_username: string;
email: string;
role: string[];
} = session.data.user;
if (!user) continue;
if (typeof opts?.roles === "string") opts.roles = [opts.roles];
if (typeof opts?.userId === "string") opts.userId = [opts.userId];
if (
user.role?.some((v) => opts?.roles?.includes(v)) ||
opts?.userId?.some((v) => user.sub === v)
) {
io.to(id).emit(event, JSON.stringify(data));
}
}
}