-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
80 lines (71 loc) · 2.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// import dependencies
import { Socket } from "socket.io";
import express from "express";
import morgan from "morgan";
import cors from "cors";
// import dotenv
import { config } from "dotenv";
config();
// database connection
import connnectDatabase from "./src/framework/database/config/dbConfig";
// import the route file
import userRoute from "./src/interface/routes/userRoutes";
import tokenRoute from "./src/interface/routes/tokenRoutes"
import { User } from "./src/domain/models/User";
import { Message } from "./src/domain/models/Message";
import { Chat } from "./src/domain/models/Chat";
// creat express application
const app = express();
// cors setting
const allowedOrigins =
[
"http://localhost:5173","http://localhost:4173",
"http://localhost:3000","http://localhost:4000",
process.env.CLIENT_ORIGIN_URL as string,
process.env.DISTRIBUTED_ORIGIN_URL as string,
];
app.use(
cors({
origin: allowedOrigins,
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
})
);
// middleware for json
app.use(express.json());
// middleware for handle form data
app.use(express.urlencoded({ extended: true }));
// middleware for log
app.use(morgan("dev"));
// user route
app.use('/', userRoute);
app.use('/refresh/token', tokenRoute);
// database connecting & app listen
const port = process.env.PORT || 8000;
connnectDatabase()
.then((res) => {
console.log(res);
const server = app.listen(port, (): void => console.log(`Server running...`));
const io = require("socket.io")(server, {
pingTimeout: 60000,
cors: {
origin: allowedOrigins,
},
});
io.on("connection", (socket: Socket) => {
socket.on("connect-to-online", (roomId: string) => {
socket.join(roomId.toString());
});
socket.on("join-to-chat", (roomId: string) => {
socket.join(roomId.toString());
});
socket.on("new-message", (newMessage: Message) => {
let chat = newMessage?.chat as Chat;
if (!chat?.users) { return; }
chat?.users.forEach((user: User) => {
if (user?.toString() === newMessage?.sender?._id?.toString()) { return };
socket.to(user.toString() as string).emit("message-recieved", newMessage);
});
});
});
})
.catch((error) => console.log(`Failed to connect database`, error));