<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Olasunkanmi Igbasan</title>
    <description>The latest articles on Forem by Olasunkanmi Igbasan (@olatisunkanmi).</description>
    <link>https://forem.com/olatisunkanmi</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F907814%2F717d2e64-7f5f-4789-89b1-64335dbac533.jpeg</url>
      <title>Forem: Olasunkanmi Igbasan</title>
      <link>https://forem.com/olatisunkanmi</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/olatisunkanmi"/>
    <language>en</language>
    <item>
      <title>Fundamentals of Networking: Connecting the Digital World</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Thu, 28 Sep 2023 22:20:14 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/fundamentals-of-networking-connecting-the-digital-world-1ka0</link>
      <guid>https://forem.com/olatisunkanmi/fundamentals-of-networking-connecting-the-digital-world-1ka0</guid>
      <description>&lt;p&gt;In today's interconnected world, understanding the basics of networking is crucial. This article explores the fundamental principles that powers the internet and modern communication systems. From Client-Server Architecture to the OSI model to IP addressing, we'll demystify the essential concepts that underpin our digital lives. &lt;/p&gt;

&lt;h2&gt;
  
  
  Client -Server Architecture
&lt;/h2&gt;

&lt;p&gt;Client-Server Architecture is a fundamental computing model that revolutionised the networking space. It's a distributed architecture where tasks or processes are divided between two types of entities: clients and servers. &lt;/p&gt;

&lt;h3&gt;
  
  
  1. Reinventing the Networking Space:
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Before Client-Server Architecture:
&lt;/h4&gt;

&lt;p&gt;In the early days of computing, the predominant model was the centralized mainframe. All processing occurred on a single mainframe computer, and users had limited access through terminals. This model was inflexible and did not scale well.&lt;/p&gt;

&lt;h4&gt;
  
  
  Client-Server Revolution: The client-server architecture introduced the concept of distributing tasks between clients (requesters) and servers (providers). This approach allowed for greater flexibility, scalability, and better resource utilization.
&lt;/h4&gt;

&lt;h3&gt;
  
  
  2. Importance of the Reinvention:
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Scalability:
&lt;/h4&gt;

&lt;p&gt;The architecture enables scaling by adding more servers to handles increased client demand. The scalability is crucial for accommodating  growing user bases&lt;/p&gt;

&lt;h5&gt;
  
  
  Flexibility:
&lt;/h5&gt;

&lt;p&gt;It offers flexibility by allowing different types of clients (e.g., desktop applications, web browsers, mobile devices) to access server resources, making it adaptable to various platforms.&lt;/p&gt;

&lt;h4&gt;
  
  
  Security:
&lt;/h4&gt;

&lt;p&gt;Centralized servers enables better security management, as security measures can be implemented as the server to avoid unwanted access and prevent data loses&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Benefits Of the Reinvention:
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Resource Utilization:
&lt;/h4&gt;

&lt;p&gt;Server resources (e.g., databases, computation power) can be efficiently shared among multiple clients, maximizing resource utilization.&lt;/p&gt;

&lt;h4&gt;
  
  
  Reliability:
&lt;/h4&gt;

&lt;p&gt;Clients can rely on the server to provide consistent and up-to-date data, reducing data inconsistency issues.&lt;/p&gt;

&lt;h4&gt;
  
  
  Maintenance:
&lt;/h4&gt;

&lt;p&gt;Centralized server management simplifies maintenance and updates, as changes can be applied at the server without affecting clients.&lt;/p&gt;

&lt;p&gt;Indeed, while the client-server architecture is remarkable, effective communication between diverse hardware components necessitates a structured communication model and standardised protocols.&lt;br&gt;
This is precisely where the OSI(Open Systems Interconnection) Model steps in. The OSI Model provides a comprehensive framework that delineates the intricate layers of network communication, ensuring seamless interoperability and reliable data exchange between different hardware elements. It serves as the foundational structure that enables the digital world to communicate coherently and efficiently, making it an indispensable cornerstone of modern networking.&lt;/p&gt;

</description>
      <category>network</category>
      <category>client</category>
    </item>
    <item>
      <title>Fundamentals Of Network Engineering For Backends.</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Thu, 28 Sep 2023 20:53:56 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/fundamentals-of-network-engineering-for-backends-18la</link>
      <guid>https://forem.com/olatisunkanmi/fundamentals-of-network-engineering-for-backends-18la</guid>
      <description>&lt;h2&gt;
  
  
  Welcome to the Fundamentals Of Network Engineering For Backends
