Meet my latest project - Realtime code collaboration tool

Meet my latest project - Realtime code collaboration tool

Β·

10 min read

Introduction 🎀

Collab is a Realtime code sync tool where one user can collaborate with any other user to write code at the same time. Beside this, users can save written code snippets to the website by creating a profile in the website. Why don't you try it yourself πŸ‘‰ ? open website

In this article I'm not walking through all the code I wrote during the development time, but I will be explaining, How I developed the project, what I learned and also share some starter code (redis connection, socket connection ) also some query
to communicate with the redis databse.


Let's start with a simple question !

What is the need of the project ?

  • problem

I don't know if it's a problem or not but, I have seen a lot of people writing code in google docs while appearing for the interview (specially while performing coding round). So, I was thinking of building a project to address this problem. At the same time my college was off due to some reason & I thought this would be the right time to build the project which ultimately gave birth to collab.

  • Fun fact :

It's same thing writing code in paper or in a google docs. πŸ˜‚

Image inside Blog.png


What I used to build it ? πŸ‘©β€πŸ’»

There is not any drought, to say I used javaScript (React, Node - Express) to build the project but this time JavaScript is not only in the picture. Alternatively, I used Redis as a database. Ultimately, my tech stack for the project is RERN (Redis, Express, React, Node).

As the application is all about broadcasting the code to all the clients at the same time, syncing all clients so I used socket.io for the real time communication between the browsers. React, Node & express are the usual things for me, I have pretty much worked on it multiple times, but socket.io and redis were totally new to me for this project. So, I will be talking more about redis and socket.io in this blog.

Image inside Blog (1).png


Why did I choose the RERN stack ?

As redis is the one of the fastest database databases and It would be the perfect choice for the real time application where users want to save and retrieve the code within a second. Also, redis allows us to cache the api response so, maybe in future I'll be implementing the redis cache .


Learnings πŸ“°

As I already mentioned, redis and socket io were completely new for me, so It was very fun exploring them. The one word answer for the question is redis and web-socket - Oh ! those two words .. BTW, in this section I'm not just limiting myself to only those two words. I'll be throwing more than 2 big paragraphs .

  • 🌐 web sockets

Web Socket is bidirectional, a full-duplex protocol that is used in the scenario of client-server communication, unlike HTTP it starts from ws:// or wss://. It is a stateful protocol, which means the connection between client and server will keep alive until it is terminated by either party (client or server). After closing the connection by either of the client and server, the connection is terminated from both ends.

Image inside Blog (2).png

You can refer this to study in detail

The main thing is in the web socket (socket) is emitting the event or action from the client. listening to the event in the backend (server) and performing the query logic based on that and more importantly, these all things happen in a real-time.

  • 1. Initialize the socket

socket.js

// first point out the backend server
export const initSocketClient = async () => {
  let url = "http://localhost:5000";
  const options = {
    "force new connection": true,
    reconnectionAttempt: "Infinity",
    timeout: 10000,
    transports: ["websocket"],
  };
  return io(url, options);
};
  • 2. Emit data to server

sendData.js

// emit the data from here, using the socket instance created above

import {initSocketClient } from "./socket.js" ;
import React,{useRef} from "react" ;
const  socketRef = useRef();
// now using this you can emit 
const   socketRef.current = initSocketClient (); 
// emit data
  socketRef.current.emit("join", { // join is the custom event
    room_id : 458582584842,
    username : "Rajesh Khadka",
  });
  • 3. Listen to event

server.js

 import http from "http";
import { Server } from "socket.io";
const server = http.createServer(app);
const io = new Server(server);

io.on("connection",(socket)=>{
    socket.on("join", ({ username, room_id }) => {
    console.log({username, room_id})
}
})

  • πŸ›’οΈ Redis

Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. This definition is according to the official website itself.

I haven't used all of their services but if I have to answer this question from my own experience then I will probably say Redis is a database that facilitates us to store the data in memory in JSON format and also enables us to intelligently search for the data stored inside of the database. I mean their search feature is so cool that it even returns us the result that matches the synonyms of our query, of course only if we ask for it.


How does the application worksβš™

Firstly the user joins the new room by entering room ID and username. Then it gets sent to the backend which checks if the room is currently present or not with the same roomID, if yes it pushes the user to the existing room with the same roomID if not then it creates the new room with the same roomID and then pushes the user to the newly created one . Also I have already discussed the working model of the application at this part of the video.

yj586hrq0u0o1xkzreee.png


Additional Information β„Ή

  • 1. Let's connect to Redis Databse
import { Client } from "redis-om"; 
// You need to install   `redis-om` npm package to get started.

const url = process.env.REDIS_HOST;
const client = new Client();
try {
  const res = await client.open(url);
  console.log("Connected to redis !");
} catch (error) {
  console.log("failed connecting redis", error);
}
export default client;
  • 2. Add stuff to the database
import { codeRepository } from "../schema/code.schema.js";
  // like model in mongoDB you need to create schema in redis

const postCode = async (req, res) => {
  const code = codeRepository.createEntity(req.body);
  const id = await codeRepository.save(code);
  if (!id) {
    return res.status(404).json({
      message: "Something went wrong !",
    });
  }
  res.status(201).json({
    message: "Posted !!",
  });
};
  • 3. Read the data from Database
  import { codeRepository } from "../schema/code.schema.js";
  // like model in mongoDB you need to create schema in redis
  const getMycode = async (req, res) => {
  const myCode = await codeRepository
    .search()
    .return.all();
  res.status(200).json(myCode);
};
  • 4. Delete the data from Database
  import { codeRepository } from "../schema/code.schema.js";
  // like model in mongoDB you need to create schema in redis
  const deleteCode = async (req, res) => {
  try {
    await codeRepository.remove(req.params.code_id);
    res.status(200).send("Deleted");
  } catch (error) {
    res.status(400).send(error);
  }
};

πŸ”— main repository

πŸ”— frontend part of the repository

πŸ”— backend part of the repository


Β