59 lines
1.8 KiB
JavaScript
59 lines
1.8 KiB
JavaScript
|
const WebSocket = require('ws');
|
||
|
const { sendMessageAsync } = require('./controllers/chatController');
|
||
|
const webSocketClients = require('./utils/webSocketClients');
|
||
|
const jwt = require('jsonwebtoken');
|
||
|
const { User } = require('./models');
|
||
|
|
||
|
// WebSocketサーバーの設定
|
||
|
function setupWebSocketServer(wss) {
|
||
|
wss.on('connection', async (ws, req) => {
|
||
|
try {
|
||
|
const token = req.url.split('?token=')[1]; // トークンをURLから取得
|
||
|
if (!token) {
|
||
|
ws.close(4000, 'Unauthorized');
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// トークンを検証
|
||
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||
|
const user = await User.findByPk(decoded.userId);
|
||
|
|
||
|
if (!user) {
|
||
|
ws.close(4000, 'Unauthorized');
|
||
|
return;
|
||
|
}
|
||
|
|
||
|
// WebSocketにユーザーIDを紐付け
|
||
|
ws.userId = user.id;
|
||
|
webSocketClients.push(ws);
|
||
|
|
||
|
// WebSocketが閉じられたときの処理
|
||
|
ws.on('close', () => {
|
||
|
console.log('WebSocket connection closed');
|
||
|
const index = webSocketClients.indexOf(ws);
|
||
|
if (index !== -1) {
|
||
|
webSocketClients.splice(index, 1);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
// WebSocket経由でメッセージを受信したときの処理
|
||
|
ws.on('message', async (messageData) => {
|
||
|
try {
|
||
|
// Bufferから文字列に変換してJSONパース
|
||
|
const { userMessage, isotopeId } = JSON.parse(messageData.toString('utf8'));
|
||
|
|
||
|
// メッセージ送信処理を呼び出す
|
||
|
await sendMessageAsync(ws, userMessage, isotopeId);
|
||
|
} catch (error) {
|
||
|
console.error('Error processing message:', error);
|
||
|
}
|
||
|
});
|
||
|
} catch (error) {
|
||
|
console.error('WebSocket connection error:', error);
|
||
|
ws.close(4000, 'Unauthorized');
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
module.exports = setupWebSocketServer;
|