&lt;/h2&gt;

&lt;p&gt;Welcome to the comprehensive resource center for the &lt;strong&gt;Fundamentals Of Network Engineering For Backends&lt;/strong&gt; series. This collection of articles serves as a cornerstone for understanding the core principles and practices associated with network engineering, particularly in the context of backend systems. Whether you're a seasoned network professional or just starting your journey in this field, this series will provide you with valuable insights and knowledge.&lt;/p&gt;

&lt;h2&gt;
  
  
  Overview
&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;Fundamentals Of Network Engineering For Backends&lt;/strong&gt; series is designed to help you grasp the essential concepts and techniques necessary for effective backend design and management. If you're looking to deepen your understanding of network engineering or are pursuing a career in backend development, this series is a valuable resource.&lt;/p&gt;

&lt;h2&gt;
  
  
  Course on Udemy
&lt;/h2&gt;

&lt;p&gt;For those who prefer a structured learning experience, you can access the course through the following link: &lt;a href="https://www.udemy.com/course/fundamentals-of-networking-for-effective-backend-design/"&gt;Fundamentals of Networking for Effective Backend Design&lt;/a&gt; by &lt;a href="https://www.udemy.com/course/database-engines-crash-course/#instructor-1"&gt;Hussein Nasser&lt;/a&gt;. It offers a guided curriculum and hands-on exercises to reinforce your learning.&lt;/p&gt;

&lt;h2&gt;
  
  
  Articles in the Series
&lt;/h2&gt;

&lt;p&gt;Here are some of the topics we'll cover in this series:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://dev.to/olatisunkanmi/fundamentals-of-networking-connecting-the-digital-world-1ka0"&gt;&lt;strong&gt;Fundamentals of Networking&lt;/strong&gt;&lt;/a&gt;: Understand the fundamentals on Networking, The Why and How.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These articles will serve as a valuable reference as you progress through the series and deepen your knowledge of network engineering for backends.&lt;/p&gt;

&lt;h2&gt;
  
  
  Regular Updates
&lt;/h2&gt;

&lt;p&gt;This page will be regularly updated to ensure that you have access to the latest articles and resources related to the series. Check back often to stay up-to-date.&lt;/p&gt;

&lt;p&gt;Thank you for joining me on this educational journey. I am excited to be your guide in mastering the fundamentals of network engineering for effective backend design. Stay tuned for my upcoming articles, and don't hesitate to explore the Udemy course for a structured learning experience.&lt;/p&gt;

</description>
      <category>backend</category>
      <category>networking</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Building Robust Node.js Applications with Socket.io: Best Practices</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Thu, 16 Mar 2023 03:13:58 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/building-robust-nodejs-applications-with-socketio-best-practices-5hm5</link>
      <guid>https://forem.com/olatisunkanmi/building-robust-nodejs-applications-with-socketio-best-practices-5hm5</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Introduction&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;This article will guide you through building a basic AI chatbot using Node.js and socket.io while incorporating some of the best practices for Node.js development. With its bi-directional communication capabilities, socket.io makes it easy to build real-time applications that require continuous interaction between the server and clients. &lt;/p&gt;

&lt;p&gt;Throughout the development process, we'll follow best practices to ensure that our application is secure, scalable, and maintainable.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Setting up the Environment&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To set up the environment for building a web application using Node.js, you will need to follow a few simple steps:&lt;/p&gt;

&lt;p&gt;1 Install Node.js.&lt;br&gt;
2 Setup project directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my-chatbot/
├── node_modules/
├── public/
│   ├── css/
│   │   ├── style.css
│   ├── js/
│   │   ├── chat.js
│   │   ├── socket.io.js
│   ├── index.html
├── app/
│   ├── services/
│   |     ├── store.js
│   ├── socket/
│   |    ├── socket.js
│   |    ├── socketHelper.js
│   ├── utils/
│   |     ├── constants.js
├── config/
│   |      ├── app.js
├── app.js
├── .env
├── .gitignore
├── package-lock.json
├── package.json
└── README.md

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;3 Install the necessary dependencies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i express socket.io
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Socket.io&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Socket.io is a popular library for building real-time web applications that require bi-directional communication between the server and clients. It is built on top of the WebSockets API and provides a simple and elegant API for building real-time applications with features such as broadcasting, namespaces, and rooms. &lt;/p&gt;

