Skip to main content

URL Shortener with GitHub-Actions and Azure (NodeJS) part-1


Creating a URL Shortener using NodeJS

Prerequisite

Abstract

Getting to know about how to deal with a NoSQL Database (here in this repo, we'll use MongoDB). Deploying the webapp to Azure via GitHub Actions.

Table of Content

Resource Links
Demos - 1-Setting-Backend
- Setting-up-Directory-structure
- Building-a-basic-Front-End
- Connecting-to-our-Database
- Setting-up-the-Routes-for-the-app
- Pushing-Project-to-GitHub-and-Azure

Demos

We'll cover the making of this whole repository in small demos If you didn't covered the basic EJS project repo, then visit this link

1-Setting-up-the-Backend

On the Command line navigate to the directory where you want to save the project on your system, then type in the following commands
  • mkdir URLShortener
  • cd URLShortener
  • npm init -y
    • What this will do is that it will keep init output as per the default template.
    • alt text
  • Explore what package.json is. Mainly mention the entrypoint which is main: index.js
  • How to open the terminal in VSCode (View > Terminal)
  • Let's install other libraries as well at once, so type in the below command:
    • npm install express ejs config mongoose shortid valid-url --save
    • alt text
    • What the above step will do is it will record the names of the dependencies which are required to run the package.
    • alt text
  • Create the file index.js
  • Type in/snippet/copy/paste the following content.
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
// ..
app.get('/', (req, res) => res.send('Hello world'));
app.listen(port, () => console.log('Application started at => http://localhost:'+port));
 
  • Run the code by this command: node index.js and go to localhost:3000. To see the Home Page.
    • alt text
  • Next let's just get rid of this continuously pressing F5 or typing in node index.js again and again.
  • So to automate this process we've a papckage called "nodemon". So lets install it: npm i nodemon --save-dev
    • alt text
  • Now lets see the package.json file, and add some script to it, so that it can trigger nodemon whenever we run that dev script.
  • Replace the below snippet with the later one:
    • To be replaced
      • "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1"
        }
         
    • To be replaced by
      • "scripts": {
         "start": "node index",
         "dev": "nodemon index"
        }
         
    • alt text
  • Use the below code snippet in the index.js file (remove all the previous code):
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json({
 extended: false
}));
app.use(express.urlencoded({
 extended: false
}));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
 res.render('home');
});
app.listen(port, () => console.log('Application started at => http://localhost:' + port));
 
  • Here the statement app.use(express.json(-------)); is a Middleware which will allow us to accept JSON data into our API.

Setting-up-Directory-structure

  • Create folders & files inside the project directory as per thie below given List:
    • config (Folder)
      • db.js
      • default.json
    • models (Folder)
      • Url.js
    • routes (Folder)
      • urlRedirect.js
      • url.js
    • views (Folder)
      • home.ejs

Building-a-basic-Front-End

  • Now use the below snippet for the home.ejs file:
<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <title>UNITE- URL Shortner 😍
    </title> 
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> 
  </head> 
  <body> 
    <div class="container-fluid"> 
      <div class="jumbotron" style="text-align: center;"> 
        <h1 class="display-4">Welcome to the URL Shortner
        </h1> 
      </div> 
      <!-- FORM --> 
      <!-- URLs Table --> 
      <footer class="footer container-fluid my-4"> 
        <hr> 
        <span class="row justify-content-center text-muted"> Copyright 
          <% const date = new Date(); %> 
            <%= date.getFullYear() %> 
              </span> 
            </footer> 
          </div> 
        </body> 
      </html>
 
  • In this above code we've used a 3rd party frontend css library to speed up our front end jobs beautifully.
  • Now lets see the implementation of the said tool nodemon.
  • in the command line, preferably in the VS Code, type: npm run dev
    • alt text
  • Now comes the snippet for the url shortening form in teh home.ejs file. Place the below snippet right below the <!-- FORM --> Comment in the html file:
