Introduction
Web development involves creating websites or web applications using programming languages. It is an underrated skill that is critical in various emerging technologies, such as AI and smart contracts and programs like GSCOC. Possessing web development skills can open up job opportunities in almost every business today, as they require an online presence.
Understanding the Jargon
- communication protocols: this is also known as client-server architecture
The communication between systems through a large amount of wiring is known as a network, and this technology was created by ARPANET during the Cold War to enable easier communication between computers
There are two types of layers in the OSI model and the TCP/IP protocol suite:
The Transport Layer: This layer ensures reliable and efficient data transmission between applications or processes running on different hosts connected by a network. The most common transport layer protocols are TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).
TCP: TCP is a reliable transport layer protocol that provides secure transmission between a server and a client. It ensures that data is transmitted without errors and in the correct sequence.
UDP: UDP is an unreliable transport layer protocol that provides faster data transmission but with no error-checking or sequencing guarantees. It is often used for applications such as video streaming, where small delays or lost packets may not be noticeable.
Application layer: The application layer protocols define the format and rules for exchanging data between applications or processes running on different hosts. Examples of common application layer protocols include HTTP (Hypertext Transfer Protocol) for web browsing
HTTP: HTTP uses a client-server architecture, where the client (such as a web browser) sends a request to the server (such as a web server) for a resource (such as a web page), and the server sends back a response containing the requested data.
HTTP also supports various methods for communicating between the client and server, such as GET (retrieve a resource), POST (submit data to be processed), PUT (update an existing resource), and DELETE (remove a resource). The specific method used depends on the type of action being performed and the resource being accessed.
Why should we make our server?
Web browsers display content from servers and files differently. A web server stores and delivers web content to browsers, while files are displayed directly in the browser or appropriate application. Browsers may treat server content differently based on security settings or content types, such as scripts or plug-ins.
so the testing in the server is more secure than the testing files
2. Data Bases
A database is a structured collection of data organized for efficient storage, retrieval, and manipulation using a database management system (DBMS). It consists of tables containing rows and columns of data representing entities and their attributes and is used in a variety of applications for data storage and management.
some famous databases some of which we already know or will know my SQL, Postgres, mango Db, and Firebase we use Postgres for this road map
generally, the picture database looks like this above.
for building small applications we only need a browser, HTTP, and a database which we are building in this blog but for a larger one we discuss in further blogs
Message bus/pub subs
Decoupling: Pub/subsystems allow for the decoupling of components in a distributed system. By publishing events or messages to a message bus, the sender does not need to know who will receive the message or how it will be processed. This allows for more flexible and scalable architectures, where components can be added or removed without affecting the overall system.
Asynchronous communication: Pub/subsystems provide a way for components to communicate asynchronously, which can improve system performance and responsiveness. Instead of waiting for a response from a component before continuing, the sender can publish a message and continue with other tasks.
Scalability: Message brokers can handle large volumes of messages and can distribute them to multiple consumers, allowing for better scalability of the system.
Fault tolerance: Pub/sub systems can provide fault tolerance by ensuring that messages are not lost in the event of a system failure. Messages can be persisted to disk, and consumers can be designed to handle failures gracefully.
Real-time processing: Pub/sub systems can enable real-time processing of events or data streams. By processing messages as they are received, systems can provide up-to-date information to users and respond quickly to changing conditions.
whenever the server is down like the email and what's app then message bus stores the query when the server is back they can their data which is asynchronous architecture
what are we cooking?
The general idea of this roadmap is to build a Leet code website which is a coding platform and a very popular tool to solve Data Structure and Algorithm problems
we see the problem on right and solving area on right and when we click to submit it activates the backend part of our code tested and then shows us if the test is passed or not in this blog we are dealing with the backend part and making
login
signup
create a new problem
submit problem
tech stack using is infamous MERN stack and language using Javascript
Installing Node.js, npm
you just go to chat up and ask how to install Node js in your system in chatgpt
open your terminal and write down
mkdir express-backend-app npm init ( keep entterung then you see file called package .json)
when you click it. it will show like this
you can add start: "node index.js" by pressing cntrl + D exit it
now create a main file by calling "vi main.js"
now open this file in the code editor of your choice
when you open vs code then run a command in the terminal "npm install express" This will add express to your project
creating a local route for LeetCode
in this code, I write down comments to every single comment so that it is easy to understand why every line
const express = require('express')
const app = express()
const port = 3001
// An array of user objects
const USERS = [];
// An array of question objects
const QUESTIONS = [{
title: "Two states",
description: "Given an array , return the maximum of the array?",
testCases: [{
input: "[1,2,3,4,5]",
output: "5"
}]
}];
const SUBMISSION = [
]
// ''' this line request to the user end point. When a Post request is
// made to the endpoint , the callback funtion passed as second argument will be executed'''
app.post('/signup', function(req, res) {
// ths line destructing assignments to extract the 'email' and 'password' from the rew.body
// req.body is object which repersent the data sent in the request body
const {email, password } = req.body;
// check if user with given email already exists and the 'some()'method returns 'true'
// if at least one element satisfies the condition, or false otherwise.
const userExists = USERS.some(user => user.email === email);
if (userExists) {
return res.status(400).json({ error: 'User with email already exists'});
}
// if user doesn't exist,create a new user object with email and password
const newUser = {email, password};
// Add new user object to the USER array
USERS.push(newUser);
// Return a success response with a 200 status code which indicating that user was created successfully
return res.status(200).json({message: 'User created successfully'});
})
// Setup HTTP POST route at the '/login' endpoint with a callback function
// that handles the request and sends a response
app.post('/login', function(req, res) {
// This code uses destructuring assignment to extract the email
// and password properties from the req.body object, which contains the data sent in the request body.
const { email, password } = req.body;
// Find the user with the given email in USERS array by using find() method
const user = USERS.find(user => user.email === email);
// If user is not found, return a 401 status code with an error message
if (!user) {
return res.status(401).json({ error: 'Invalid email or password'});
}
// check if the password matches the user's passwors
if (user.password !== password) {
return res.status(401).json({error: 'Invalid email or password' });
}
// This code generates a random number between 0 and 999999
// and assigns it to the token variable
const token = Math.floor(Math.random()* 1000000);
// This code returns a 200 status code with JSON response containing the 'token'
// variable. the cient can then use the token to authenticate request.
return res.status(200).send('Hello World from route 3!');
})
app.get('/questions', function(req, res) {
// Return all the questions in the QUESTIONS array along with a message
return res.status(200).json({ questions: QUESTIONS, message: "Hello World from route 4!"}) ;
})
app.get("/submissions", function(req, res) {
res.send("Hello World from route 4!")
// 200 status code to indicate that the request was successful
return res.status(200).json({SUBMISSION});
});
app.post("/submissions", function(req, res) {
// Extract the submitted solution from the request body
const { solution } = req.body;
// Randomly accept or reject the solution
const isAccepted = Math.random() < 0.5;
// Create a new submission object with the solution and acceptance status
const newSubmission = { solution, isAccepted };
// Add the submission to the SUBMISSION array
SUBMISSION.push(newSubmission);
res.send("Hello World from route 4!")
// Send a response indicating whether the submission was accepted or rejected
const message = isAccepted ? "Your solution was accepted!" : "Your solution was rejected :(";
});
// create a route thta allowa an admin to add a new problem
// uses 'app.post()' which specify route path
app.post('/problems/new', function(req, res) {
// extract the title, description, and difficulty properties from
// the request body using destructuring assignment.
const { title, description, difficulty } = req.body;
// check if the user making request is an admin if not then it return 401(Unauthorized)
if (req.user.role !== 'admin') {
return res.status(401).json({error: 'Unauthorized' });
}
// it ensure that each prooblem has a unique identifer by creating a object with id property
// that is equal to the length of problem
const newProblem = {id: PROBLEMS.length + 1, title, description, difficulty };
// it pushes the new problem object to the 'PROBLEMS' array
PROBLEMS.push(newProblem);
// t returns a 201(Created)status code with a success message
return res.status(201).json({message: 'Problem added successfully', problem: newProblem });
});
// This sets up the express app to listen for incoming requests on port 3001
app.listen(port, function() {
console.log(`Example app listening on port ${port}`)
})
This code creates a basic Express server that handles HTTP requests for a simple user and problem submission system. The service allows users to sign up and log in, view a list of questions, submit solutions to problems and allows an admin user to add new problems.
The server runs on port 3001 and contains the following routes:
/signup
(POST) - handles user sign-up. It extracts the user's email and password from the request body, checks if the user already exists, create a new user object, and adds it to the USERS array./login
(POST) - handles user login. It extracts the user's email and password from the request body, finds the user with the given email in the USERS array, and returns an authentication token if the email and password match./questions
(GET) - returns a list of all questions in the QUESTIONS array./submissions
(GET, POST) - allows users to submit solutions to problems. The GET method returns a list of all submissions, and the POST method accepts a solution and randomly accepts or rejects it./problems/new
(POST) - allows an admin user to add a new problem. It extracts the problem's title, description, and difficulty properties from the request body, checks if the user making the request is an admin, add a unique identifier to the problem, adds the problem to the PROBLEMS array and returns a success message.
The server also uses various middleware and helper functions from the Express library to handle HTTP requests and responses.
Credits
this video is more than a road please give Ita a try he gonna make 3 videos 2 of which out 2nd on front