&lt;p&gt;Socket.io would be a crucial part of the chatbot has it would majorly be handling the communication between our server and client.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Creating the express server&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;code&gt;app/&lt;/code&gt;: This directory contains all the backend code for our application. &lt;/p&gt;

&lt;p&gt;Within this file we would be initializing our express application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const { appConfig, Logger } = require('./config');
const app = express();

global.logger = Logger.createLogger({ label: 'E-commerce Chatbot' });

appConfig(app);

module.exports = app;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a simple configuration that exports an instance of the Express application after initializing the app configuration and logger. &lt;/p&gt;

&lt;p&gt;Firstly, we import the express framework module, then we import &lt;code&gt;appConfig, Logger&lt;/code&gt; from the config module.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;global.logger = Logger.createLogger({ label: 'E-commerce Chatbot' });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the line above, &lt;code&gt;logger&lt;/code&gt; is defined as a global variable. This allows it to be accessed from any module within the Node.js application, providing a centralized location for logging.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Configuring Express app&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const http = require('http');
const path = require('path');
const Socket = require('../app/socket/socket');

const appConfig = async (app) =&amp;gt; {
    // Set up server
    const server = http.createServer(app);

    // Set up socket
    const { SocketInstance } = Socket.createSocket(server);
    SocketInstance(server);
    // Set static files
    app.use(express.static(path.join(__dirname, '../public')));

    const PORT = 9000;
    // Listen to port
    server.listen(PORT, () =&amp;gt; {
        logger.info(`Server running on port ${PORT}`);
    });
};

module.exports = appConfig;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the appConfig function which configures the Express app.&lt;/p&gt;

&lt;p&gt;The appConfig function plays a critical role in configuring the Express app for the chatbot. It creates an HTTP server using &lt;code&gt;http.createServer(app)&lt;/code&gt;, configures the socket instance using &lt;code&gt;Socket.createSocket(server)&lt;/code&gt;, and sets up static files with &lt;code&gt;express.static()&lt;/code&gt;. The function then listens to a specified port using &lt;code&gt;server.listen()&lt;/code&gt;. These actions follow Node.js best practices, such as setting up the server to listen on a specific port and using the path module to serve static files.&lt;/p&gt;

&lt;p&gt;Additionally, it is a good practice to keep the app configuration within the scope of a function in Node.js. It helps to isolate the configuration code and prevents it from being accessed or modified outside of the function's scope, which can help improve the security of the application.&lt;/p&gt;

&lt;p&gt;By doing so, you can limit the access to important variables or configurations that are necessary for your application to work properly, making it more difficult for unauthorized access or modification. Additionally, it can also help to improve the maintainability of your code by keeping it organized and easy to read.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Configuring Socket.io&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;One of the key aspects of backend development is data-privatization and encapsulation. One of best way to implement this  is the use of a class-based approach.&lt;/p&gt;

&lt;p&gt;Within the Socket class, private methods are used to handle the socket events, such as when a user sends a message or when a user joins or leaves the chatroom. The use of private methods helps to keep the implementation details hidden from external modules, improving the overall security and maintainability of the code.&lt;/p&gt;

&lt;p&gt;Furthermore, the public methods of the Socket class are used to emit messages to the chatroom, whether it be from the user or the bot. By separating these methods, it becomes easier to manage the logic of the socket instance and improves the overall readability of the code.&lt;/p&gt;

&lt;p&gt;The constructor of the Socket class initializes the instance with the necessary properties, such as the server and the socket instance. Additionally, default values for the bot and user names are set, providing a more customizable implementation.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;initializeSocket&lt;/code&gt; method is responsible for handling the connection event and initializing the necessary event listeners for user messages, bot messages, notifications, and disconnections. By organizing these events in a separate method, the code is easier to understand and maintain.&lt;/p&gt;

&lt;p&gt;Finally, the &lt;code&gt;createSocket&lt;/code&gt; static method is used to create a new instance of the Socket class and initialize the socket instance. This method provides an easy-to-use interface for other modules to create and manage their own socket instances.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Socket config 👇🏼 *&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const socket = require('socket.io');
const constants = require('../utils/constants');

const {
    CHAT_BEGINNING,
    NEW_CONNECTION,
    BOT_NAME,
    BOT_INTRO,
    BOT_INTRO_2,
} = constants;

