<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Pujan Gautam on Medium]]></title>
        <description><![CDATA[Stories by Pujan Gautam on Medium]]></description>
        <link>https://medium.com/@mepujan10?source=rss-6b15035c2a6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qTtg0SvfnDjKMdAB</url>
            <title>Stories by Pujan Gautam on Medium</title>
            <link>https://medium.com/@mepujan10?source=rss-6b15035c2a6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:18:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mepujan10/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploy Django Application Using Docker, NGINX, and EC2]]></title>
            <link>https://mepujan10.medium.com/deploy-django-application-using-docker-nginx-and-ec2-915a353b83a5?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/915a353b83a5</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[django-deployment]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 17:44:55 GMT</pubDate>
            <atom:updated>2024-02-07T01:47:22.817Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, we are going to deploy the Django web application in AWS EC2 using docker and NGINX web server.</p><h4>Prerequisite</h4><ol><li>Existing Django Web Application</li><li>Docker</li><li>Gunicorn wsgi server</li><li>General Knowledge of EC2 Instance</li></ol><p>If you do not have docker in your system, you can install it from the docker official website <a href="https://www.docker.com/"><em>https://www.docker.com/</em></a></p><p>To install gunicorn server, first activate your virtual environment and install it using command:</p><p><em>pip install gunicorn</em></p><p>And generate “requirements.txt” file using command:</p><p><em>pip freeze &gt; requirements.txt</em></p><h4>Setting Up Docker Environment</h4><p>In project level, create a file name “Dockerfile” and write following codes. You can use the base image of your choice, working directory but the main concept remains the same.</p><pre>FROM python:3.11.4-alpine<br><br>WORKDIR /usr/src/app<br><br># Set environment variables<br>ENV PYTHONDONTWRITEBYTECODE 1<br>ENV PYTHONUNBUFFERED 1<br><br># Upgrade pip and install dependencies<br>RUN pip install --upgrade pip<br><br># Copy requirements file and install dependencies<br>COPY ./requirements.txt /usr/src/app/<br>RUN pip install -r requirements.txt<br><br># Copy entrypoint script<br>COPY ./entrypoint.sh /usr/src/app/entrypoint.sh<br><br># Switch to root to set execute permission<br>RUN [&quot;chmod&quot;, &quot;+x&quot;, &quot;/usr/src/app/entrypoint.sh&quot;]<br><br># Copy the rest of the application code<br>COPY . /usr/src/app/<br><br># Specify the entrypoint script<br>ENTRYPOINT [&quot;sh&quot;,&quot;/usr/src/app/entrypoint.sh&quot;]</pre><p>This Dockerfile begins with the Python 3.11.4 Alpine base image, sets the working directory to /usr/src/app, and establishes environment variables to optimize Python behavior. It upgrades pip and installs dependencies from a requirements.txt file. An entrypoint script (entrypoint.sh) is copied, given execute permissions, and the remaining application code is added. The entrypoint script is specified to run when the container starts. This Dockerfile facilitates the creation of a lightweight Python environment in a container, ensuring efficient dependency management and script execution, particularly useful for containerized Python applications.</p><p>Similarly, create a file name “docker-compose.yml” and</p><pre>version: &#39;3.2&#39;<br>services:<br>  django_gunicorn:<br>    env_file:<br>      - .env<br>    build:<br>      context: .<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - static:/usr/src/app/staticfiles<br><br>  nginx:<br>    build: ./ngnix<br>    volumes:<br>      - static:/usr/src/app/staticfiles<br>    ports:<br>      - &quot;80:80&quot;<br>    depends_on:<br>      - django_gunicorn<br>volumes:<br>  static:</pre><p>Version 3.2 of the Docker Compose configuration defines two services. The first, django_gunicorn, utilizes an environment file, builds from the current context, maps ports 8000 to 8000, and shares volumes for static files. The second service, nginx, builds from the &quot;./nginx&quot; directory, shares the same static file volume, maps ports 80 to 80, and depends on the availability of the django_gunicorn service. A volume named &quot;static&quot; is created to persist static files across these services. This configuration orchestrates the deployment of Django with Gunicorn and Nginx in a Dockerized environment.</p><p>Now, we will be creating “entrypoint.sh” file. This file contains the basic commands that we run in django terminal:</p><pre>#!/bin/sh<br>echo &quot;Apply Database Migration&quot;<br>python manage.py migrate --no-input<br>python manage.py collectstatic --no-input<br>gunicorn src.wsgi:application --bind 0.0.0.0:8000</pre><p>This shell script initiates database migration, applies Django model changes, and collects static files. Finally, it starts the Gunicorn server, running the src.wsgi module&#39;s application object, binding to 0.0.0.0 on port 8000.</p><h4>Setting Up NGINX</h4><p>Create folder name “nginx” in your project. Inside “nginx” folder create two files name “Dockerfile” and “default.conf” respectively.</p><h4>Setting up default.conf file</h4><pre>upstream django {<br>    server django_gunicorn:8000;<br>}<br><br>server {<br>    listen 80;<br><br>    location / {<br>        proxy_pass http://django;<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br><br>    location /static/ {<br>        alias /usr/src/app/staticfiles/;<br>    }<br>}</pre><p>This Nginx configuration sets up an upstream block named django pointing to the Gunicorn server (django_gunicorn) on port 8000. The server block listens on port 80 and directs requests to the Django application through the defined upstream. It includes proxy settings to forward headers like Host, Real IP, and Forwarded-For. For static files, requests to the &quot;/static/&quot; path are redirected to the specified directory in the container (&quot;/usr/src/app/staticfiles/&quot;). This Nginx configuration enables the seamless integration of Django and Gunicorn, efficiently handling static files and proxying requests to the Django application.</p><h4>2. Setting up Dockerfile</h4><pre>FROM nginx:1.19.0-alpine<br>COPY ./default.conf /etc/nginx/conf.d/default.conf</pre><p>This Dockerfile utilizes the Nginx 1.19.0 Alpine base image. It then copies a custom Nginx configuration file (default.conf) into the container&#39;s /etc/nginx/conf.d/ directory. This configuration likely includes settings for the upstream Django server, defines how requests are proxied, and specifies the handling of static files. This Dockerfile is designed to customize the Nginx configuration for seamless integration with the Django application and Gunicorn server.</p><p>Now, Everything is configured, we can check if everything is running well in our local device using command:</p><p><em>docker-compose up</em><em>--build</em></p><p>To build docker in detached mode.</p><p><em>docker-compose up -d</em><em>--build</em></p><p>This command instructs Docker Compose to rebuild the images (--build) and then start the services in detached mode (-d). The --build flag ensures that the images are rebuilt before starting the containers, incorporating any changes made to the Dockerfiles or related files.</p><p>Make sure you run this command in the same directory where your docker-compose.yml file is located.</p><h4>Deploying Project in EC2</h4><p>In “settings.py” file, update the following</p><pre>DEBUG = FALSE<br><br>ALLOWED_HOSTS = [&#39;*&#39;]</pre><p>Push all the project in GitHub. We will be cloning the project from GitHub in EC2 instance.</p><p>Launch an EC2 instance. While Launching instance, donot forget to checked “Allow HTTPS Traffic” and “Allow HTTP Traffic” checkbox. Otherwise, it need to be added manually in “Inbound Rules” in security group.</p><p>Wait for 2/2 security check and connect to the instance.</p><p>First, update and upgrade the instance using command:</p><p><em>sudo apt update &amp;&amp; sudo apt upgrade</em></p><p>Install docker and docker-compose using command:</p><p><em>sudo apt install docker.io docker-compose</em></p><p>Check the version of docker and docker-compose using commands:</p><p><em>sudo docker version</em></p><p><em>docker-compose --version</em></p><p>Now, Clone the project repository in EC2 using command:</p><p>git clone &lt;github-project-url&gt;</p><p>After cloning the project, change the directory to the project level.</p><p>cd &lt;project-directory-name&gt;</p><p>Then, run the command:</p><p><em>docker-compose up</em><em>--build</em></p><p>To build docker in detached mode.</p><p><em>docker-compose up -d</em><em>--build</em></p><p>After successful completion of building the container, we can use public IPv4 to access the website or public IPV4 DNS. But the public IPV4 changes each time the instance is restarted. So, inorder to fix this, we can assign “elastic ip” to make ip address persistant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=915a353b83a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NodeJS (Express)Application using Relation Database]]></title>
            <link>https://mepujan10.medium.com/nodejs-express-application-using-relation-database-da37e3866a6b?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/da37e3866a6b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[relational-databases]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 21:53:24 GMT</pubDate>
            <atom:updated>2023-02-06T21:53:24.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7pEsDl7pS4oSzvZ6iyD3g.png" /></figure><p>Sequelize is ORM (Object Relation Mapping) for TypeScript and NodeJS that supports Relational Database Management System like MYSQL, POSTGRES, ORACLE and more.</p><p>It allows to store javascript object into the relational database without using raw sql query. This means we can use OOP approach to write our queries.</p><p>Sequelize provides features such as solid transaction, relations among tables, lazy loading, read replication and more.</p><p>You can learn more about sequelize from</p><p><a href="https://sequelize.org/">Sequelize</a></p><p>Lets install the dependencies for the project:</p><p>npm install express sequelize mysql2 dotenv</p><p>Now lets create index.js file and test the connection with the database. For this tutorial i am using MYSQL.</p><pre>import express from &#39;express&#39;;<br>import { Sequelize } from &quot;sequelize&quot;;<br><br>const app = express();<br>const PORT = process.env.PORT || 3000;<br><br>const dbConnection = new Sequelize(process.env.DATABASE_URL);<br><br>app.use(express.json())<br><br>const Start = async() =&gt;{<br>  try{<br>    await dbConnection.authenticate();<br>     app.listen(PORT,()=&gt;{<br>            console.log(`Successfully Connected to Database ${config.db_name}.`);<br>            console.log(`Server is running on port ${PORT}`)<br>        });<br>      dbConnection.close();<br>    }<br>  catch(e){<br>  console.log(e);<br>  console.log(&quot;Server is not running. Try Again&quot;);<br>    }<br>}</pre><p>There are different ways to create database connection using sequelize. One that i show you is using DATABASE_URL . Here are some other approaches to connect to database. I have taken it from the documentation.</p><pre>import { Sequelize } from &#39;sequelize&#39;;<br><br>// Option 1: Passing a connection URI<br>const sequelize = new Sequelize(&#39;sqlite::memory:&#39;) // Example for sqlite<br>const sequelize = new Sequelize(&#39;postgres://user:pass@example.com:5432/dbname&#39;) // Example for postgres<br><br>// Option 2: Passing parameters separately (sqlite)<br>const sequelize = new Sequelize({<br>  dialect: &#39;sqlite&#39;,<br>  storage: &#39;path/to/database.sqlite&#39;<br>});<br><br>// Option 3: Passing parameters separately (other dialects)<br>const sequelize = new Sequelize(&#39;database&#39;, &#39;username&#39;, &#39;password&#39;, {<br>  host: &#39;localhost&#39;,<br>  dialect: /* one of &#39;mysql&#39; | &#39;postgres&#39; | &#39;sqlite&#39; | &#39;mariadb&#39; | &#39;mssql&#39; | &#39;db2&#39; | &#39;snowflake&#39; | &#39;oracle&#39; */<br>});</pre><p>Now lets create a model. In OOP approach, each table in database is represented by model. It is more likely the abstraction of table represented in database. For this we will be creating javascript class. There are two approach of defining model using sequelize.</p><h4>Approach -1</h4><p>Calling <em>sequelize.define(modelName, attributes, options)</em>method.</p><p>Example:</p><pre>//model/ProductModel.js<br><br>import {Sequelize,DataTypes} from &#39;sequelize&#39;;<br>const sequelize= new Sequelize(process.env.DATABASE_URL);<br><br>export const Product = sequelize.define(&#39;Product&#39;,{<br>  //attributes<br>  name:{<br>        type: DataTypes.STRING,<br>        allowNull: false<br>       },<br>  price:{<br>         type: DataTypes.DOUBLE,<br>         allowNull:false<br>        },<br>  descriptions:{<br>        type:DataTypes.STRING,<br>        allowNull:true<br>        }<br>},<br>//options<br>{<br>    sequelize,<br>    underscored: true,<br>    timestamps: true,<br>    modelName: &#39;Product&#39;<br>  });</pre><p>You can take reference from documentation for all datatypes and validation. We need to pass sequelize and modelName as an option. Here, timestamps: true will automatically create createdAt and updatedAt timestamp when the object is created.</p><h4>Approach -2</h4><p>By extending Model and calling <em>init(attributes,options)</em></p><p>Example: We will take same example from approach-1.</p><pre>//model/ProductModel.js<br><br>import {Sequelize,DataTypes} from &#39;sequelize&#39;;<br>const sequelize= new Sequelize(process.env.DATABASE_URL);<br><br>class Product extends Model{}<br>export default User.init({<br>  name:{<br>    type:DataTypes.STRING,<br>    allowNull: false<br>},<br>  price:{<br>    type: DataTypes.DOUBLE,<br>    allowNull: false<br>},<br>  descriptions:{<br>    type: DataTypes.STRING,<br>    allowNull: true<br>}<br>},{<br>    sequelize,<br>    underscored: true,<br>    timestamps: true,<br>    modelName: &#39;Product&#39;<br>  });</pre><p>Both approaches are equivalent.</p><p>We can also create database table automatically from the model above. This can be done by adding</p><p>Product.sync();</p><p>Now let’s create two controller:</p><blockquote>Fetch All data from the Database</blockquote><pre>//controllers/ProductController.js<br><br>import Product from &#39;./model/ProductModel.js&#39;;<br><br>export const FetchAllProducts = async(req,res,next)=&gt;{<br>     try{<br>        const data = await Product.findAll();<br>        return res.status(200).json(data);<br>  <br>    }catch(e){<br>        next(e)<br>    }<br>}</pre><blockquote>Save Product data to Database</blockquote><p>Sequelize provides two approach to save database to database:</p><blockquote>Using create()method:</blockquote><p>This method directly write data to database.</p><pre>//controllers/ProductController.js<br><br>import Product from &#39;./model/ProductModel.js&#39;;<br><br>export const AddNewProduct = async(req,res,next)=&gt;{<br>     try{<br>        const newProduct = await Product.create(req.body);<br>        return res.status(201).json({message:&quot;Product Saved Successfully&quot;,newProduct});<br>  <br>    }catch(e){<br>        next(e)<br>    }<br>}</pre><blockquote>2. Using build() method:</blockquote><p>build() method first create model-object from the data provided and then save() method is called to actually write data to database.</p><p>It allows to manipulate data in between creating javascript object and saving data to database.</p><pre>//controllers/ProductController.js<br><br>import Product from &#39;./model/ProductModel.js&#39;;<br><br>export const AddNewProduct = async(req,res,next)=&gt;{<br>     try{<br>        const newProduct = await Product.build(req.body);<br>        const savedResult = newProduct.save();<br>        return res.status(201).json({message:&quot;Product Saved Successfully&quot;,savedResult});<br>  <br>    }catch(e){<br>        next(e)<br>    }<br>}</pre><p>Now Defining routes for each methods:</p><pre>// routes/productRoutes.js<br><br>import express from &#39;express&#39;;<br>import {FetchAllProducts, AddNewProduct} from &quot;./controllers/ProductController.js&quot;;<br><br>const productRoutes = express.Router();<br><br>productRoutes.get(&quot;/products&quot;,fetchAllProducts);<br>productRoutes.post(&quot;/addProduct&quot;,AddNewProduct);<br></pre><p>Sequelize also provide feature for Associations and more. For more informations, please refer to official documentation of sequelize.</p><p><a href="https://sequelize.org/docs/v7/getting-started/">Getting Started | Sequelize</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da37e3866a6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Sending Email Verification Code And Verifying Code Django Rest API]]></title>
            <link>https://mepujan10.medium.com/implementing-sending-email-verification-code-and-verifying-code-django-rest-api-ed52c93e156e?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed52c93e156e</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 01:27:26 GMT</pubDate>
            <atom:updated>2022-12-10T01:33:49.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Here, In this tutorial, we will be implementing email verification code to the Django REST API. This will be suitable for scenario where email has to be verified before hand. For example, while registering for certain program, you first need to provide an email and after that you will get verification code provided in email and entering that code will verify you or to validate the email before resetting the password and so on.</p><pre># Packages Used:<br>Django<br>DjangoRestFramework</pre><p>Firstly, I am setting up model with class name EmailVerificationCode . This model will have two fields email and code where we will be saving user entered email in email field and automatically generated code in code . After that we will override save method to generate 6-digit random number before saving it to the database.</p><p>You can do it multiple ways using pre_save or post_save signals. But I will show you overriding the save method.</p><pre># models.py file<br><br>import random<br><br>class EmailVerificationCode(models.Model):<br>    email = models.EmailField()<br>    code = models.CharField(max_length=6,null=True,blank=True)<br><br><br>    def __str__(self):<br>        return f&#39;{self.code} is generated for {self.email} &#39;<br><br>    def save(self,*args,**kwargs):<br>        numbers = [i for i in range(10)]<br>        code =[]<br><br>        for _ in range(6):<br>            num = random.choice(numbers)<br>            code.append(num)<br>        code_str = &#39;&#39;.join(str(i) for i in code)<br>        self.code = code_str<br>        return super().save(*args,**kwargs)</pre><p>Inside the save method, first we generate the list of integer numbers starting from 0 to 9.</p><p>We have empty list code where we will append random number chosen by random.choice() method. After that, converting list to string using .join() method and assiging that code to the code variable of our class and returning save() method. Now when we provide email a randomly generated 6-digit number will automatically save to database.</p><p>This saved code is send to the user and use for verifying the user.</p><p>Now, we will create a serializer, that will only contain email field. This is because code will be automatically generated and saved in database.</p><pre>#serializers.py file<br>from rest_framework import serializers<br><br>class EmailVerificationSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = EmailVerificationCode<br>        fields = (&#39;email&#39;,)</pre><p>Now we will write a logic to send code via email, if that sepecific API is called.</p><pre># views.py file<br><br>from rest_framework.views import APIView<br>from .serializers import EmailVerificationSerializer<br><br>class SendCodeViaEmailAPIView(APIView):<br>    serializer_class = EmailVerificationSerializer<br>    def post(self,request):<br>        serializer= self.serializer_class(data = request.data)<br>        if serializer.is_valid():<br>            EmailVerificationCode.objects.update_or_create(<br>                email= serializer.data[&#39;email&#39;],<br>                defaults={<br>                    &#39;email&#39;:serializer.data[&#39;email&#39;]<br>                }<br>                )<br>            code = EmailVerificationCode.objects.get(email=serializer.data[&quot;email&quot;]).code<br>            html_file = get_template(&quot;email_validation.html&quot;)<br>            html_content = html_file.render({&quot;verification_code&quot;: code})<br>            subject = &quot;why this code is send&quot;<br>            message = &quot;Email Body&quot;<br>            from_email = &quot;test@gmail.com&quot;<br>            recipient_list = [serializer.data[&quot;email&quot;]]<br>            email = EmailMultiAlternatives(<br>                    subject,<br>                    message,<br>                    from_email,<br>                    recipient_list,<br>                )<br>            email.attach_alternative(html_content, &quot;text/html&quot;)<br>            email.send()<br><br>            return Response(<br>                    {&quot;success&quot;: &quot;Success! Check your email for the code.&quot;}<br>                )<br>        else:<br>            return Response(status=status.HTTP_400_BAD_REQUEST,{&quot;error&quot;:&quot;Validation failed&quot;})<br><br></pre><p>Here, first we check if the serializer is valid or not by populating the data that comes from the user. The data will be in request.data field. If the data coming from the user is not valid email address then it will fail and return an error with 404 status code . If the data is validated then, create_or_update method creates if object does not exist otherwise it will update the code of email in existing data.</p><p>The verification code generated will be fetched and pass to the template file using .render() method as shown above. Then passing all the attributes defined to EmailMultiAlternatives() method. It will provide feature to send message in html format.</p><p>Then we will define simple template called email_validation.html in templates folder. We can style the template as we like. I am using a simple html styling</p><pre>// email_validation.html <br><br>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br><br>&lt;head&gt;<br>  &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>  &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>  &lt;title&gt;Email Validation&lt;/title&gt;<br>&lt;/head&gt;<br><br>&lt;body&gt;<br>  {% autoescape off %}<br>  &lt;h3&gt;Welcome To Test APP&lt;/h3&gt;<br>  &lt;h4&gt;<br>    Your Email Verification code is :<br>    &lt;b style=&quot;color: darkgreen&quot;&gt;{{ verification_code }}&lt;/b&gt;<br>  &lt;/h4&gt;<br>  &lt;p&gt;If you think, it&#39;s not you, then just ignore this email.&lt;/p&gt;<br>  &lt;p&gt;For any Queries or any feedback,&lt;/p&gt;<br>  &lt;p&gt;Email: test@gmail.com&lt;/p&gt;<br><br>  {% endautoescape %}<br>&lt;/body&gt;<br><br>&lt;/html&gt;</pre><p>Now, implementing logic to validate the code send by user.</p><p>For this, we will be asking, both email and send code from the user.</p><p>For this, lets write the serializer</p><pre># serializers.py <br># This is the same page that we have above.<br><br>from rest_framework import serializers<br><br>class CodeVerificationSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = EmailVerificationCode<br>        fields = (&#39;email&#39;,&#39;code&#39;)</pre><p>Now its API View will be as:</p><pre># views.py file<br><br>class VerifyCodeAPI(APIView):<br>    def post(self, request):<br>        email = request.data[&#39;email&#39;]<br>        code = request.data[&#39;code&#39;]<br>        if EmailVerificationCode.objects.filter(email=email,code=code).exists():<br>            return Response({&quot;success&quot;:&quot;Code Successfully Verified.&quot;})<br>        else:<br>            return Response(status=status.HTTP_404_NOT_FOUND,{&quot;error&quot;:&quot;Code doesnot match.&quot;})</pre><p>We just collect the email and code sent by the user and filter that data from the database using filter method. If the both code and its associated email exist then API will send success message as a response with 200 OK status code. Otherwise, it will send error message with 404 status code.</p><p>Now we can define the URL end-points for both APIs, We will do this in urls.py file</p><pre># urls.py file<br>from django.urls import path<br>from .views import SendCodeViaEmailAPIView, VerifyCodeAPI<br><br>urlpatterns = [<br>  path(&#39;api/send_verification_code&#39;,SendCodeViaEmailAPIView.as_view(), name =&quot;send_code&quot;),<br>  path(&#39;api/verify_code&#39;,VerifyCodeAPI.as_view(), name = &quot;verify_code&quot;)<br>]</pre><p>Last but not the least, now we have to write configuration to set up SMTP in settings.py file. It must be there otherwise email service will not work.</p><pre># Include this in settings.py file<br><br>EMAIL_USE_TLS = True<br>EMAIL_HOST = &quot;smtp.gmail.com&quot;<br>EMAIL_HOST_USER = &quot;youremail@gmail.com&quot;<br>EMAIL_HOST_PASSWORD = &quot;your_password&quot;<br>EMAIL_PORT = 587</pre><p>EMAIL_HOST_USER, EMAIL_HOST_PASSWORD you can be save it in .env file and and fetch data from there for security purposes.</p><p>That’s it, you have successfully build the API service that sends verification code to the user and validate it.</p><p>It’s a simple concept but can vary its usage as per the requirement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed52c93e156e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express JS Joining Two Collections using Aggregate Method]]></title>
            <link>https://mepujan10.medium.com/express-js-joining-two-collections-using-aggregate-method-1e3f199c017c?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e3f199c017c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 23:05:53 GMT</pubDate>
            <atom:updated>2023-03-05T00:17:05.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPQ7MDPCOdpdJSXP2f3Jjw.png" /><figcaption><a href="https://www.toptal.com/nodejs/secure-rest-api-in-nodejs">https://www.toptal.com/nodejs/secure-rest-api-in-nodejs</a></figcaption></figure><p>In this tutorial, we will be looking at the aggregating two collections of MongoDB in Express JS. And populate the foreign objectId field with its related data. We will be generating the schema and implementing validation to different attributes.</p><blockquote>We will develop two schema “ProductSchema” and “BrandSchema” and draw the relationship between them. And also look at how we can join these two tables to view the combined result.</blockquote><p>From the schema we will be creating models to interact with the database.</p><p>First let us list all the packages required to build the project</p><ul><li><em>express</em></li><li><em>mongoose</em></li><li><em>body-parser</em></li></ul><p>Here, mongoose is a package that allows to use ORM (Object Relation Mapping) to talk with the database instead of raw SQL query. It means we can query the database using Object-Oriented Paradigm.</p><p>And what body-parser does is that it parse HTTP request body. It provides middleware for parsing JSON, plain text and other files object.</p><blockquote>Now lets make the project name and call it “MyStore” and first lets initialize this folder to set up npm packages. This can be done using following command:</blockquote><pre>npm init -y</pre><p>It will create package.json file that contains all the details of project and its dependencies.</p><p>Now, lets install all the dependencies required for the project:</p><pre>npm i express mongoose body-parser</pre><p>In this project, we will be using ES6 syntax. So, do not forgot to include,</p><blockquote><em>“</em>type”: “module”</blockquote><p>in <em>package.json</em> file, otherwise you will get error.</p><p>Now, creating model folders and inside it creating two files <em>“product.js” </em>and <em>“brand.js”</em></p><p>Lets dive into <em>“product.js”</em> file to define schema and model.</p><pre>//product.js file<br><br>import mongoose from &quot;mongoose&quot;;<br><br>const ProductSchema = new mongoose.Schema({<br>    product_name: {<br>        type: String,<br>        required: true<br>    },<br>    price: {<br>        type: Number,<br>        required: &quot;Price is required&quot;<br>    },<br>    brand: {<br>        type: Schema.Types.ObjectId,<br>        ref: &#39;Brand&#39;<br>    }<br><br>});<br><br>export default mongoose.model(&quot;Product&quot;, ProductModelSchema);</pre><p>Here brand attribute will be the<em> ObjectId </em>of <em>“Brand”</em> model. We can define reference to <em>“Brand”</em> model using <em>“ref”</em> keyword.</p><p>In <em>“brand.js”</em> file:</p><pre>// brand.js<br><br>import mongoose from &quot;mongoose&quot;;<br><br>const BrandSchema = new mongoose.Schema({<br>    name: {<br>        type: String,<br>        unique: true,<br>        required: true<br>    }<br>});<br><br>export default mongoose.model(&quot;Brand&quot;, BrandSchema);</pre><p>Now, lets create a controller folder and inside that folder, we will create two files <em>“productController.js”</em> and <em>“brandController.js”</em></p><p>In <em>brandController.js</em> file, we will import <em>“Brand” </em>model created from <em>“BrandSchema”</em></p><pre>// brandController.js<br><br>import Brand from &#39;../model/brand.js&#39;;<br><br>export const createNewBrand = async(req, res,next) =&gt;{<br>try{<br>    const newBrand = new Brand(req.body);<br>    const result = await newBrand.save();<br>    return res.status(201).json(result);<br>  }catch(error){<br>      next(error)<br>  }<br>}</pre><p>You can make the functions that will get all brand list , get brand by id or by name and delete the brand by id.</p><p>Now, lets create the method that will create new product object in database and get specific product by id. we will also join the product model with brand model to provide aggregate result to user.</p><pre>// productController.js<br><br>import Product from &#39;../model/product.js&#39;;<br>import mongoose from &#39;mongoose&#39;;<br><br>// function to create new product <br><br>export const createNewProduct = async(req,res,next) =&gt;{<br>  try{<br>      const newProduct = new Product(req.body);<br>      const result = newProduct.save();<br>      return res.status(201).json(result);<br>  }catch(error){<br>    next(error);<br>  }<br>}<br><br><br><br>// function that return aggregate data of product and brand <br><br>export const getProductById = async(req,res,next) =&gt;{<br>  try{<br>      const { productId } = req.params;<br>      const product =  await Product.aggregate([<br>            {<br>                $match:{ _id : new mongoose.Types.ObjectId(productId)}<br>            },<br>            {<br>                $lookup:{<br>                    from:&#39;brands&#39;,<br>                    localField:&#39;brand&#39;,<br>                    foreignField: &#39;_id&#39;, <br>                    as:&#39;brand&#39;<br>                }<br>            },<br>            {<br>                $unwind :&#39;$brand&#39;<br>            }<br>        ]);<br>    return res.status(200).json(product);<br>  }catch(error){<br>    next(error);<br>  }<br>}<br><br></pre><blockquote>we need to specify all those four attributes inside lookup. And <em>$unwind</em> need to be specified otherwise it will create list of brand object .</blockquote><p>Now create routes folder and inside it create “route.js” file.</p><p>In route.js file</p><pre>// route.js<br><br>import express from &#39;express&#39;;<br>import { createNewProduct , getProductById } from &#39;../controller/productController.js&#39;;<br><br>const router = express.Router();<br><br>router.post(&#39;/create_product&#39;, createNewProduct);<br>router.get(&#39;/product/:productId, getProductById);<br><br>export default router;</pre><p>We can do the same thing to create route for the brandController.</p><p>Now importing the route in index.js file, lets create index.js file</p><pre>//index.js <br>//setting up index file<br><br>import express from &#39;express&#39;;<br>import bodyParser from &#39;body-parser&#39;;<br>import router from &#39;./routes/route.js&#39;<br><br>const app = express();<br>app.use(express.json());<br>app.use(bodyParser.urlencoded({extended:true}));<br><br>// router is implemented here as middleware<br>app.use(router);<br><br>const PORT = process.env.PORT || 3000;<br><br>const Start = async() =&gt;{<br>    try{<br>        await connectionDB(databaseURL);<br>        app.listen(PORT,()=&gt;{<br>            console.log(&quot;Successfully Connected to Database.&quot;);<br>            console.log(`Server is running on port ${PORT}`)<br>        });<br>    }catch(error){<br>        console.log(error);<br>        console.log(&quot;Failed To Connect to Database. Server is not running&quot;);<br>    }<br>    <br>}<br><br>Start();</pre><blockquote>To setup the connectionDB, you can refer <a href="https://medium.com/@mepujan10/setup-mongodb-connection-in-express-js-9cbc4db1273">https://medium.com/@mepujan10/setup-mongodb-connection-in-express-js-9cbc4db1273</a></blockquote><p>We can check out output using postman or other API client application that allows to interact with the server.</p><p>when you call</p><p>“localhost:3000<em>/product/?productId=</em>636aa0247d488df79692418d<em>”</em></p><p>from postman you will get the result as below</p><pre>{<br>    &quot;_id&quot;: &quot;636aa0247d488df79692418d&quot;,<br>    &quot;product_name&quot;: &quot;A52- Samsung&quot;,<br>    &quot;price&quot;: 250.5,<br>    &quot;brand&quot;: {<br>        &quot;_id&quot;: &quot;636951103c62324aecd303ee&quot;,<br>        &quot;name&quot;: &quot;Samsung&quot;,<br>        &quot;__v&quot;: 0<br>    },<br>    &quot;__v&quot;: 0<br>}</pre><p>If we don’t use aggregate method, our output will look like:</p><pre>// response without using aggregate method<br>{<br>    &quot;_id&quot;: &quot;636aa0247d488df79692418d&quot;,<br>    &quot;product_name&quot;: &quot;A52- Samsung&quot;,<br>    &quot;price&quot;: 250.5,<br>    &quot;brand&quot;: &quot;636951103c62324aecd303ee&quot;,<br>    &quot;__v&quot;: 0<br>}</pre><p>This output below is less readable than and first one and if we need brand details as well then we have to call two apis to get the combined result. But with aggregate method implemented, we get required response in one api call which ultimately increase the performance of application that api will be called from.</p><p>To dive more into the REST API using Express JS and mongoose, you can look for the reference code here :</p><p><a href="https://github.com/mepujan/Ecommerce_Be">GitHub - mepujan/Ecommerce_Be</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e3f199c017c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Firebase Push Notification API in Django for Android Notification]]></title>
            <link>https://mepujan10.medium.com/integrating-firebase-push-notification-in-django-for-android-notification-api-640256dcad70?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/640256dcad70</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Sun, 04 Dec 2022 03:45:31 GMT</pubDate>
            <atom:updated>2022-12-05T02:43:44.042Z</atom:updated>
            <content:encoded><![CDATA[<p>To understand this content, you need to have some prior knowledge in Django framework and Firebase.</p><h4>Requirements:</h4><ul><li><em>Python3</em></li><li><em>Django</em></li><li><em>Django Rest Framework</em></li></ul><blockquote>First we need to create project in firebase. Inside project go to ProjectOverview -&gt; Project Settings -&gt; Service Account</blockquote><p>You will find “Generate new private key” button. Clicking on this button will download the private key to local drive. It can be use in code to verify the user FCM token.</p><p>Now we will integrate it to the Django Project. For this we need to install package called firebase admin. It can be installed via following command:</p><pre>pip install firebase-admin</pre><p>Now we will use above download file to provide credential to web application and define function that holds configuration to send notification in android application. Lets call this file util.py</p><pre>import os<br><br>import firebase_admin<br>from firebase_admin import credentials, messaging<br><br>cred = credentials.Certificate(&lt;path_to_private_key&gt;)<br>firebase_admin.initialize_app(cred)<br><br>def send_push(title, msg, registration_token, data_object):<br>    message = messaging.MulticastMessage(<br>        tokens=registration_token,<br>        android=messaging.AndroidConfig(<br>            priority=&quot;high&quot;,<br>            notification=messaging.AndroidNotification(<br>                title=title,<br>                body=msg,<br>                priority=&quot;high&quot;,<br>                click_action=&quot;FLUTTER_NOTIFICATION_CLICK&quot;,<br>                default_sound=True,<br>                color=&quot;#AFEEEE&quot;,<br>                default_light_settings=True,<br>                ticker=&quot;Test&quot;<br>                icon= &quot;favicon.ico&quot;<br>                vibrate_timings_millis=[30, 50000, 400, 10000, 400, 100, 400]<br>            ),<br>            data=data_object,<br>        ),<br>    )<br>    messaging.send_multicast(message)</pre><p>Here, send_multicast(message) provides feature to send notification to multiple devices. Every things here can be changed according to user requirement.</p><p>First lets create a model and for the notification API in file models.py</p><pre>class Notification(models.Model):<br>    sender_id = models.ForeignKey(User, on_delete = model.CASCADE)<br>    receiver_id = models.ForeignKey(User, on_delete = model.CASCADE)<br>    call_url = models.URLField()<br>    created = models.DateTimeField(auto_now_add=True)<br>    updated = models.DateTimeField(auto_now=True)<br><br>    def __str__(self):<br>        return f&quot;{self.receiver_id} received notification from {self.sender_id}&quot;</pre><p>Now lets create serializer.py file.</p><pre>class NotificationSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Notification<br>        fields = &quot;__all__&quot;</pre><p>After that creating the api view</p><pre>class NotificationAPIView(generics.CreateAPIView):<br>    serializer_class = NotificationSerializer<br><br>    def post(self, request, *args, **kwargs):<br>        import .utils as fcm<br><br>        sender = User.objects.filter(id=request.data[&quot;sender_id&quot;]).exists()<br>        receiver = User.objects.filter(id=request.data[&quot;receiver_id&quot;]).exists()<br>        if receiver and sender:<br>            receiver_fcm = UserFCMToken.objects.filter(<br>                user_id__exact=request.data[&quot;receiver_id&quot;]<br>            ).exists()<br>            if receiver_fcm:<br>                usr_token = UserFCMToken.objects.get(<br>                    user_id__exact=request.data[&quot;receiver_id&quot;]<br>                ).fcm_token<br>                token = [usr_token]<br>                sender_name = User.objects.get(id=request.data[&quot;sender_id&quot;]).username<br>                sender_image = User.objects.get(<br>                    id=request.data[&quot;sender_id&quot;]<br>                ).profile_pic<br>                sender_email = User.objects.get(id=request.data[&quot;sender_id&quot;]).email<br>                call_url = request.data[&quot;call_url&quot;]<br>                title = f&quot;{sender_name} is calling ....&quot;<br>                msg = &quot;Tap to Receive&quot;<br>                data_obj = {<br>                    &quot;title&quot;: sender_name + &quot; is calling...&quot;,<br>                    &quot;body&quot;: &quot;Tap Join to Receive&quot;,<br>                    &quot;sender_id&quot;: str(request.data[&quot;sender_id&quot;]),<br>                    &quot;sender_name&quot;: sender_name,<br>                    &quot;sender_image&quot;: str(sender_image),<br>                    &quot;sender_email&quot;: str(sender_email),<br>                    &quot;call_url&quot;: str(call_url),<br>                    &quot;click_action&quot;: &quot;FLUTTER_NOTIFICATION_CLICK&quot;,<br>                    &quot;sound&quot;: &quot;default&quot;,<br>                    &quot;status&quot;: &quot;done&quot;,<br>                    &quot;screen&quot;: &quot;screenA&quot;,<br>                }<br>                fcm.send_push(title, msg, token, data_obj)<br>                return self.create(request, *args, **kwargs)<br>            else:<br>                return Response(<br>                    {&quot;message&quot;: &quot;No FCM token associated with the receiver&quot;}<br>                )<br>        else:<br>            if sender:<br>                return Response({&quot;message&quot;: &quot;No Receiver Details Available&quot;})<br>            elif receiver:<br>                return Response({&quot;message&quot;: &quot;No Sender Details Available&quot;})<br>            else:<br>                return Response({&quot;message&quot;: &quot;No User Available&quot;})</pre><p>Now creating the routes for the api. In urls.py file,</p><pre>from django.urls import path, include<br>from rest_framework.routers import DefaultRouter<br>from .views import NotificationAPIView<br><br>urlpatterns = [<br>path(&quot;api/send_notification/&quot;, CallAPIView.as_view(), name=&quot;send_notification&quot;),<br>]</pre><p>Now, our notification api is ready and is available in path <em>localhost:8000/api/send_notification/</em></p><p>You connect with me on LinkedIn and GitHub</p><p>LinkedIn: <a href="https://www.linkedin.com/in/pujangautam/"><em>https://www.linkedin.com/in/pujangautam/</em></a></p><p>Github:<em> </em><a href="https://github.com/mepujan"><em>https://github.com/mepujan</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=640256dcad70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Node JS Web App using Fly.io]]></title>
            <link>https://mepujan10.medium.com/deploy-node-js-web-app-using-fly-io-c6fe939b5292?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6fe939b5292</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[flyio]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 19:08:57 GMT</pubDate>
            <atom:updated>2022-12-03T19:13:07.621Z</atom:updated>
            <content:encoded><![CDATA[<p>Before deploying the web application, make sure that you have implemented CORS policy in express.</p><p>According to <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">Wikipedia</a>:</p><blockquote>Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. Certain “cross-domain” requests, notably Ajax requests, are forbidden by default by the same-origin security policy.</blockquote><p>In your express application, install CORS using following command:</p><p><em>npm install cors</em></p><p>Implement middleware in order to accept request from all origins.</p><p><em>import cors from ‘cors’;</em></p><p><em>app.use(cors());</em></p><p>Now, we need fly.io to deploy our app. Create account if you do not have one. You can use service for free but you need to provide credit card details to launch the application.</p><p>To use fly.io, first install flyctl in your operating system.</p><blockquote>For Mac, you can use homebrew or you can install via script</blockquote><p><em>brew install flyctl</em></p><p>or</p><p><em>curl -L </em><a href="https://fly.io/install.sh"><em>https://fly.io/install.sh</em></a><em> | sh</em></p><blockquote>For Linux, Run the install script</blockquote><p><em>curl -L </em><a href="https://fly.io/install.sh"><em>https://fly.io/install.sh</em></a><em> | sh</em></p><blockquote>For windows, Run PowerShell install script</blockquote><p><em>iwr </em><a href="https://fly.io/install.ps1"><em>https://fly.io/install.ps1</em></a><em> -useb | iex</em></p><p>After all these process, now its time to deploy our application to web. Your terminal should be in project level directory.</p><blockquote>Start by authenticating using the following command:</blockquote><p><em>flyctl auth login</em></p><blockquote>Initialize the app using following command:</blockquote><p><em>flyctl launch</em></p><p>It will ask you to choose app name, region of the server and database you want to use.</p><p>It will automatically generate Dockerfile and .dockerignore file.</p><blockquote>The last question will be “Would you like to deploy now (y/N)?”. choose ‘y’. Then your app is deployed to the fly.io server.</blockquote><p>You can view your application in fly.io dashboard. You can monitor, scale the production as per your need.</p><p>If you need to update something, you can update the code and re-deploy it using command:</p><p><em>flyctl deploy</em></p><p>To view the log in terminal or command prompt. You can use command:</p><p><em>flyctl log</em></p><p>After successful deploy of the application, fly.toml file is generated automatically. It contains all the configuration settings of your app in the server. You can add the configurations as per you need and after that you should re-deploy the app using above deploy command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEiArzM6U1XqJyKSINyZwQ.png" /></figure><p>Hostname inside Application Information is the URL of the site you hosted.</p><p>You can learn more from their official site:</p><p><a href="https://fly.io/">Deploy app servers close to your users · Fly</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6fe939b5292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup MongoDB Connection In Express JS]]></title>
            <link>https://mepujan10.medium.com/setup-mongodb-connection-in-express-js-9cbc4db1273?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbc4db1273</guid>
            <category><![CDATA[mongoosejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[express-and-mongodb]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[databaseconnectionexpress]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 03:03:02 GMT</pubDate>
            <atom:updated>2022-12-03T03:03:02.098Z</atom:updated>
            <content:encoded><![CDATA[<p>For this demo tutorial, I am using</p><blockquote>node version: 14.17.3</blockquote><blockquote>npm version: 6.14.3</blockquote><blockquote>express: ^4.18.2</blockquote><p>If you do not have node installed, then you can install using</p><p><a href="https://nodejs.org/en/">Node.js - Run JavaScript Everywhere</a></p><p>Check node version and npm version using command:</p><p><em>node — version</em></p><p><em>npm — version</em></p><p>Firstly, initialize the project in the directory using command:</p><p><em>npm init -y</em></p><p>And then install the package required. For this we are gonna use</p><ol><li><em>express</em></li><li><em>dotenv</em></li><li><em>mongoose</em></li></ol><p>Installing these dependencies for the project</p><p><em>npm install express dotenv mongoose</em></p><p>To support ES6 import syntax in the project. Add</p><p><em>“type”: “module”</em></p><p>in “package.json” file.</p><p>creating .env file and storing database connection string there:</p><p><em>DatabaseString = mongodb://localhost:27017</em></p><p>.env is an environment file that contains sensitive information such as Database Connection String, Secret Keys and others information that you do not want to expose to other user.</p><p>This file is only used for development purpose only.</p><p>After that lets create dbConnect.js file that holds the configuration to connect with database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*7vvU0lQgDbdla01OAH5nVA.png" /><figcaption>figure-1: Database Connection Configuration Code</figcaption></figure><p>In index.js file, lets use this write logic to start the server only when there is successful database connection established. Otherwise we will just log the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*Btf48oo9wtgRXG2lA_oQ4w.png" /><figcaption>figure-2: Index js file</figcaption></figure><p>After that the server can be run using the command:</p><p><em>node index.js</em></p><p>To learn more. Please refer to express JS official documentation.</p><p><a href="https://expressjs.com/">Express.js · Node.js web application framework</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbc4db1273" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GIT Merge and GIT Rebase]]></title>
            <link>https://mepujan10.medium.com/git-merge-and-git-rebase-dfc35b39b757?source=rss-6b15035c2a6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc35b39b757</guid>
            <category><![CDATA[git-merge-and-git-rebase]]></category>
            <category><![CDATA[git-merge]]></category>
            <category><![CDATA[git-rebase]]></category>
            <category><![CDATA[git-merge-vs-rebase]]></category>
            <dc:creator><![CDATA[Pujan Gautam]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 19:29:01 GMT</pubDate>
            <atom:updated>2022-12-03T05:32:10.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>GIT Merge vs GIT Rebase</h3><h3><strong>What is Merging ?</strong></h3><p>Merging means combining multiple entities into a single entity without having any conflict.</p><p>There are two ways of merging branches in GIT.</p><ol><li>Git Merge</li><li>Git Rebase</li></ol><p>To dive into the merging branch. First, we need to have some concept of branching. So first, lets develop some concept of branch.</p><h3>Git Branch</h3><p>Git Branch help to create an isolated development environment within the repository. Mostly used in independent line of development such as fixing bugs, developing new features without having direct interaction with the main branch.</p><p>Git provide feature to create, list, delete branch.</p><h4>Syntax</h4><blockquote>Creating the branch</blockquote><p><em>git branch &lt;branch_name&gt;</em></p><blockquote>Listing the existing branch</blockquote><p><em>git branch</em></p><blockquote>Delete existing branch</blockquote><p><em>git branch -d &lt;branch_name&gt;</em></p><blockquote>To work in existing branch, you need to be in that branch. This can be possible via checkout command:</blockquote><p><em>git checkout &lt;branch_name&gt;</em></p><blockquote>Creating and checkout branch command can be merged. We can create and checkout to that branch with one command:</blockquote><p>g<em>it checkout -b &lt;branch_name&gt;</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*jco2U9VtiE56Y1WIxPaC7Q.png" /></figure><h3><strong>GIT Merge</strong></h3><p>It is technique to merge two branches in which the commit history are kept as one whole unified history.</p><p>Join two or more development history together.</p><h4>Syntax:</h4><pre>git merge [-n] [--stat] [--no-commit] [--squash] [--[no-]edit]<br>	[--no-verify] [-s &lt;strategy&gt;] [-X &lt;strategy-option&gt;] [-S[&lt;keyid&gt;]]<br>	[--[no-]allow-unrelated-histories]<br>	[--[no-]rerere-autoupdate] [-m &lt;msg&gt;] [-F &lt;file&gt;]<br>	[--into-name &lt;branch&gt;] [&lt;commit&gt;…​]</pre><p>First we need to checkout to that main branch and then perform “git merge &lt;branch_name&gt;” command to merge that branch with the current branch.</p><blockquote>Let us take an example. Suppose there are two branch one is main branch and one is feature branch. Currently we are working in feature branch and wants to merge current work to the main branch. Merging can be done in following ways:</blockquote><p><em>git checkout main</em></p><p><em>git merge feature</em></p><p>These two lines of commands can be condensed into a single command.</p><p><em>git merge main feature</em></p><p>It will create a new “merge commit” in main branch keeping all the commit history intact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6ru-sB5tnJq4v94lCZARgg.png" /></figure><h4>Pros</h4><ol><li>Easy to trace the bugs and resolve it.</li><li>Commits logs are kept intact so it is easy to understand when and how each merge happens.</li></ol><h4><strong>Cons</strong></h4><ol><li>Not user-friendly log.</li></ol><h4>Types of Git Merge:</h4><p>Here we generally looks what is Fast Forward Merge and 3-way Merge.</p><h4>Fast Forward Merge (2-Way Merge)</h4><p>Fast Forward Merge can be performed when there is linear path from current branch tip to target branch.</p><p>Git Simply move source branch pointer to target branch pointer without creating any extra merge commit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*IT-WY4pXPemmH_PbbrPBeQ.png" /></figure><p>While performing fast-forward merge, C3 and F2 are compared and merged automatically if no conflict arises. Although F2 is two commit forward of C3, fast-forward merge move master branch forward.</p><h4>3-Way Merge</h4><p>It includes three snapshot of commits. Two snapshot are from Fast Forward Merge and third one is base file or common ancestor with which these two files will be compared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*64uJXNaKWRnekdB_XDe2hw.jpeg" /></figure><p>In this method, C4 and F3 branch are compared and merged automatically if no conflict arises. C3 branch is the common ancestor branch of C4 and F3.</p><h3><strong>GIT Rebase</strong></h3><p>Rebase is another way of merging two branches in git.</p><p>Reapply commits on top of another base tip</p><h4>Syntax</h4><pre>git rebase [-i | --interactive] [&lt;options&gt;] [--exec &lt;cmd&gt;]<br>	[--onto &lt;newbase&gt; | --keep-base] [&lt;upstream&gt; [&lt;branch&gt;]]</pre><p>It is safer to backup your branch before rebasing to ensure we do not loose any data.</p><p>For the same example above, rebase can be implemented as:</p><p><em>git checkout main</em></p><p><em>git checkout -b main-backup</em></p><p><em>git rebase feature</em></p><p>This command can be merged as:</p><p><em>git rebase main feature</em></p><p>This merge entire feature branch to main branch re-writing the project history by creating new commits for each commits in original branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*gofbJSTxCA_tsJf3HDlNJw.png" /></figure><h4>Pros</h4><ol><li>Logs are linear.</li><li>Easy to move through the project.</li><li>Eliminate unnecessary merge commits generated by git merge.</li></ol><h4>Cons</h4><ol><li>Commits logs are kept linear so it’s difficult to understand when and how each merge happens.</li></ol><h4>When to use git rebase ?</h4><p>It is very important to learn when not to use rebasing. Since, git rebase re-writes the history, it is not recommended to use on public branch that is shared with other people, unless you all are git expert.</p><p>This is because, if you rebase the feature branch with the main branch, then rebase moves all the commits of feature onto tip of main branch. All other developers still working in feature branch. Since, it re-writes the history, git think that your feature branch has diverged from everybody else. And this might create conflict.</p><p>In order to synchronize the feature branch, you need to run the extra merge commit and two set of commits that contains same changes (one from original branch and one from rebase branch). It is quite confusing for new users.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ff1wnYdLEpgI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Df1wnYdLEpgI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ff1wnYdLEpgI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f393f2ec69c95afb01df8c210cd83f6/href">https://medium.com/media/6f393f2ec69c95afb01df8c210cd83f6/href</a></iframe><p>References:</p><ul><li><a href="https://www.edureka.co/blog/git-rebase-vs-merge/">Git Rebase vs Git Merge - Which is better? - Edureka</a></li><li><a href="https://www.atlassian.com/git/tutorials/merging-vs-rebasing">Merging vs. Rebasing | Atlassian Git Tutorial</a></li><li><a href="https://git-scm.com/docs/git-merge">Git - git-merge Documentation</a></li><li><a href="https://git-scm.com/docs/git-rebase">Git - git-rebase Documentation</a></li><li><a href="https://medium.com/@koteswar.meesala/git-fast-forward-merge-vs-three-way-merge-8591434dd350">Git Fast-forward merge vs three-way merge</a></li><li><a href="https://www.tutorialspoint.com/what-is-a-fast-forward-merge-in-git">What is a fast-forward merge in Git?</a></li><li><a href="https://git-scm.com/docs/git-branch">Git - git-branch Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc35b39b757" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>