-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (65 loc) · 2.09 KB
/
server.js
File metadata and controls
77 lines (65 loc) · 2.09 KB
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
import cookieParser from 'cookie-parser'
import 'dotenv/config'
import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import { Server } from 'socket.io'
import http from 'http'
import path from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url) // get the resolved path to the file
const __dirname = path.dirname(__filename)
// route
import MainRoute from './routes/main.route.js'
import EventRoute from './routes/event.route.js'
import QuestionRoute from './routes/question.route.js'
const app = express()
const server = http.createServer(app)
export const io = new Server(server, {
path: '/api/socket.io',
cors: {
origin: 'http://localhost:5173',
methods: ['GET', 'POST'],
},
})
// Statik fayllar uchun serverni sozlash
app.use('/uploads', express.static(path.join(__dirname, 'uploads')))
export let clientSocketId = {}
io.on('connection', (socket) => {
console.log('Backend: New connection established')
socket.on('userId', (userId) => {
console.log(`Received user ID: ${userId}`)
clientSocketId[userId] = socket.id
console.log(clientSocketId)
})
socket.on('disconnect', () => {
console.log('Backend: Connection closed')
// userId orqali socket id ni o'chirish
for (let userId in clientSocketId) {
if (clientSocketId[userId] === socket.id) {
delete clientSocketId[userId]
break
}
}
})
})
app.use(express.json())
app.use(cookieParser())
app.use(cors({ origin: 'http://localhost:5173', credentials: true }))
app.use('/api', MainRoute)
app.use('/api', EventRoute)
app.use('/api', QuestionRoute)
const PORT = process.env.PORT || 7002
const start = async () => {
try {
await mongoose
.connect(process.env.MONGO_URL)
.then(() => console.log('Database is connected'))
server.listen(PORT, () =>
console.log(`Server running on Port: http://localhost:${PORT}/api`),
)
} catch (error) {
console.log(error)
}
}
await start()