<!-- FORM -->
<form action="/shorten/" method="POST" style="padding: 0 25px 0 25px;">
  <div class="form-group row justify-content-md-center">
    <label class="col-lg-1 col-md-10" for="longUrl">Long URL: 
    </label>
    <input required="" type="url" class="col-lg-3 col-12 form-control" name="longUrl" id="longUrl" placeholder="Enter your Name">
  </div>
  <div class="form-group row justify-content-md-center">
    <label class="col-lg-1 col-md-10" for="shortUrl">Short URL: 
    </label>
    <input type="text" class="col-lg-3 col-12 form-control" id="shortUrl" name="shortUrl" placeholder="Enter the custom name (if any)">
  </div>
  <div class="form-group row justify-content-md-center">
    <button type="submit" class="col-12 col-lg-4 btn btn-primary">Submit
    </button>
  </div>
</form>
 
and the Table code below the Table Comment <!-- URLs Table -->:
<!-- URLs Table --> 
<div style="margin: auto;" class="row justify-content-md-center table-responsive-sm"> 
  <table style="padding: 0 25px 0 25px;" class="table table-hover col-12 col-md-10 col-lg-6"> 
    <thead> 
      <tr> 
        <th># ID
        </th> 
        <th>Long URL
        </th> 
        <th>Short URL
        </th> 
        <th>Clicks
        </th> 
      </tr> 
    </thead> 
    <tbody> 
      <tr> 
        <th scope="row">#
        </th> 
        <td>
          <a target="_blank" href=#">Long URL Comes Here</a></td> <td><a target="_blank" href="#">Short URL Comes Here</a></td> <td>0</td> </tr> </tbody> </table> </div>
 
  • Now refresh the browser page
    • alt text
Stay tuned for the next part...
Thanks for reading this article 😄

Comments

Popular posts from this blog

Post-Event Resources- Ai Gaming with Microsoft Azure Heya  Folks hope you enjoyed the Event, do let us know in the comment section about your experience. As said, Here are the Post Event Resources for your continual Learning... Basic Concept of Ai (Theory) AI in Video Games: Toward a More Intelligent Game What is an API Open-Ai 5 Article Microsoft Cognitive- Getting started with Azure Cognitive Services Bundled Playlist on Youtube Microsoft Cognitive Vision Service- Try for Free online Some Videos by Siraj:  OpenAI Five vs Dota 2 Explained How to Install OpenAI's Universe and Make a Game Bot    How to Make an Amazing Video Game Bot Easily Hope you find the Resources resources... For folks interested in Microsoft Azure ML, Click Here

Creating a URL Shortener Deplyment on Azure (NodeJS) part-2

For reference to the previous post, please refer to this link : Connecting-to-our-Database Now let's head to the package that we added config in the npm install command, what it does is that it will look for default.json the file inside config (folder) which we created earlier that will consist of the global variables for our project. Now let's open that default.json file and place the below snippet in it: { "mongoURI": "<ConnectionStringHere>" } We'll replace the Connection String from the cluster's string from our Atlas Account (if you still don't have an account, click here to create one) After Logging in to the Atlas, create a free Cluster and add a database user in it Now use the below code in the db.js the file inside the config (folder): const mongoose = require('mongoose'); const config = require('config'); // Grab the Connection string URL from the default.json file const db = confi...

Signing Up for Azure 4 Students Account

Sign-Up: Microsoft Azure 4 Students Hola readers, In this post we're gonna learn how to create a new Microsoft Azure Account for Students. As a typical Azure account requires you to provide with the Credit Card details but due to the fact that not all the students around the globe have credit cards. So Microsoft have a provision for granting Azure Credits to students by the help of their Educational Account provided by their School/ Universities. Here are the steps provided to create a new Azure4Students Account (Though a video is also available to follow along): Text version of the SigningUp Process Visit: aka.ms/Azure4Students Sign in with your Microsoft Account or create a Microsoft Account if you don't have one After successfully logging in, enter your Country code & mobile number. Then click on the Verification options (Text/ Call) for your Identity verification. Next comes the Student Verification. This can be done by either: Providing your scho...
Counter Widget