class Socket {
    constructor(server) {
        this.server = server;
        this.io = socket(server, { cors: { origin: '*' } });
        this.botName = BOT_NAME;
        this.userName = 'User';
    }

    /**
     * @private
     * @function _emitUserMessage
     * @param {object} socket
     * @param {object} message
     * @emits userMessage - when a user sends a message
     * @memberof Socket
     * @returns {object} message - returns user message to the chatroom
     */
    _emitUserMessage(socket, message) {
        socket.emit('userMessage', Helper(this.userName, message));
    }

    /**
     * @private
     * @function _emitBotMessage
     * @param {object} socket
     * @param {object} message
     * @emits botMessage - when the chatbot sends a message
     * @memberof Socket
     * @returns {object} message - returns bot message to the chatroom
     */
    _emitBotMessage(socket, message) {
        socket.emit('botMessage', Helper(this.botName, message));
    }

    /**
     * @private
     * @function _emitNotification
     * @param {object} socket
     * @param {object} message
     * @emits notification - when a user joins or leaves the chatroom
     * @memberof Socket
     * @returns {object} message - returns notification to the chatroom
     */
    _emitNotification(socket, message) {
        socket.emit('notification', Helper(this.botName, message));
    } 

    /**
     * @private
     * @function _broadcastNotification
     * @param {object} socket
     * @param {object} message
     * @emits notification - when a user joins or leaves the chatroom
     * @memberof Socket
     * @returns {function} _emitNotification - returns notification to the chatroom
     */
    _broadcastNotification(socket, message) {
        this._emitNotification(socket.broadcast, message);
    }

    /**
     * @private
     * @function _emitDisconnect
     * @param {object} socket
     * @emits disconnect - when a user disconnects from the chatroom
     * @memberof Socket
     * @returns {function} _broadcastNotification - returns notification to the chatroom
     */
    _emitDisconnect(socket) {
        socket.on('disconnect', (reason) =&amp;gt; {
            this._broadcastNotification(socket, reason);
        });
    }


    /**
     * @private
     * @function initializeSocket
     * @memberof Socket
     * @returns {function} _listenRegister - listens for register
     * @returns {function} _emitNotification - emits notification to the chatroom
     * @returns {function} _emitBotMessage - emits bot message to the chatroom
     * @returns {function} _listenToChatMessage - listens for chat message
     * @description Initializes socket
     * @listens for connection
     * @emits userMessage
     * @emits botMessage
     * @emits notification
     * @emits disconnect
     * @emits access
     */
    initializeSocket() {
        this.io.on('connection', (socket) =&amp;gt; {
            logger.info(NEW_CONNECTION(socket.id));


            // Emit to the new user only
            this._emitNotification(socket, CHAT_BEGINNING);

            // Emit bot message
            this._emitBotMessage(socket, BOT_INTRO);

            this._emitBotMessage(socket, BOT_INTRO_2);


        });


    }

    /**
     * @static
     * @function createSocket
     * @param {object} server- server instance
     * @memberof Socket
     * @returns {object} socketInstance - returns socket instance
     * @description Creates a socket instance
     */
    static createSocket(server) {
        const _createSocketInstance = (server) =&amp;gt; {
            const socketInstance = new Socket(server);
            return socketInstance.initializeSocket();
        };

        return {
            SocketInstance: _createSocketInstance,
        };
    }
}

module.exports = Socket;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Full Break down&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When the server starts up, the Socket constructor is called and is passed the HTTP server instance. Inside the constructor, the Socket.IO library is used to create a new socket instance and this instance is stored as a property of the Socket object. The Socket object also initializes some properties to store the names of the bot and the user, which will be used later.&lt;/p&gt;

&lt;p&gt;The Socket class has several private methods that are used to emit messages to the connected sockets. These methods include &lt;code&gt;_emitUserMessage&lt;/code&gt;, &lt;code&gt;_emitBotMessage&lt;/code&gt;, &lt;code&gt;_emitNotification&lt;/code&gt;, and &lt;code&gt;_broadcastNotification&lt;/code&gt;. These methods all take a socket object and a message object as parameters and emit the message to either the socket that called the method or to all sockets except for the socket that called the method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages of using private class methods&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Defining these methods as private methods within the class provides encapsulation and modularity to the code. By keeping these methods within the class, they are not exposed to the global scope and can only be accessed within the class itself. This prevents potential naming conflicts with other methods or variables in the global scope.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Additionally, by encapsulating these methods within the class, it makes it easier to maintain and modify the code. Since these methods are closely related to the functionality of the class, it makes sense to keep them within the class for better organization and ease of access.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Another advantage of defining these methods as private within the class is that it helps to abstract away some of the complexities of using the Socket.io library. By creating methods that handle the details of emitting specific events and messages, the rest of the code can focus on the higher-level logic of the application, without needing to worry about the specifics of Socket.io's API.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, it also helps with code reusability, as these methods can be called from within other methods in the class, rather than being duplicated across multiple functions. This helps to reduce code duplication and makes it easier to maintain the codebase.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Socket class also has a public method called &lt;code&gt;initializeSocket&lt;/code&gt;, which is called to start the socket server. Inside this method, the Socket.IO library's on method is used to listen for the connection event. When a new client connects to the socket server, a new socket object is created for that client and a logger is used to log that a new connection has been established.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;initializeSocket&lt;/code&gt; method then calls some of the private methods to send messages to the client, such as a welcome message from the bot, a notification that a new user has joined, and an introduction message from the bot. The method also listens for the disconnect event and broadcasts a notification to all connected sockets when a client disconnects from the server.&lt;/p&gt;

&lt;p&gt;Finally, the &lt;code&gt;createSocket&lt;/code&gt; static method is used to create a new instance of the Socket class and initialize the socket instance. This method provides an easy-to-use interface for other modules to create and manage their own socket instances.&lt;/p&gt;

&lt;p&gt;A class-based approach for socket.io can be particularly beneficial for backend developers, as it allows them to maintain a cleaner and more organized code structure. This is especially important for backend development, where code can become complex and difficult to manage as the application grows in size and complexity.&lt;/p&gt;

&lt;p&gt;By encapsulating socket-related logic and events within a class, backend developers can effectively separate the concerns of the application, making it easier to manage and maintain the code. This can be particularly helpful when working with large-scale applications that require multiple developers to work on different parts of the codebase.&lt;/p&gt;

&lt;p&gt;In addition to improving the organization of the code, using a class-based approach for socket.io can also help to prevent conflicts and improve modularity. This is because different parts of the application can use sockets without interfering with each other, allowing developers to work on different components of the application in parallel.&lt;/p&gt;

&lt;p&gt;Furthermore, by adopting a class-based approach, backend developers can make use of object-oriented programming concepts, such as inheritance and polymorphism, which can lead to more efficient and maintainable code. For example, by using inheritance, developers can create a base class for common socket-related logic and events, and then extend this class to add specific functionality for different parts of the application.&lt;/p&gt;

&lt;p&gt;Overall, using a class-based approach for socket.io can be a valuable tool for backend developers, helping to streamline development, improve code organization, and enhance modularity and efficiency.&lt;/p&gt;

</description>
      <category>socketio</category>
      <category>node</category>
      <category>express</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Building a simple REST api with Express: A walkthrough.</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Tue, 10 Jan 2023 22:57:48 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/how-to-build-a-simple-blog-api-with-expressjs-1gha</link>
      <guid>https://forem.com/olatisunkanmi/how-to-build-a-simple-blog-api-with-expressjs-1gha</guid>
      <description>&lt;p&gt;&lt;strong&gt;Project Description&lt;/strong&gt;&lt;br&gt;
This article is meant for developers and other technical audiences, looking to understand the implementation of a blogging app or any app really with the Express framework. Furthermore, this article is organized in a way that would cover the main areas of the project such as the technical requirements, design and implementation, challenges, deployment and testing and conclusion.&lt;/p&gt;

&lt;p&gt;This project is a web application using Node.js, Express, and MySQL, It also demonstrates a one-to-many SQL relationship.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Technology Stack&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;server side : Node.js, Express.js&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Database: MySQL&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Basic knowledge of JavaScript, and SQL.&lt;/li&gt;
&lt;li&gt;MySQL server, Node.js and npm installed on your Machine.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Setting up the server&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new directory for the project.&lt;/li&gt;
&lt;li&gt;Navigate to the terminal of the directory. &lt;/li&gt;
&lt;li&gt;Initialize a new Node.js project with the code below
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`npm init -y`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Install the following dependencies&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;nodemon - nodemon is a tool that helps develop node-based applications by automatically restarting the node application when file changes in the directory are detected.&lt;/p&gt;

