Skip to content

AndrewJBateman/node-websockets-crud

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

⚡ Node Websockets CRUD

  • A Node.js app to Create, Read, Update and Delete (CRUD) todo cards using Websockets
  • Tutorial code from Fazt with changes to code and styling
  • Note: to open web links in a new window use: ctrl+click on link

GitHub repo size GitHub pull requests GitHub Repo stars GitHub last commit

📄 Table of contents

📚 General Info

  • Socket.IO enables realtime, bi-directional communication between the client and server, with a client-side library that runs in the browser, and a server-side library for Node.js.
  • uuid npm module provides each todo with a Universally Unique IDentifier (UUID) RN Namespace (doc. Number RF4122)
  • The 16 octets of a UUID are represented as 32 hexadecimal (base-16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 eg: "ee0a1fb5-fd31-4962-bf48-bdbe5dba1bd2"
  • Bootstrap cards used with simple styling

📷 Screenshots

Example screenshot.

📶 Technologies

💾 Setup

  • npm run dev to start a dev server on localhost:3000
  • npm run build to create a build folder using Babel JS compiler
  • npm start to run production version on http://localhost:3000

💻 Code Examples

  • sockets.js websocket functions to create, read, update & delete todos.
export default (io) => {
	io.on('connection', (socket) => {
    console.log('user connected');

		// Send todos to all connected sockets
		socket.emit('server:loadtodos', todos);

    // add new todo to existing todos array using push operator
		socket.on('client:newtodo', (newTodo) => {
			const todo = { id: uuid(), ...newTodo  };
			todos.unshift(todo);
			io.emit('server:newtodo', todo);
		});

    // filter todos to remove todo with id matching delete command
    // then rerender todos
		socket.on('client:deletetodo', (todoId) => {
			todos = todos.filter((todo) => todo.id !== todoId);
			io.emit('server:loadtodos', todos);
		});

    // fetch todo to be edited using find function where ids match
		socket.on('client:gettodo', (todoId) => {
			const todo = todos.find((todo) => todo.id === todoId);
			socket.emit('server:selectedtodo', todo);
		});

    // update todo using new data for todo where ids match
		socket.on('client:updatetodo', (updatedTodo) => {
			todos = todos.map((todo) => {
				if (todo.id === updatedTodo.id) {
					todo.title = updatedTodo.title;
					todo.description = updatedTodo.description;
				}
				return todo;
			});
			io.emit('server:loadtodos', todos);
		});

		socket.on('disconnect', () => {
			console.log(socket.id, 'disconnected');
		});
	});
};

📋 Status & To-Do List

  • Status: Working
  • To-Do: Nothing

👏 Inspiration

📁 License

  • N/A

✉️ Contact