NodeJS – Express, Socket.io and Mysql – CRUD

Here is an example of a CRUD (create, read, update, delete) application using Node.js, Socket.IO, and MySQL:

const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'database',
});

connection.connect();

io.on('connection', (socket) => {
  socket.on('create', (item) => {
    connection.query('INSERT INTO items SET ?', item, (error) => {
      if (error) throw error;
      socket.broadcast.emit('create', item);
    });
  });

  socket.on('read', () => {
    connection.query('SELECT * FROM items', (error, results) => {
      if (error) throw error;
      socket.emit('read', results);
    });
  });

  socket.on('update', (item) => {
    connection.query('UPDATE items SET ? WHERE id = ?', [item, item.id], (error) => {
      if (error) throw error;
      socket.broadcast.emit('update', item);
    });
  });

  socket.on('delete', (item) => {
    connection.query('DELETE FROM items WHERE id = ?', item.id, (error) => {
      if (error) throw error;
      socket.broadcast.emit('delete', item);
    });
  });
});

server.listen(8080);

This code sets up an Express server and a Socket.IO server on port 8080, and connects to a MySQL database. It also listens for incoming connections and sets up event listeners for create, read, update, and delete events. When an event is received, the server performs the corresponding operation on the MySQL database and broadcasts the event to all connected clients except for the client that sent the event.

To test this server, we can use a client that connects to the server and sends events to perform CRUD operations. Here is an example of a simple Socket.IO client in Node.js that can be used to test the CRUD application:

const io = require('socket.io-client');
const socket = io('http://localhost:8080');

socket.on('connect', () => {
  console.log('connected to server');

  const item = { id: 1, name: 'Item 1' };
  socket.emit('create', item);
  socket.emit('read');
  socket.on('read', (data) => {
    console.log(data);

    item.name = 'Updated Item 1';
    socket.emit('update', item);
    socket.emit('read');
    socket.on('read', (data) => {
      console.log(data);

      socket.emit('delete', item);
      socket.emit('read');
      socket.on('read', (data) => {
        console.log(data);
      });
    });
  });
});

This writing was generated using ChatGPT of openai.com

Leave a Comment

Your email address will not be published.

Free Web Hosting