-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
91 lines (79 loc) · 2.54 KB
/
socket.js
File metadata and controls
91 lines (79 loc) · 2.54 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import { Server } from 'socket.io'
import {
sendMessage,
markMessagesAsRead,
getHistoryMessages,
} from './src/controller/chat.js'
import middlewareSession from './src/config/session.js'
import passport from 'passport'
import Chat from './src/model/chat.js'
const startSocketIo = server => {
const io = new Server(server, {
connectionStateRecovery: {},
cors: {
origin: 'http://localhost:5173',
methods: ['GET', 'POST'],
credentials: true,
},
cookie: true,
})
function onlyForHandshake(middleware) {
return (req, res, next) => {
const isHandshake = req._query.sid === undefined
if (isHandshake) {
middleware(req, res, next)
} else {
next()
}
}
}
io.engine.use(onlyForHandshake(middlewareSession))
io.engine.use(onlyForHandshake(passport.session()))
io.engine.use(
onlyForHandshake((req, res, next) => {
if (req.user) {
next()
} else {
res.writeHead(401)
res.end()
}
})
)
const handleNewMessage = (chatId, message) => {
io.emit('newMessage', { chatId, message })
}
Chat.subscribe(handleNewMessage)
io.on('connection', async socket => {
const currentUserId = socket.request.session.passport.user
socket.on('getHistory', async msg => {
const users = {
senderId: currentUserId,
receiverId: msg.receiver,
}
const history = await getHistoryMessages(users)
if (history) {
socket.emit('chatHistory', history)
} else {
socket.emit('chatHistory', [])
}
})
socket.on('sendMessage', async msg => {
const message = {
senderId: currentUserId,
text: msg.text,
receiverId: msg.receiver,
}
const newMessage = await sendMessage(message)
})
socket.on('markAsRead', async msg => {
const { messageIds } = msg
const updatedMessages = await markMessagesAsRead(messageIds)
console.log('Сообщения отмечены как прочитанные:', updatedMessages)
socket.emit('messagesMarkedAsRead', updatedMessages)
})
socket.on('disconnect', () => {
console.log('user disconnected')
})
})
}
export default startSocketIo