Skip to content

🌏 NTUOSS Web Backend workshop that deals with REST APIs, Socket-connections and MongoDB

Notifications You must be signed in to change notification settings

naseer2426/NTUOSS-BackendWorkshop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

NTUOSS Web Backend Workshop

by Naseer Ahmed Khan for NTU Open Source Society

This is the second workshop in the NTUOSS Web development workshop series. This workshop will build upon the beautiful front end developed in the first workshop. I highly recommend going through the first workshop here

The slides for this workshop can be found here


Workshop Banner

Artwork by Bryna Goh Jia Rui

Workshop Details

When: Friday, 21 February 2020. 6:30PM - 8:30PM
Where: TCT-LT, Nanyang Technological University
Who: NTU Open Source Society

Questions

Please raise your hand any time during the workshop.

Errors

For errors, typos or suggestions, please do not hesitate to post an issue! Pull requests are very welcome, thank you!


Index


Prerequisites

  • Nodejs
    • Check if you have nodjs installed on your laptop by running the following command on terminal (Mac) or command line (windows)
node --version
  • If you don't have it installed, get it here (for Windows users)
  • Mac users can install brew by running
mkdir homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew
  • Then run
brew install node
  • Postman
    • If you don't have postman installed get it here
  • A text editor
    • Preferable Visual Studio Code because its amazing!
    • Get it here

Getting started

The first thing you need to do is clone this repository by running the following command on your terminal

git clone https://github.com/naseer2426/Backend-Workshop.git

If you don't have git installed you can download the zip of this repository here. Unzip this file and you will get a folder called Backend-Workshop. Open terminal/command-line in this folder.

Next, you need to enter the client folder by running the following command

cd workshop_code/client

Install all the dependencies required for the front end by running

npm install

After the installation is complete, run the following command to check if the front end works perfectly..

npm start

You should see something like this

Front-End-Demo

Server code

Make a new folder called server inside the workshop_code folder. Enter this folder and open terminal here. Initialize node here by running the following command.

npm init -y

Install all the required dependencies by running

npm install --save body-parser cors express mongodb socket.io

Make a file named index.js, this will be your main file that runs your server code. Import all the dependencies into index.js

var express = require("express");
var app = express();
const bodyParser = require("body-parser");
const { MongoClient } = require("mongodb");
const PORT = 8000;
const cors = require("cors")({ origin: true });
var server = require("http").Server(app);
var io = require("socket.io")(server);
app.use(bodyParser.json());
app.use(cors);

Simple Socket connection

A simple socket connection requires socket code on both client and server side.

Server side code to establish a socket connection

io.on("connection", socket => {
    console.log("connected new client");
    console.log(socket.id);
});


server.listen(PORT, () => {
    console.log(`Server listening to port ${PORT}`);
});

Client side code to establish socket connection

  • Importing socket.io

    import io from "socket.io-client";
  • Assinging socket in the contructor

    this.server = "http://localhost:8000";
    this.socket = io(this.server);

Sending messages from client to server

Sending a JSON message to the server is the easiest thing the world.

this.socket.emit("send", newMessage);

Recieving messages from client in the server

socket.on("send", data => {
        console.log(data);
    });

Sending messages from server to client

socket.emit("recieving",data);

Recieving messages from server in client

this.socket.on("recieving", data => {
            console.log(data);
        });

Broadcasting messages to all connected clients

socket.broadcast.emit("recieving", data);

Setting up the group chat

Server side code

io.on("connection", socket => {
    console.log("connected");
    console.log(socket.id);

    socket.on("send", data => {
        socket.broadcast.emit("recieving", data);
    });
});

server.listen(PORT, () => {
    console.log(`Server listening to port ${PORT}`);
});

Client side code

Sending a message to the server

var newMessage = {
            body: this.state.message,
            name: this.state.name
        };
this.setState(prevState => ({messages: [...prevState.messages, newMessage],message: ""}));

this.socket.emit("send", newMessage);

Recieving a broadcast message from the server

this.socket.on("recieving", data => {
            this.setState(prevState => ({
                messages: [...prevState.messages, data]
            }));
        });

You would have noticed that all previous messages vanish when you reload the page. This is because we never save these messages anywhere. We need our own database to store our chats.

Setting up MongoDB

To set up mongoDB, click here and sign in with google. Once you sign in, you need to create a new project

mongo-project

Once the project is created, you'll see something like this.

Mongo-Home

Next you need to create an admin user whose credentials will be used to access the database. Go to database access under security and add user.

admin-user

Next you need to white-list your IP address to access the database. For now we will just allow all IP addresses to access our database

configure-IP

Now you create a cluster for your database.

cluster

Connecting to mongoDB from the server

This is the server side code to connect to your MongoDB database.

const uri = //Enter your URI;
const client = new MongoClient(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

var messages;
client.connect(err => {
    if (err != null) {
        console.log(err);
    }
    messages = client.db("Telegram").collection("Chat");
    console.log("Connected to mongo boi");

});

Getting all the documents in your collection

messages.find().toArray((err, docs) => {
        console.log(docs);
    });

Inserting a document into your collection

var response = await messages.insertOne(req.body);

REST APIs

There are different types of HTTP requests (GET,PUT,UPDATE,DELETE,POST etc.). You can use express to call a function whenever the client sends an HTTP request to the server.

GET Request

app.get("/", async (req, res) => {
    //req has all the data sent by the client
    //res has everything you need to send back a response
});

POST Request

app.post("/send", async (req, res) => {
    //req has all the data sent by the client
    //req.body will give you the json body sent by the client
    //res has everything you need to send back a response
});

Making REST API for MongoDB

First we need an API to get all the messages. We can use a GET request for this. The following code goes in the server

app.get("/", async (req, res) => {
    messages.find().toArray((err, docs) => {
        res.send(docs);
    });
});

We can call this API from the client side using the following code.

fetch(this.server)
            .then(res => res.json())
            .then(
                result => {
                    console.log(result);
                },
                error => {
                    console.log(error);
                }
            );

Next we make an API to add a mesasage to the database. This will be a POST request. The server side code is given below.

app.post("/send", async (req, res) => {
    var response = await messages.insertOne(req.body);
    res.send(response);
});

You can make the post request from the client side using the following code.

fetch(this.server + "/send", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(newMessage)
        })
            .then(res => res.json())
            .then(result => {
                console.log(result);
            });
    };

Deploying your server on Heroku

You can deploy your server online so that anyone in the world can access it. To learn how to deploy a node server onto heroku, you can follow this tutorial.

Deploying your React app on github pages

Since this is a static web page, you can deploy your front end in any server. I chose to do it on github pages. To learn how to do this follow this tutorial.

About

🌏 NTUOSS Web Backend workshop that deals with REST APIs, Socket-connections and MongoDB

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published