&lt;p&gt;Express - Express is a free and open-source Node.js web application framework.&lt;/p&gt;

&lt;p&gt;bcrypt - bcrypt turns a simple password into fixed-length characters called a hash.&lt;/p&gt;

&lt;p&gt;body-parser - body-parser is the Node.js body parsing middleware. &lt;/p&gt;

&lt;p&gt;crypto-js - crypto-js is a module in Node. js which deals with an algorithm that performs data encryption and decryption.&lt;/p&gt;

&lt;p&gt;dotenv - The dotenv package is a great way to keep passwords, API keys, and other sensitive data out of your code.&lt;/p&gt;

&lt;p&gt;express-rate-limit - express-rate-limiting is a strategy you can use to control traffic on a network, secure backend API and limits the number of unwanted requests that a user can make within a specific time frame.&lt;/p&gt;

&lt;p&gt;helmet - helmet fills in the gap between Node.js and Express.js by securing HTTP headers that are returned by your Express apps.&lt;/p&gt;

&lt;p&gt;joi - joi is used for schema description and data validation.&lt;/p&gt;

&lt;p&gt;joi-password - joi-password is an extension of joi that helps in validating passwords.&lt;/p&gt;

&lt;p&gt;jsonwebtoken - Often called JWT, or JSON Web Token. JWTs are mainly used for authentication. After a user signs in to an application, the application then assigns JWT to that user.&lt;/p&gt;

&lt;p&gt;morgan - morgan is a Node. js and Express middleware to log(taking records of events that occur in a software) HTTP requests and errors, and simplifies the process.&lt;/p&gt;

&lt;p&gt;winston - winston is designed to be a simple and universal logging library with support for multiple transports.&lt;/p&gt;

</description>
      <category>watercooler</category>
    </item>
    <item>
      <title>The Reactor Pattern in NodeJS</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Tue, 22 Nov 2022 14:10:32 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/the-reactor-pattern-in-nodejs-49j6</link>
      <guid>https://forem.com/olatisunkanmi/the-reactor-pattern-in-nodejs-49j6</guid>
      <description>&lt;p&gt;Every programming language, framework, and library has a unique design pattern and guiding philosophy  which makes up for its peculiarity, and it is widely known that NodeJS is built with on the chrome V8 Engine. &lt;/p&gt;

&lt;p&gt;However, the Reactor pattern is the heart of Nodejs. &lt;/p&gt;

&lt;h3&gt;
  
  
  The Reactor Pattern.
&lt;/h3&gt;

&lt;p&gt;To prevent input/output operations from being blocked, the reactor pattern is used. It provides a handler connected to I/O operations for us, I/O requests are generated and sent to a demultiplexer, which handles concurrency to prevent I/O mode blocking, gathers the requests in the form of events, and queues those events accordingly to the Event Loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;I/O operations are performed generally in two ways&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Blocking I/O&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The execution thread will be blocked by the function call associated with an I/O request (user request) in conventional blocking I/O programming until the operation is finished. i.e. Synchronous programming &lt;/p&gt;

&lt;p&gt;2 &lt;strong&gt;Non I/O Blocking&lt;/strong&gt;&lt;br&gt;
The system call always returns immediately in this operating mode, without waiting for the data to be read or written. If there are no results available at the time of the call, the function will simply return a predefined constant, indicating that there is no data to return at that time. i.e. Asynchronous programming &lt;/p&gt;

&lt;h3&gt;
  
  
  Recipe for the Reactor Pattern.
&lt;/h3&gt;

&lt;p&gt;Since you have learned that the Reactor pattern is the Heart of NodeJS, then what exactly is the Reactor pattern made of?&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Resources&lt;/strong&gt;: They are shared by multiple applications for I/O operations, making executions generally slower. (this is because I/O is naturally slow )&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Synchronous Event Demultiplexer&lt;/strong&gt;: When a read or write operation carried out over one of those resources is finished, the synchronous event demultiplexer watches multiple resources and returns a new event (or set of events). The synchronous event demultiplexer is advantageous in this situation because it naturally blocks until there are new events to process.&lt;br&gt;
In conclusion, the Event De-multiplexer pushes the new events into the Event Queue when a set of I/O operations is finished.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Event Queue and Event Loop&lt;/strong&gt;:&lt;br&gt;
An event queue is a repository where events and each handles from the application are held prior to being processed by a receiving program or system, which is the Event Loop. The Event Loop iterates over the event queue&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  How does the Reactor Pattern Works?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmlxhlsi5b230npsobn4v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fmlxhlsi5b230npsobn4v.png" alt="Reactor Pattern in NodeJs" width="800" height="529"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;(a) When a new I/O request is generated by the application by submitting a request to the &lt;strong&gt;Event Demultiplexer&lt;/strong&gt;. The application also attaches an handle to the request, which will be called when the operations is complete. (b). Submitting an I/O request is to the &lt;strong&gt;Event Demultiplexer&lt;/strong&gt; asynchronous in nature, hence control is returned back to the application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When the operations for request is complete, the events with its corresponding handler is pushed into the Event Queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;At this points, the &lt;strong&gt;Event Loop&lt;/strong&gt; iterates over the items in the &lt;strong&gt;Event Queue&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The handler for the I/O request in the Event Loop is invoked for execution.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;(a)After the invocation and execution of the Handler, control is given back to the &lt;strong&gt;Event Loop&lt;/strong&gt;. (b) While the handler executes it can cause for a new I/O request be made (usually asynchronous), causing new items to be added to the Event Demultiplexer.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A new cycle begins when a new event becomes available after all of the items in the Event Queue have been processed by the Event Loop, which then blocks once more on the Event Demultiplexer.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When there are no more pending operations in the event demultiplexer and no more events to process inside the event queue, a Node.js application will exit.&lt;/p&gt;

