generated from lucien/api-template
fix: improved websocket usage
This commit is contained in:
parent
fbf7821320
commit
132b1f3c06
7 changed files with 135 additions and 79 deletions
|
@ -11,16 +11,6 @@ router.get('/', async (req, res) => {
|
||||||
res.send(channels);
|
res.send(channels);
|
||||||
});
|
});
|
||||||
|
|
||||||
const sockets = new Set();
|
|
||||||
|
|
||||||
router.ws('/', function(ws, req) {
|
|
||||||
sockets.add(ws);
|
|
||||||
|
|
||||||
ws.on('close', () => {
|
|
||||||
sockets.delete(ws);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/:name', async (req, res) => {
|
router.get('/:name', async (req, res) => {
|
||||||
const name = req.params.name;
|
const name = req.params.name;
|
||||||
const connection = await getConnection();
|
const connection = await getConnection();
|
||||||
|
@ -33,22 +23,6 @@ router.get('/:name', async (req, res) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const channelSockets = new Map();
|
|
||||||
|
|
||||||
router.ws('/:name', function(ws, req) {
|
|
||||||
const name = req.params.name;
|
|
||||||
|
|
||||||
if (!channelSockets.has(name)) {
|
|
||||||
channelSockets.set(name, new Set());
|
|
||||||
}
|
|
||||||
|
|
||||||
channelSockets.get(name).add(ws);
|
|
||||||
|
|
||||||
ws.on('close', () => {
|
|
||||||
channelSockets.get(name).delete(ws);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
router.get('/:name/messages', async (req, res) => {
|
router.get('/:name/messages', async (req, res) => {
|
||||||
const name = req.params.name;
|
const name = req.params.name;
|
||||||
const connection = await getConnection();
|
const connection = await getConnection();
|
||||||
|
@ -105,21 +79,11 @@ router.post('/:name/messages/send', async (req, res) => {
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
||||||
if (sockets.size > 0) {
|
req.sockets.emit({
|
||||||
for (const client of sockets) {
|
type: 'new_message',
|
||||||
if (client.readyState === 1) {
|
channel_id: channel[0].id,
|
||||||
client.send('new_message');
|
user_id: user.id,
|
||||||
}
|
});
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (channelSockets.has(name)) {
|
|
||||||
for (const client of channelSockets.get(name)) {
|
|
||||||
if (client.readyState === 1) {
|
|
||||||
client.send('new_message');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res.send({ message: 'Message sent' });
|
res.send({ message: 'Message sent' });
|
||||||
});
|
});
|
||||||
|
@ -157,21 +121,11 @@ router.post('/:name/messages/delete', async (req, res) => {
|
||||||
await deleMentions(connection, message_id);
|
await deleMentions(connection, message_id);
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
||||||
if (sockets.size > 0) {
|
req.sockets.emit({
|
||||||
for (const client of sockets) {
|
type: 'delete_message',
|
||||||
if (client.readyState === 1) {
|
channel_id: channel[0].id,
|
||||||
client.send('delete_message');
|
user_id: user.id,
|
||||||
}
|
});
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (channelSockets.has(name)) {
|
|
||||||
for (const client of channelSockets.get(name)) {
|
|
||||||
if (client.readyState === 1) {
|
|
||||||
client.send('delete_message');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res.send({ message: 'Message deleted' });
|
res.send({ message: 'Message deleted' });
|
||||||
});
|
});
|
||||||
|
@ -201,13 +155,9 @@ router.post('/add', async (req, res) => {
|
||||||
await addChannel(connection, name, description, user.id);
|
await addChannel(connection, name, description, user.id);
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
||||||
if (sockets.size > 0) {
|
req.sockets.emit({
|
||||||
for (const client of sockets) {
|
type: 'new_channel'
|
||||||
if (client.readyState === 1) {
|
});
|
||||||
client.send('new_channel');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res.send({ message: 'Channel added' });
|
res.send({ message: 'Channel added' });
|
||||||
});
|
});
|
||||||
|
|
|
@ -14,6 +14,10 @@ app.use(express.json());
|
||||||
app.use(cookieParser());
|
app.use(cookieParser());
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
|
|
||||||
|
const { router, socketsMiddleware } = require("./libs/middlewares");
|
||||||
|
app.use("/api/ws", router);
|
||||||
|
app.use(socketsMiddleware);
|
||||||
|
|
||||||
function loadRoutes(folderName) {
|
function loadRoutes(folderName) {
|
||||||
const routesPath = path.join(__dirname, folderName);
|
const routesPath = path.join(__dirname, folderName);
|
||||||
const files = fs.readdirSync(routesPath);
|
const files = fs.readdirSync(routesPath);
|
||||||
|
|
|
@ -1,5 +1,6 @@
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { getConnection, getUser } = require('./mysql');
|
const { getConnection, getUser } = require('./mysql');
|
||||||
|
const express = require('express');
|
||||||
|
|
||||||
async function checkAuth(req, res, next) {
|
async function checkAuth(req, res, next) {
|
||||||
const { token } = req.body;
|
const { token } = req.body;
|
||||||
|
@ -23,6 +24,30 @@ async function checkAuth(req, res, next) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
const sockets = new Set();
|
||||||
|
|
||||||
|
router.ws('/', function(ws, req) {
|
||||||
|
sockets.add(ws);
|
||||||
|
|
||||||
|
ws.on('close', () => {
|
||||||
|
sockets.delete(ws);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function socketsMiddleware(req, res, next) {
|
||||||
|
req.sockets = {
|
||||||
|
emit: function(data) {
|
||||||
|
for (const socket of sockets) {
|
||||||
|
socket.send(JSON.stringify(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
next();
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
checkAuth,
|
checkAuth,
|
||||||
|
router,
|
||||||
|
socketsMiddleware,
|
||||||
};
|
};
|
|
@ -71,17 +71,28 @@ export default function ChannelPage() {
|
||||||
}, [name]);
|
}, [name]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const socket = new WebSocket(`/api/channels/${name}`);
|
const socket = new WebSocket(`/api/ws`);
|
||||||
|
|
||||||
|
const id = setInterval(() => {
|
||||||
|
socket.send(JSON.stringify("ping"));
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
socket.addEventListener('message', function (event) {
|
socket.addEventListener('message', function (event) {
|
||||||
if (event.data === "new_message" || event.data === "delete_message") {
|
const data = JSON.parse(event.data);
|
||||||
|
console.log(data);
|
||||||
|
if ((data.type === "new_message" || data.type === "delete_message") && data.channel_id === channel?.id) {
|
||||||
axios
|
axios
|
||||||
.get(`/api/channels/${name}/messages`).then((res) => {
|
.get(`/api/channels/${name}/messages`).then((res) => {
|
||||||
setMessages(res.data)
|
setMessages(res.data)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}, [name])
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(id);
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
}, [channel])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const words = message.toString().split(" ");
|
const words = message.toString().split(" ");
|
||||||
|
|
|
@ -34,10 +34,15 @@ export default function ChannelsPage() {
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const socket = new WebSocket("/api/channels");
|
const socket = new WebSocket("/api/ws");
|
||||||
|
|
||||||
|
const id = setInterval(() => {
|
||||||
|
socket.send(JSON.stringify("ping"));
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
socket.addEventListener('message', function (event) {
|
socket.addEventListener('message', function (event) {
|
||||||
if (event.data === "new_channel") {
|
const data = JSON.parse(event.data);
|
||||||
|
if (data.type === "new_channel") {
|
||||||
axios
|
axios
|
||||||
.get("/api/channels")
|
.get("/api/channels")
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
|
@ -48,6 +53,11 @@ export default function ChannelsPage() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(id);
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
if (!channels) {
|
if (!channels) {
|
||||||
|
|
|
@ -59,10 +59,16 @@ export default function Home() {
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const socket = new WebSocket("/api/channels");
|
const socket = new WebSocket("/api/ws");
|
||||||
|
|
||||||
socket.addEventListener('message', function (event) {
|
const id = setInterval(() => {
|
||||||
if (event.data === "new_message" || event.data === "delete_message") {
|
socket.send(JSON.stringify("ping"));
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
|
socket.addEventListener('message', function (event)
|
||||||
|
{
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
if (data.type === "new_message" || data.type === "delete_message") {
|
||||||
axios
|
axios
|
||||||
.get("/api/lastmessages")
|
.get("/api/lastmessages")
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
|
@ -80,7 +86,7 @@ export default function Home() {
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
console.error(err.response)
|
console.error(err.response)
|
||||||
})
|
})
|
||||||
} else if (event.data === "new_channel") {
|
} else if (data.type === "new_channel") {
|
||||||
axios
|
axios
|
||||||
.get("/api/activechannels")
|
.get("/api/activechannels")
|
||||||
.then((res) => {
|
.then((res) => {
|
||||||
|
@ -100,6 +106,11 @@ export default function Home() {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(id);
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
|
@ -25,17 +25,62 @@ export default function UserPage() {
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
axios.get(`/api/users/${username}`).then((res) => {
|
axios
|
||||||
setPageUser(res.data);
|
.get(`/api/users/${username}`)
|
||||||
});
|
.then((res) => {
|
||||||
|
setPageUser(res.data);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err.response);
|
||||||
|
});
|
||||||
|
|
||||||
axios.get(`/api/users/${username}/lastmessages`).then((res) => {
|
axios
|
||||||
setMessages(res.data);
|
.get(`/api/users/${username}/lastmessages`)
|
||||||
});
|
.then((res) => {
|
||||||
|
setMessages(res.data);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err.response);
|
||||||
|
});
|
||||||
}, [username]);
|
}, [username]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const socket = new WebSocket("/api/ws");
|
||||||
|
|
||||||
|
const id = setInterval(() => {
|
||||||
|
socket.send(JSON.stringify("ping"));
|
||||||
|
}, 10000);
|
||||||
|
|
||||||
|
socket.addEventListener('message', function (event) {
|
||||||
|
const data = JSON.parse(event.data);
|
||||||
|
if ((data.type === "new_message" || data.type === "delete_message") && data.user_id === pageUser?.id) {
|
||||||
|
console.log("new message");
|
||||||
|
axios
|
||||||
|
.get(`/api/users/${username}/lastmessages`)
|
||||||
|
.then((res) => {
|
||||||
|
setMessages(res.data);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error(err.response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
clearInterval(id);
|
||||||
|
socket.close();
|
||||||
|
};
|
||||||
|
}, [pageUser]);
|
||||||
|
|
||||||
if (!pageUser) {
|
if (!pageUser) {
|
||||||
return <div>Loading...</div>;
|
return (
|
||||||
|
<div className="user-page">
|
||||||
|
<TopBar user={user} />
|
||||||
|
<div className="user">
|
||||||
|
<h2>Loading...</h2>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue