basic 2-way communication
This commit is contained in:
		@@ -27,9 +27,14 @@ const startChat = async () => {
 | 
			
		||||
 | 
			
		||||
    await consumer.run({
 | 
			
		||||
        eachMessage: async ({topic, partition, message}) => {
 | 
			
		||||
            const jsonMessage = JSON.parse(message.value.toString())
 | 
			
		||||
            let jsonMessage
 | 
			
		||||
            try {
 | 
			
		||||
                jsonMessage = JSON.parse(message.value.toString())
 | 
			
		||||
            } catch (e) {
 | 
			
		||||
                console.log(e)
 | 
			
		||||
                return
 | 
			
		||||
            }
 | 
			
		||||
            if (jsonMessage.origin == "website") return;
 | 
			
		||||
            console.log(wsClients.length)
 | 
			
		||||
            wsClients.forEach(client => {
 | 
			
		||||
                console.log("sending message to a client")
 | 
			
		||||
                client.send(JSON.stringify({
 | 
			
		||||
@@ -38,14 +43,21 @@ const startChat = async () => {
 | 
			
		||||
                    timestamp: jsonMessage.timestamp 
 | 
			
		||||
                }));
 | 
			
		||||
            });
 | 
			
		||||
            console.log(message.value.toString());
 | 
			
		||||
 | 
			
		||||
            const datetime = Math.round(Date.now() / 1000);
 | 
			
		||||
 | 
			
		||||
            await db.query(
 | 
			
		||||
                "INSERT INTO chat_messages(author, datetime, content) VALUES ($1, to_timestamp($2)::timestamp, $3)",
 | 
			
		||||
                [jsonMessage.author, datetime, jsonMessage.content])
 | 
			
		||||
            .catch(e => {
 | 
			
		||||
                console.log("Error on inserting data into the DB: ", e);
 | 
			
		||||
            });
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
    });
 | 
			
		||||
 | 
			
		||||
    const wsServer = new WebSocketServer({ noServer: true });
 | 
			
		||||
    wsServer.on('connection', socket => {
 | 
			
		||||
        console.log("Hooray! New socket connection")
 | 
			
		||||
        wsClients.push(socket);
 | 
			
		||||
        socket.on('message', async (message) => {
 | 
			
		||||
            message = JSON.parse(message.toString());
 | 
			
		||||
@@ -53,7 +65,6 @@ const startChat = async () => {
 | 
			
		||||
                socket.send("Malformed package.");
 | 
			
		||||
                return;
 | 
			
		||||
            }
 | 
			
		||||
            console.log(message);
 | 
			
		||||
            const token = message.jwt;
 | 
			
		||||
            if (!jwt.verify(token, process.env.SECRET)) {
 | 
			
		||||
                socket.send("JWT is not valid.");
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user