&lt;p&gt;Sources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://www.geeksforgeeks.org/what-is-reactor-pattern-in-node-js/" rel="noopener noreferrer"&gt;https://www.geeksforgeeks.org/what-is-reactor-pattern-in-node-js/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Node Design Patterns by Mario Casciaro and Luciano Mammino&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>java</category>
    </item>
    <item>
      <title>NodeJS Module System</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Tue, 15 Nov 2022 10:30:32 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/nodejs-module-system-323m</link>
      <guid>https://forem.com/olatisunkanmi/nodejs-module-system-323m</guid>
      <description>&lt;p&gt;A JavaScript run-time called Node.js is built on top of the Chrome v8 engine. In essence, the Node.js platform offers an environment for JavaScript code execution that is separate from the typical web browser (it's crucial to remember that Node.js was developed for the creation of network applications utilizing JavaScript).&lt;/p&gt;

&lt;p&gt;The building blocks for building complex applications are modules in Node.&lt;br&gt;
Using the module building system, you can segregate the codebase into manageable chunks that can be independently created and tested. By keeping all the functions and variables that are not explicitly designated to be exported private, modules are also the primary mechanism for enforcing information shielding.&lt;/p&gt;
&lt;h2&gt;
  
  
  Modules are of three types:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Core Modules&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Local Modules &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Third Party Modules&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Core Modules&lt;/strong&gt;: Node.js comes with a number of inbuilt modules that are installed as part of the infrastructure. The require function can be used to import these modules into the application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const module = require('module-name')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You need only refer to the module name when loading a core module or a module from the node modules subdirectory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Local Modules&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;A separate JavaScript file must be used to create the local module. We can declare a JavaScript object with various properties and functions in a separate file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Hello = {

    sayHello : function() {
        console.log("Hello  user");
  },

  curTime : new Date().toLocaleDateString(),


}

module.exports = Hello

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using the above module;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const localModule = require("./Hello.js");
localModule.sayHello();
console.log(localModule.currTime);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Third Party Modules :&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Third party modules are often external modules installed through the Node Package Manager.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install express

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;👆🏼 How to install third party modules.&lt;br&gt;
👇🏼 How to import third party modules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How loading a module works
&lt;/h2&gt;

&lt;p&gt;When loading a module, node first checks to see whether the module identifier (the string passed into the require function call) begins with "./," "/," or "../," and if it doesn't, node checks to see whether the identifier matches any of its core modules (http, path, fs, etc.). If a match is found, node loads the recognized core module; or else, node knows to browse the node modules folder.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Need for modules.
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The ability to divide the codebase into several files&lt;br&gt;
This keeps the code more ordered, makes it simpler to understand, and helps maintain the independence of different functionality.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enabling code reuse across various projects: It's possible for a module to implement a generic feature that can be helpful for various projects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Encapsulation (information protection): Most module systems allow for the selective concealment of the private portion of the code while exposing the public interface, such as functions, classes, or objects, which are intended for usage by the module's consumers.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In conclusion, depending on the global scope is a very risky effort, especially as your application evolves. As a result, when a modification is required, just the module where the function is written is addressed.&lt;br&gt;
When a change is required or when your application changes, the Module system prevents a complete breakdown.&lt;/p&gt;

&lt;p&gt;The well-known DON'T REPEAT YOURSELF software development philosophy is taken to a whole new level with the Module system.&lt;/p&gt;

</description>
      <category>npm</category>
      <category>node</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Simple search vs Binary search Algorithms.</title>
      <dc:creator>Olasunkanmi Igbasan</dc:creator>
      <pubDate>Sun, 14 Aug 2022 13:28:00 +0000</pubDate>
      <link>https://forem.com/olatisunkanmi/simple-search-vs-binary-search-algorithms-4jm3</link>
      <guid>https://forem.com/olatisunkanmi/simple-search-vs-binary-search-algorithms-4jm3</guid>
      <description>&lt;p&gt;Hello there !&lt;br&gt;
Welcome and stay with me as I explain Big O Notation to you in the simplest words ever!&lt;/p&gt;

&lt;p&gt;"Total time needed for an algorithm to run," is the simplest definition of Big O Notation, but &lt;strong&gt;why does it matter to you as a developer&lt;/strong&gt;? &lt;/p&gt;

&lt;p&gt;To answer that, below is a simple search Algorithm that finds any given item in an array; if the given item is not in the array, our algorithm returns null.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Simple Search Algorithm.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fst12i2amaa3f7oewaos3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fst12i2amaa3f7oewaos3.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;           Fig 1.0 (For-loop search algorithm )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The above is a simple JavaScript For-loop that iterates over each item in the array, checks if the current iteration equals our input ('item' ), and if the item is not in the array, it returns "null."&lt;/p&gt;

&lt;p&gt;Below (Fig 2.0 ) is a while loop that does the same as the above For-loop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Binary Search Algorithm.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F08n5jws0lny8ysssmzlw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F08n5jws0lny8ysssmzlw.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;      Fig 2.0 (while loop search algorithm )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Although,  the above functions do precisely the same thing. But what happens when the number of items in our array increases &lt;strong&gt;&lt;em&gt;exponentially&lt;/em&gt;&lt;/strong&gt;? &lt;/p&gt;

&lt;p&gt;How efficient will both our algorithms still be ? &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A step-by-step break-down of the Binary Search Algorithm&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;We compare 'item' with the middle index of the array.&lt;/li&gt;
&lt;li&gt;if 'item' matches the mid index, we return the mid element.&lt;/li&gt;
&lt;li&gt;else if 'item' is greater than the middle element, length of the array is reassigned to the middle  ( element - 1 ).&lt;/li&gt;
&lt;li&gt; else if 'item' is lesser than the middle element, beginning of the array is reassigned to the middle  ( element + 1 ).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;With this method we eliminate half of the array in the first comparison.&lt;/p&gt;

&lt;p&gt;For better understanding,&lt;br&gt;
If the length of the array increases to 1millon.&lt;br&gt;
With the first function (Fig 1.0), we will perform 1 million iterations (&lt;em&gt;worst case&lt;/em&gt;) to find our item. However, we will perform at most 10 iterations (&lt;em&gt;worst case&lt;/em&gt;) with the second function. &lt;/p&gt;

&lt;p&gt;The Big O notation of our functions.&lt;/p&gt;

&lt;p&gt;Simple search algorithm (Fig 1.0) -   O(n)   // Bad guy&lt;br&gt;
Binary search  algorithm (Fig 2.0)  -  O(log n)    // Good guy.&lt;/p&gt;

&lt;p&gt;Stay with me on this blog while I explain Algorithms and Data Structures as succinctly as possible. &lt;/p&gt;

&lt;p&gt;Link to Code and remember  to give it a star.&lt;br&gt;
&lt;a href="https://github.com/Olatisunkanmi/Data-Structures-and-Algorithms-/tree/main/5%20Algorithms/Binary%20Search" rel="noopener noreferrer"&gt;https://github.com/Olatisunkanmi/Data-Structures-and-Algorithms-/tree/main/5%20Algorithms/Binary%20Search&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>algorithms</category>
      <category>bigonotatio</category>
    </item>
  </channel>
</rss>
