<?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 Debasis Das on Medium]]></title>
        <description><![CDATA[Stories by Debasis Das on Medium]]></description>
        <link>https://medium.com/@debasisdasnospdii?source=rss-397223dd041b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vKw65bwnAfaunb2d</url>
            <title>Stories by Debasis Das on Medium</title>
            <link>https://medium.com/@debasisdasnospdii?source=rss-397223dd041b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:42:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debasisdasnospdii/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[Idempotency in Scalable Distributed Architectures — Example]]></title>
            <link>https://medium.com/@debasisdasnospdii/idempotency-in-scalable-distributed-architectures-example-e23a12c70048?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23a12c70048</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[idempotency]]></category>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 06:40:57 GMT</pubDate>
            <atom:updated>2023-09-28T06:40:57.504Z</atom:updated>
            <content:encoded><![CDATA[<h3>Idempotency in Scalable Distributed Architectures — Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*kLUTL3u7Dy0QylqYCoC9hQ.gif" /></figure><h4>1. What is Idempotence :</h4><p>Idempotence is a property that ensures that an operation or action can be performed multiple times without changing the result beyond the initial application. In simpler terms, if the same request is sent to a microservice endpoint multiple times, the result should remain consistent, as if the request was only made once.</p><h4><strong>2. Application of Idempotency :</strong></h4><ol><li><strong>Order Processing (Rest API) :</strong> For instance, in an e-commerce application, there can be order creation requests (Rest API) that could potentially fail but can be retried automatically. However, this could often lead to cases where your orders can be duplicated in the system. By adopting idempotency, you can guarantee that the order is created only once, regardless of when the request is retried.</li></ol><ul><li>In the REST API concept, GET, PUT, UPDATE, DELETE, and OPTIONS are idempotent operation since they don’t change anything on the server and returns the same response every time.</li><li>While POST is not idempotent since it creates a new resource on the server/database every time we execute it.</li><li><strong>Example — Problem :</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*1pDK9-idRKx4GwL41lv8WQ.png" /></figure><p><strong>. Example — Solution using idempotency :</strong></p><p>Use idempotency table to store all idempotency key with status. If idempotency key is not available in db, then process request. Otherwise simple return to user duplicate request (status : “Received”)or request already processed (Status :“Processed”)response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*WEhw6MAWinykvscYpJeTSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*gLRY8Fg--RVH5ZxgCI8VHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*y_m_YPzJ7ioEQXnkWsy-vw.png" /></figure><p><strong>2. Inventory Management (Distributed system/ Distributed transaction) : </strong>When updating inventory levels in microservice after a purchase, idempotency ensures that stock quantities are adjusted correctly regardless of network hiccups or retries, preventing inaccuracies in inventory levels.</p><p>Use different different idempotency table to store all idempotency key with status for each microservice. If idempotency key is not available in db, then process request. Otherwise simple return to user duplicate request (status : “Received”) or request already processed (Status :“Processed”)response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_2CJ7VxuJpio57hnO931Q.gif" /></figure><h4>3. Advantages of idempotency in scalable distributed system :</h4><ol><li>In microservices, where data flows across multiple services, idempotency ensures that updates are uniform across the board. This maintains <strong>data integrity</strong> and coherence</li><li>Network disruptions or service failures are common in distributed systems. Idempotent operations allow for reliable <strong>retries </strong>without concern for negative outcomes.</li><li>The<strong> scalability and fault tolerance</strong> of microservices hinge on idempotent operations. They permit horizontal scaling and retries without jeopardizing system stability.</li><li>Non-idempotent operations risk unintentional consequences when repeated. Idempotency guarantees that executing the <strong>same operation multiple times</strong> doesn’t introduce unexpected side effects.</li></ol><p><strong>Summary : </strong>That’s it! In this post, we understand about idempotency use in post rest API and in scalable distributed system.</p><p><strong>Thank you</strong> for reading my blogs ……..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23a12c70048" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro service: API gateway]]></title>
            <link>https://medium.com/@debasisdasnospdii/micro-service-api-gateway-a4770e02fcf3?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4770e02fcf3</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[api-gateway]]></category>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 14:38:19 GMT</pubDate>
            <atom:updated>2023-09-12T15:25:46.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Micro service: API gateway — Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ivoUhES1PyiBzxVtQ2W8Wg.gif" /></figure><h4><strong>What is micro services :</strong></h4><blockquote>A microservices architecture is one type of <em>distributed system</em>, since it decomposes an application into separate <strong>components or services</strong>.</blockquote><blockquote>For example, a microservice architecture may have services that correspond to business features (<strong>payments, price, inventory</strong> etc.) where each corresponding component handles the business logic for that responsibility.</blockquote><h4>What is API gateway :</h4><p>API gateways are middleware or software components that sit <strong>between client applications and back-end services. </strong>API gateways provide a more straightforward, secure, and reliable API interface for complex subsystems by working as a <strong>proxy between the API system and its consumers.</strong></p><p><strong><em>The primary function of an API gateway is to route and transmit client requests to the appropriate back-end services.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*mgnuPJx2kxfzGxiBFFWBkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*GWqmnLBDXqsfm-XHS4Yx3g.png" /></figure><p>They also provide other capabilities, such as <strong>security, rate limit, caching, request/response transformation, monetization, and load balancing</strong>.</p><h4>Why need API gateway :</h4><ol><li><strong>Security</strong> — When you need to make sure your APIs are protecting the sensitive data in a reliable manner</li><li><strong>Scalability</strong> — When you need to power up your API’s performance by implementing performance features, such as, <strong>traffic management, caching data</strong>, etc.</li><li><strong>Interoperability</strong> — When you are spending too much time with the mediation and data transformation needs for incoming and outgoing requests to support different data formats and requirements</li><li><strong>Monitoring and logging</strong> — When you need a central cockpit for aggregated logging, auditing, and monitoring your APIs to maintain them all</li><li><strong>Monetization</strong> — When you need an easy way to package, price, promote, and monitor your APIs throughout their lifecycle</li></ol><h4>API gateway vs API proxy :</h4><p>Like an API gateway, an API proxy acts as an interface between API consumers and back-end services. An API proxy exposes URL endpoints for existing APIs so users can access them via these proxy endpoints. Requests coming through these proxy URLs are routed to the configured API endpoint, which processes the requests and sends them to the proxy, then returning them to the caller.</p><p>However, API proxies are limited in their capabilities in comparison to API gateways. API gateways provide much richer functionality and customization than API proxies, such as <strong>rate limiting, API monitoring, caching, end-to-end security, load balancing, authentication</strong>, <strong>authorization </strong>— among others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*GLgoJIf0ApVGk9EN8neW9g.png" /></figure><h4>API Gateway — Kong :</h4><p>Kong Gateway is a lightweight, fast, and flexible API gateway. An API gateway <strong>is a reverse proxy that lets you manage, configure, and route requests to your APIs</strong>.</p><p>Kong Gateway runs in front of any RESTful API and can be extended through modules and plugins.</p><blockquote>3 Steps to Getting Started — Service, Route, Plugins</blockquote><ol><li><strong>Add a service :</strong> This is the ID that kong gateway uses to refer to the upstream APIs and microservice it manages.</li><li><strong>Add route to the service :</strong> Routes specify how (and if) requests are sent to their Services after they reach the API gateway. A single Service can have many Routes</li><li><strong>Add plugins:</strong> which provide a modular system for modifying and controlling Kong’s capabilities. Plugins provide a wide array of functionality, including <strong>access control, caching, rate limiting, logging</strong> and more</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*RNtRrL2VF-jPVJZQbE-n9A.png" /></figure><p><strong>Summary : </strong>That’s it! In this post, we understand about micro service API gateway and handling microservices requests and basic about kong.</p><p><strong>Thank you</strong> for reading my blogs ……..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4770e02fcf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Logging for Microservices — Practical]]></title>
            <link>https://blog.stackademic.com/distributed-logging-for-microservices-practical-5d308109b7c5?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d308109b7c5</guid>
            <category><![CDATA[distributed-log]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 13:46:34 GMT</pubDate>
            <atom:updated>2023-09-13T01:02:16.753Z</atom:updated>
            <content:encoded><![CDATA[<h3>Distributed Logging for Microservices — Practical</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*ue9PI7OUZxHYbRzKWnSwOQ.gif" /></figure><h4><strong>1. What is micro service :</strong></h4><p>A microservices architecture is one type of <em>distributed system</em>, since it decomposes an application into separate <strong>components or services</strong>.</p><p>For example, a microservice architecture may have services that correspond to business features (<strong>payments, price, inventory</strong> etc.) where each corresponding component handles the business logic for that responsibility.</p><h4><strong>2. What is distributed logging :</strong></h4><p>Each microservice emits its <strong>own logs</strong> and often stores them in different locations. With distributed systems, logging is the easy part.</p><p>If you need to implement logging for a distributed system, the first step is to select a <strong>single location to store the logs.</strong> Dozens of solutions are available and <strong>azure application insights</strong> is one of them.</p><h4>3 . What is distributed tracing :</h4><p>Distributed tracing is a method used to profile or monitor the result of a request that is executed across a distributed system. Monitoring a distributed system can be challenging because each individual node has its own separate stream of logs and metrics. To get an accurate view of a distributed system, these separate node metrics need to be aggregated into a holistic view.</p><h4>4. The need for a Centralized Logging Service:</h4><p>A single centralized logging service that aggregates logs from all the services should be a preferred solution in a microservices architecture.</p><p>When one or more services fail, we need to know which service experienced an issue and why. It’s also difficult to decipher the complete request flow in microservices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*-1dZwsZ_1yE8LKgo9R74dg.png" /></figure><h4>5. microservices logging best practices:</h4><ol><li><strong>unique correlation ID per request: I</strong>magine a situation where a large number of microservices produce millions of log entries every hour. For each request sent to a server, a correlation request ID would be inserted.</li><li><strong>Structured logging:</strong> Consider using a structured logging format such as <strong>JSON.</strong> This will make it easier to search and analyze your logs and will also make it easier to send your logs to a centralized logging solution.</li><li><strong>Add contextual data in your logs: </strong>Make sure to include enough context in your logs. This might include information such as the request URL, request parameters, and user ID.</li><li><strong>Use Log Levels:</strong> Use different log levels (such as<strong> error, warning, and info</strong>) to indicate the severity of a log message. This will make it easier to filter your logs and understand the most important issues.</li><li><strong>Provide informative application logs: </strong>The log should have all the information required to understand the error when it occurs. We can troubleshoot more effectively and more quickly the more information that is accessible from the microservices logs. Logs need to contain the following details:</li></ol><p>. Service name</p><ul><li>UserID</li><li>Hostname</li><li><strong>Correlation ID</strong> (can be in the form of traceid)</li><li>Time Stamp</li><li>Overall duration (at the end of a request)</li><li>Method name</li><li>Request Method</li><li>Request URI</li></ul><h4>6. Implement distributed logging using microsoft azure application insights :</h4><ol><li><strong>Create azure application insight resources : </strong>Login to azure portal and setup azure application insight resources.</li><li><strong>Copy connection string : </strong>Copy your resource’s connection string from your new resource. Application Insights uses the connection string to map data to your Azure resource. Before the SDK can use your connection string, you must specify the connection string in an environment variable or in your code.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOcIV3icxrsq3XpEbkWz9g.png" /></figure><p><strong>3. Install packages :</strong> Install packages applicationinsights, winston</p><p><strong>4. Common logging code :</strong></p><pre>import { format } from &quot;winston&quot;;// import<br>const appInsights = require(&quot;applicationinsights&quot;);// import<br>appInsights.setup(APPINSIGHTS_INSTRUMENTATIONKEY).start();// connection string<br>import * as winston  from &quot;winston&quot;;// import<br><br>const { AzureApplicationInsightsLogger } = require(&quot;winston-azure-application-insights&quot;);<br><br>//levels: winston.config.syslog.levels,<br>    export function initLogger(): winston.Logger {<br>        const logger = winston.createLogger({<br>            levels: winston.config.syslog.levels,<br>            transports: [<br>                new winston.transports.Console({ level: &#39;info&#39; }),<br>                new winston.transports.File({ filename: &#39;error/logger_error.log&#39; , level: &#39;error&#39; })<br>            ],<br>            format: format.combine(<br>                format.colorize(),<br>                format.simple(),<br>                format.align(),<br>            )<br>        });<br>        const validWinstonLogLevels = [&quot;emerg&quot;, &quot;alert&quot;, &quot;crit&quot;, &quot;error&quot;, &quot;warning&quot;, &quot;warn&quot;, &quot;notice&quot;, &quot;info&quot;, &quot;verbose&quot;, &quot;debug&quot;, &quot;silly&quot;];<br>        logger.add(new AzureApplicationInsightsLogger({<br>            client: appInsights.defaultClient,<br>            level : winston.config.syslog.levels,<br>            sendErrorsAsExceptions: true<br>        }));<br>        return logger;<br>    }</pre><p><strong>4. Import above code in every microservice for logging :</strong></p><pre>const logger = initLogger();<br><br>        logger.info({<br>          message: &lt;message with Correlation ID&gt;,<br>          info: {<br>            UserID: &lt;&gt;,<br>            Servicename: &lt;&gt;,<br>            Hostname: &lt;&gt;, <br>            UserID: &lt;&gt;,<br>            CorrelationID: &lt;&gt;,<br>            TimeStamp: &lt;&gt;,<br>            Methodname: &lt;&gt;<br>          }<br>        })</pre><p>5. Distributed logging and tracing in azure application insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_D2jjPqKOi7RwtycmvnzJg.png" /></figure><p><strong>Summary : </strong>That’s it! In this post, we understand about <strong>microservice</strong>, <strong>distributed logging</strong>, <strong>tracing</strong>,<strong> implemetation of distributed logging using Azure application insight</strong>.</p><p><strong>Thank you</strong> for reading my blogs!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d308109b7c5" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/distributed-logging-for-microservices-practical-5d308109b7c5">Distributed Logging for Microservices — Practical</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real time message/notification using azure web pubsub — Example]]></title>
            <link>https://blog.stackademic.com/real-time-message-notification-using-azure-web-pubsub-example-1a80bc64c185?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a80bc64c185</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 06:36:56 GMT</pubDate>
            <atom:updated>2023-09-13T01:02:31.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-time message/notification using Azure web pubsub — Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*iEaXrcdag21h8xV7M7ElQQ.gif" /></figure><blockquote><strong>What is Azure Web PubSub :</strong> The Azure Web PubSub Service helps you build<strong> real-time messaging</strong> web applications using <strong>WebSockets</strong> and the <strong>publish-subscribe pattern</strong> easily. This real-time functionality allows publishing content updates between server and connected clients. T<strong>he clients do not need to poll the latest updates, or submit new HTTP requests for updates.</strong></blockquote><blockquote><strong>Application of azure Web PubSub service:<br>1. </strong>Azure Web PubSub service can be used in any application type that <strong>requires real-time content updates.</strong><br><strong>2.</strong> Real time <strong>notification/messages to one user or group of user.</strong><br><strong>3. </strong>Real-time broadcasting, targeted ads, location on map</blockquote><blockquote><strong>Benefits using azure web pubsub service :<br><em>1.</em> </strong>The service allows multiple instances to work together and scale to <strong>millions of client</strong> connections.<br><strong>2.</strong> it also supports multiple global regions for <strong>sharding</strong>, <strong>high availability</strong>, or <strong>disaster recovery</strong> purposes<br><strong>3.</strong> The server sends messages to a particular client, all clients<br><strong>4 .</strong> The clients send messages to server.</blockquote><h4>How to use the Azure Web PubSub service :</h4><ol><li><strong>Azure Web Pub Sub Service : </strong><br> * Login to <a href="https://azure.microsoft.com/">https://azure.microsoft.com/</a> and create azure Web Pub Sub Service.<br>* Get PUBSUB_CONNECTION_STRING and PUBSUB_HUBNAME</li><li><strong>Backend (Nest.js): <br> * Install package : </strong>npm i <a href="https://www.npmjs.com/package/@azure/web-pubsub">@azure/web-pubsub</a><br>* Make connection with azure pub sub server<br>* Send messages/events/notifications to azure pubsub</li></ol><pre>import { WebPubSubServiceClient } from &#39;@azure/web-pubsub&#39;; //import package<br>export class PubSubService {<br>    pubsubclient: WebPubSubServiceClient;<br>    constructor() {<br>        this.setConfiguration();<br>    }<br><br>    private setConfiguration() {  //configure with azure pub sub service<br>        if(PUBSUB_CONNECTION_STRING &amp;&amp; PUBSUB_HUBNAME){<br>            this.pubsubclient = new WebPubSubServiceClient(Config.PUBSUB_CONNECTION_STRING, Config.PUBSUB_HUBNAME);<br>        }<br>    }<br><br>   // publish message/event/notification to one or group of user<br>    public async publishMessage(notyificationMessage: RealTimeMessageModel) {<br>        const result = new Promise&lt;string&gt;((resolve, reject) =&gt; {<br>            this.pubsubclient.sendToUser(<br>                notyificationMessage?.companyId, //one or multiple user id<br>                notyificationMessage  //message/notification<br>            );<br>            resolve(&quot;message sent&quot;);<br>        });        <br>        return result;<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1zWlryD0CDKLBSkZgPlCw.png" /></figure><p><strong>3. Frontend (React.js):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*drUn2RP1nmulS5CW0o0udA.png" /></figure><ul><li>Install package — npm i <a href="https://www.npmjs.com/package/websocket">websocket</a></li><li>Send API request to backend to get token and handle messages:</li></ul><pre>const W3CWebSocket = require(&#39;websocket&#39;).w3cwebsocket; //import package<br>    <br>// send api request to backend to get access token<br>    axios.get(sharedUrl+ &#39;/event/token-url&#39;, {<br>      withCredentials: true,<br>      params: {<br>        selectedaccount: &quot;user id&quot; // user id<br>      }<br>    }).then((response) =&gt; {<br>      if (response.data) {<br>        if(!unsubscribed){<br>          handleAccessToken(response.data); // handle access token<br>        }<br>      }<br>    }).catch((error)=&gt; {<br>    });<br>  }<br><br><br>// Handle access token<br>  function handleAccessToken(tokenUrl) {<br>    const ws = new W3CWebSocket(tokenUrl);<br>    ws.onerror = (e =&gt; {<br>      ws.close();<br>    });<br><br>    ws.onopen = (() =&gt; {<br>      // console.log(&quot;wwsocket connection opened&quot;);<br>    });<br><br>    ws.onmessage = (e =&gt; {<br>    // Handle messages<br>    });<br><br>    //retry after close connection<br>    ws.onclose = (e =&gt; {<br>      return;<br>    });<br>  }</pre><ul><li>Backend generate token and send it to frontend :</li></ul><pre>import { WebPubSubServiceClient } from &#39;@azure/web-pubsub&#39;;<br><br> const serviceClient = new WebPubSubServiceClient(PUBSUB_CONNECTION_STRING,<br>PUBSUB_HUBNAME);<br> const token = await serviceClient.getClientAccessToken({<br>     userId: accountId, expirationTimeInMinutes:5<br>    });<br>    <br> return token.url;</pre><p><strong>Summary : </strong>That’s it! In this post, we saw how to use the azure pubsub to publish message from backend and consume messages on frontend.</p><p><strong>Thank you</strong> for reading my blogs!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a80bc64c185" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/real-time-message-notification-using-azure-web-pubsub-example-1a80bc64c185">Real time message/notification using azure web pubsub — Example</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Onion Architecture : An Example Folder Structure — Nest.js]]></title>
            <link>https://medium.com/@debasisdasnospdii/onion-architecture-an-example-folder-structure-nest-js-480ea9c6ec3a?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/480ea9c6ec3a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[onionarchitecture]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 15:08:33 GMT</pubDate>
            <atom:updated>2023-08-31T15:08:33.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Onion Architecture : An Example Folder Structure — Nest.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*xt9Jj3OVCY_J0jNeGJ_Kiw.png" /></figure><p><strong>In this article, we will delve into the key concepts of Onion Architecture and provide an example folder structure that illustrates its implementation.</strong></p><p><strong>A. What is onion architecture : </strong>As shown in the above picture, <strong>onion architecture</strong> is a way to structure the code by dividing it into domain-driven design layers. each layer can only access the layer below it throw its interfaces, and then using the dependency inversion principle each interface will be replaced with its class.</p><p><strong>B. Key tenets of Onion Architecture:</strong></p><ol><li>The application is built around an independent object model</li><li>Inner layers define interfaces. Outer layers implement interfaces</li><li>Direction of coupling is toward the center</li><li>All application core code can be compiled and run separate from infrastructure</li></ol><p><strong>C. Layers of the Onion:</strong></p><ul><li><strong>Domain Layer ( Domain model and Domain service)</strong>: Contains the core business logic, entities, and business rules of the application.</li><li><strong>Application Layer:</strong> Implements use cases and coordinates the flow of data between the domain and infrastructure layers.</li><li><strong>Infrastructure Layer:</strong> Handles external concerns such as databases, file systems, or external services.</li><li><strong>API Layer: </strong>API is an interface that use to exchange information securely between frontend and backed server.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*uYepHgvnS58MBccKgfK1SA.png" /></figure><p><strong>D. Example Folder Structure : </strong>Lets demonstrate a common folder structure based on Onion Architecture —</p><ul><li><strong>Domain Layer — Domain model : </strong>Contains the core entities. src/domain/entities</li></ul><pre>export class EmployeeEN {<br>    FirstName: string;<br>    SurName: string;<br>    Gender: string;<br>    Designation: string;<br>    Email: string;<br>    Address: string;<br>    Balance: number;<br>  }</pre><ul><li><strong>Domain Layer — Domain service : </strong>Contains the core business logic and business rules of the application. <em>src/domain/domain_services</em></li></ul><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { EmployeeEN } from &#39;src/domain&#39;;<br>import { CreateAuthorDto } from &#39;src/domain/Dto/employee.dto&#39;;<br><br>@Injectable()<br>export class EmployeeFactoryService {<br>  getBalance (employee : EmployeeEN): number {<br>    return employee?.Balance;<br>  }<br><br>  canWithdrawBalance (employee : EmployeeEN, amount : number): boolean {<br>    return (employee.Balance - amount) &gt; 0;<br>  }<br><br>  withdrawBalance (employee : EmployeeEN, amount : number): EmployeeEN {<br>     employee.Balance = employee?.Balance - amount;<br>     return employee;<br>  }<br>}</pre><ul><li><strong>Application Layer/ Usecase Layer:</strong> Implements use cases and coordinates the flow of data between the domain and infrastructure layers. <em>src/useCases/</em></li></ul><pre>import { Injectable } from &quot;@nestjs/common&quot;;<br>import { EmployeeServiceDB } from &#39;../../infastructure/data-services/mongoDB/employee.service&#39;;<br>import { IDataServices } from &quot;src/domain/abstracts/data-services.abstract&quot;;<br>import { CreateAuthorDto } from &quot;src/domain/Dto/employee.dto&quot;;<br>import { EmployeeFactoryService } from &quot;../../domain/domain_service/employee-factory&quot;;<br>import { error } from &quot;console&quot;;<br><br><br>@Injectable()<br>export class EmployeeUseCases {<br>  constructor(<br>    private dataServices: IDataServices,<br>    private employeeFactoryService: EmployeeFactoryService<br>  ) { }<br><br>  getAllEmployee(): Promise&lt;any&gt; {<br>    return this.dataServices.empoyees.getAll();<br>  }<br><br>  createEmployee(employeeDto: CreateAuthorDto): Promise&lt;any&gt; {<br>    const employee = this.employeeFactoryService.createnewEmployee(employeeDto);<br>    return this.dataServices.empoyees.create(employee);<br>  }<br><br> async withdrawBalance (email: string, balance: number) : Promise&lt;number&gt; {<br>    let employee = await this.dataServices.empoyees.get(email);<br>    console.log(&quot;Employeee :::: &quot;, employee);<br>    if(!this.employeeFactoryService.canWithdrawBalance(employee, balance))<br>       throw error(&quot;Less Balance&quot;);<br>    <br>    employee = this.employeeFactoryService.withdrawBalance(employee, balance);<br><br>    console.log(&quot;employee   ::: &quot;, employee);<br><br>    const updatedEmployee = await this.dataServices.empoyees.update(email, employee);<br><br>    console.log(&quot;updatedEmployee :::: &quot;, updatedEmployee);<br><br>    return updatedEmployee?.balance;<br>  }<br>}</pre><ul><li><strong>Infrastructure Layer:</strong> Handles external concerns such as databases, file systems, or external services. <em>src/infrastrucure/dataservices/mongodb, src/infrastrucure/dataservices/queueService</em></li></ul><pre>import {<br>  Injectable<br>} from &#39;@nestjs/common&#39;;<br><br>import {<br>  Model<br>} from &#39;mongoose&#39;;<br><br>import { IGenericRepository } from &#39;src/domain/abstracts&#39;;<br><br>@Injectable()<br>export class EmployeeServiceDB&lt;T&gt; implements IGenericRepository&lt;T&gt; {<br>  private _repository: Model&lt;T&gt;;<br>  private _populateOnFind: string[];<br><br>  constructor(repository: Model&lt;T&gt;, populateOnFind: string[] = []) {<br>    this._repository = repository;<br>    this._populateOnFind = populateOnFind;<br>  }<br><br>  getAll(): Promise&lt;T[]&gt; {<br>    return this._repository.find().populate(this._populateOnFind).exec();<br>  }<br><br>  create(item: T): Promise&lt;T&gt; {<br>    return this._repository.create(item);<br>  }<br><br>  async get(email: string) {<br>    return await this._repository.findOne({Email : email}).populate(this._populateOnFind).exec();<br>  }<br><br>  update(email: string, item: T) {<br>    return this._repository.findOneAndUpdate({Email : email}, item);<br>  }<br>}</pre><ul><li><strong>API Layer: </strong>API is an interface that use to exchange information securely between frontend and backed server. <em>src/controller</em></li></ul><pre>import {<br>  Controller,<br>  Get,<br>  Post,<br>  Body,<br>  Param,<br>  Delete,<br>  Put<br>} from &#39;@nestjs/common&#39;;<br>import { CreateAuthorDto } from &#39;src/domain/Dto/employee.dto&#39;;<br>import { UpdateEmployeeDto } from &#39;src/domain/Dto/employee.update.dto&#39;;<br>import { EmployeeUseCases } from &#39;src/useCases/employee/employee.usecase&#39;;<br><br><br>@Controller(&#39;api/employee&#39;)<br>export class EmployeeController {<br>  constructor(private readonly employeeUseCases: EmployeeUseCases) { }<br><br>  @Get()<br>  findAll() {<br>    return this.employeeUseCases.getAllEmployee();<br>  }<br><br>  @Post()<br>  createAuthor(@Body() employeeDto: CreateAuthorDto) {<br>    return this.employeeUseCases.createEmployee(employeeDto);<br>  }<br><br>  @Put(&#39;:id&#39;)<br>  updateEmployee(<br>    @Param(&#39;id&#39;) email: string,<br>    @Body() updateEmployeeDto: UpdateEmployeeDto,<br>  ) {<br>    try{<br>    return this.employeeUseCases.withdrawBalance(email, updateEmployeeDto?.Balance);<br>    }catch(err){<br>      throw err;<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*5TWgwm0DZ-KNLMA6oZ7NCw.png" /></figure><p><strong>E. Benefits of this architecture pattern:</strong></p><ul><li><strong>Independent of Frameworks:</strong> The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.</li><li><strong>Testable:</strong> The business rules can be tested without the UI, Database, Web Server, or any other external element.</li><li><strong>Independent of UI:</strong> The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.</li><li><strong>Independent of Database:</strong> You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.</li><li><strong>Independent of any external agency:</strong> In fact your business rules simply don’t know anything at all about the outside world.</li></ul><h3>Conclusion:</h3><p>Problems Onion Architecture solves</p><ul><li>A more structured, layered layout of the code makes code navigation easier and makes the relationship between different parts of the codebase more visible at first glance</li><li>Loose coupling between the domain and the infrastructure</li><li>Coupling is towards the centre of The Onion — expressed by the relationship between the layers</li><li>(Usually) No coupling between the domain and the infrastructure concerns of the application</li><li>Build tool support in enforcing layers</li></ul><p>Problems Onion Architecture creates</p><ul><li>Additional learning curve for new developers, and those used to other architecture styles</li><li>Increased overall complexity of the codebase — especially with the flavour utilising the modularizing capabilities of build tools such as Gradle or Maven</li><li>Not everyone likes the smell of it</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3KN97viiv_UPSrMn34QWMw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=480ea9c6ec3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles explain]]></title>
            <link>https://medium.com/@debasisdasnospdii/understanding-solid-principles-explain-56da1ca01486?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/56da1ca01486</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 14:46:27 GMT</pubDate>
            <atom:updated>2023-08-15T14:54:33.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*R0VLumkZaf2uSiDZ_kDDvw.gif" /></figure><p><em>SOLID</em> is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin</p><p>These principles establish practices that lend to developing software with considerations for<strong> robust, testable, maintaining</strong> and <strong>extending </strong>as the project grows.</p><h3>A. <a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#single-responsibility-principle">Single-Responsibility Principle</a>:</h3><p>A class should have one and only one reason to change, meaning that a class should have only one job.</p><pre>//Its does not follow Single-Responsibility Principle<br><br><br>class Course {<br>    id;<br>    type: string;<br>    desc : string;<br>    price : number;<br><br>    constructor(id, type, desc, price) {<br>        this.id = id;<br>        this.type = type;<br>        this.desc = desc;<br>        this.price = price;<br>    }<br>}<br><br><br>class Purchase {<br>    course: Course;<br>    discountRate: number;<br>    total: number;<br><br>    constructor(course: Course, discountRate: number) {<br>        this.course = course;<br>        this.total = this.calculateTotal();<br>    }<br><br>    calculateTotal() {<br>        return (this.course?.price - (this.course?.price * this.discountRate));<br>    }<br><br>    generateInvoice () {<br>        /**<br>         * Generate invoice<br>         */<br>    }<br><br>    sendEmalNotification() {<br>        /**<br>         * Send email notification<br>         */<br>    }<br>}</pre><p><strong>Why does not follow Single-Responsibility Principle :</strong> Purchase class can only purchase course. We can not generate invoice and email notification.<br>For generate invoice, email notification we should create separate class.</p><p>Let create two more classes Invoice and emailNotification.</p><pre>/*<br>* Its follow Single-Responsibility Principle<br>*/<br><br>class Course {<br>    id;<br>    type: string;<br>    desc: string;<br>    price: number;<br><br>    constructor(id, type, desc, price) {<br>        this.id = id;<br>        this.type = type;<br>        this.desc = desc;<br>        this.price = price;<br>    }<br>}<br><br><br>class Purchase {<br>    course: Course;<br>    discountRate: number;<br>    total: number;<br><br>    constructor(course: Course, discountRate: number) {<br>        this.course = course;<br>        this.total = this.calculateTotal();<br>    }<br><br>    calculateTotal() {<br>        return (this.course?.price - (this.course?.price * this.discountRate));<br>    }<br>}<br><br>class Invoice {<br>    purchase: Purchase;<br><br>    constructor(purchase) {<br>        purchase = this.purchase;<br>    }<br><br>    generate() {<br>        /**<br>         * Generate invoice<br>         */<br>    }<br>}<br><br><br>class Notification {<br>    purchase: Purchase;<br><br>    constructor(purchase) {<br>        purchase = this.purchase;<br>    }<br><br>    emailNotification() {<br>        /**<br>         * Email notification<br>         */<br>    }<br>}</pre><h3>B. Open-Closed Principle:</h3><p>The Open-Closed Principle requires that <strong>classes should be open for extension and closed to modification.</strong></p><p><strong>New client requirement : </strong>SMS notification</p><p>For this, first thought come to our mind is change Notification class.</p><pre>/*<br>* Its does not follow Open-Closed Principle<br>*/<br><br>class Notification {<br>    purchase: Purchase;<br><br>    constructor(purchase) {<br>        purchase = this.purchase;<br>    }<br><br>    emailNotification() {<br>        /**<br>         * Email notification<br>         */<br>    }<br><br>    smsNotification() {<br>        /**<br>         * Email notification<br>         */<br>    }<br>}</pre><p><strong>Why does not follow Open-Closed Principle : </strong><br> We can not modify existing class business logic. Its may create new bugs in future.</p><pre>/**<br> * Its follow Open-Closed Principle<br> */<br><br>interface notificationI {<br>    send();<br>}<br><br>class emailNotification implements notificationI {<br>    purchase: Purchase;<br><br>    constructor(purchase) {<br>        purchase = this.purchase;<br>    }<br>    send() {<br>        /*<br>        *<br>        */<br>    }<br>}<br><br>class smsNotification implements notificationI {<br>    purchase: Purchase;<br><br>    constructor(purchase) {<br>        purchase = this.purchase;<br>    }<br>    send() {<br>        /*<br>        *<br>        */<br>    }<br>}</pre><h3>C. <strong>Liskov Substitution Principle</strong>:</h3><p>The Liskov Substitution Principle states that subclasses should be substitutable for their base classes.</p><p>This means that, given that class B is a subclass of class A, we should be able to pass an object of class B to any method that expects an object of class A and the method should not give any weird output in that case.</p><p>In other words, <strong>what we want is to have the objects of our subclasses behaving the same way as the objects of our superclass.</strong></p><pre>/*<br>* Its follow Liskov Substitution Principle<br>*/<br><br>class Purchase {<br>    course: Course;<br>    discountRate: number;<br>    total: number;<br><br>    constructor(course: Course, discountRate: number) {<br>        this.course = course;<br>        this.discountRate = discountRate;<br>        this.total = this.calculateTotal();<br>    }<br><br>    calculateTotal() {<br>        return (this.course?.price - (this.course?.price * this.discountRate));<br>    }<br>}<br><br>class PurchaseForStudent extends Purchase{<br>    constructor(course: Course, discountRate: number) {<br>        super(course, discountRate);<br>    }<br>}</pre><pre>/*<br>* Its does not follow Liskov Substitution Principle<br>*/<br><br>class Purchase {<br>    course: Course;<br>    discountRate: number;<br>    total: number;<br><br>    constructor(course: Course, discountRate: number) {<br>        this.course = course;<br>        this.discountRate = discountRate;<br>        this.total = this.calculateTotal();<br>    }<br><br>    calculateTotal() {<br>        return (this.course?.price - (this.course?.price * this.discountRate));<br>    }<br>}<br><br>class PurchaseForStudent extends Purchase{<br>    constructor(course: Course, discountRate: number) {<br>        super(course, 60); //can not change <br>    }<br>}</pre><h3>D. Interface Segregation Principle:</h3><p>Segregation means keeping things separated, and the Interface Segregation Principle is about separating the interfaces.</p><p>The principle states that many client-specific interfaces are better than one general-purpose interface. Clients should not be forced to implement a function they do no need.</p><pre>/*<br>* Its does not follow Interface Segregation Principle<br>*/<br><br><br>interface ParkingLotI  {<br>    parkCar();<br>    unparkCar(); <br> getCapacity(); <br> doPayment();<br>}<br><br>class freeParking implements ParkingLotI{<br>    parkCar() {<br><br>    }<br>    unparkCar() {<br><br>    }<br> getCapacity() {<br><br>    }<br><br>    //Its force to implemenet<br> doPayment() {<br>        throw new Error(&quot;Parking is free&quot;);<br>    }<br>}<br><br>class Parking implements ParkingLotI{<br>    parkCar() {<br><br>    }<br>    unparkCar() {<br><br>    }<br> getCapacity() {<br><br>    }<br><br> doPayment() {<br>    }<br>}</pre><p><strong>Why does not support Interface Segregation Principle:</strong> We should avoid common interface for both freepark and paidparking. In free park we are forcing to define doPayment function.</p><pre>/*<br>* Its follow Interface Segregation Principle<br>*/<br><br><br>interface PaidParkingLotI {<br>    parkCar();<br>    unparkCar();<br>    getCapacity();<br>    doPayment();<br>}<br><br>interface FreeParkingLotI {<br>    parkCar();<br>    unparkCar();<br>    getCapacity();<br>}<br><br>class freeParking implements FreeParkingLotI {<br>    parkCar() {<br><br>    }<br>    unparkCar() {<br><br>    }<br>    getCapacity() {<br><br>    }<br>}<br><br>class Parking implements PaidParkingLotI {<br>    parkCar() {<br><br>    }<br>    unparkCar() {<br><br>    }<br>    getCapacity() {<br><br>    }<br><br>    doPayment() {<br>    }<br>}</pre><h3>E. Dependency Inversion Principle:</h3><p>The Dependency Inversion principle states that our classes should depend upon interfaces or abstract classes instead of concrete classes and functions.</p><p>Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.</p><p>The dependency inversion principle is a <a href="http://staff.cs.utu.fi/~jounsmed/doos_06/material/DesignPrinciplesAndPatterns.pdf">design principle</a> that states that high-level modules should depend on abstractions rather than concrete implementations. This helps decouple the high-level and low-level modules, making it easier to change the low-level ones without affecting the high-level ones.</p><p>The dependency inversion principle helps us couple software modules loosely. The principle was developed after many years of coupling software modules, and it states:</p><ul><li>High-level modules should not import anything from low-level modules; they should both depend on abstractions</li><li>Abstractions should not rely on concrete implementations; concrete implementations should depend on abstractions</li></ul><h3><a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#conclusion">Conclusion</a></h3><p>In this article, you were presented with the five principles of SOLID Code. Projects that adhere to SOLID principles can be shared with collaborators, extended, modified, tested, and refactored with fewer complications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56da1ca01486" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Micro-Frontend using monorepo and Single-SPA]]></title>
            <link>https://medium.com/@debasisdasnospdii/react-micro-frontend-using-monorepo-and-single-spa-67bc244cbece?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/67bc244cbece</guid>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 07:19:46 GMT</pubDate>
            <atom:updated>2023-03-25T09:57:04.490Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*srnHThZGBJHjYHiDMoypAA.png" /></figure><h4><strong>Today we are going to learn about micro-frontend and develop simple micro frontend monorepo.</strong></h4><p><strong>What is micro frontend :</strong><br>Micro-frontend architecture is a design approach in which a <a href="https://www.toptal.com/front-end">front-end</a> app is decomposed into individual, semi-independent “microapps” working loosely together. The micro-frontend concept is vaguely inspired by, and named after, microservices.</p><p><strong>Micro Frontend Benefits :</strong></p><ol><li>Long term flexibility and support for new technologies.</li><li>Autonomous, Team-Based Development.</li><li>Reduced Maintenance Demands for Frontend Applications.</li><li>Faster, More Reliable Application Testing.</li></ol><p><strong>Why Monorepo?</strong></p><ol><li>Easier to manage, we need only one repo for all micro-frontend and micro services.</li><li>Sharing code is easier, we share code among micro frontends.</li><li>Sharing the same node_modules for all micro frontends and micro services.</li></ol><h4><strong>Lets start development :</strong></h4><p>Before we discuss the step-by-step instructions, let’s get a quick overview of what makes up the demo app. This app is composed of five sub-apps:</p><ul><li>A <a href="https://github.com/agungvr/micro-frontend-monorepo/tree/main/packages/micro-frontend-container">micro-frontend-container</a> that serves as the main page container and coordinates the mounting and unmounting of the micro-frontend apps</li><li>A <a href="https://github.com/agungvr/micro-frontend-monorepo/tree/main/packages/micro-frontend-app1">micro-frontend-</a>account that only shows when active</li><li>A <a href="https://github.com/agungvr/micro-frontend-monorepo/tree/main/packages/micro-frontend-app2">micro-frontend-</a>product that only shows when active</li><li>A <a href="https://github.com/agungvr/micro-frontend-monorepo/tree/main/packages/micro-frontend-app2">micro-frontend-</a>order that only shows when active</li><li>A <a href="https://github.com/agungvr/micro-frontend-monorepo/tree/main/packages/micro-frontend-app2">micro-frontend-</a>payment that only shows when active</li></ul><h4>Steps :</h4><p>1. Install node.js and npm on your system</p><p>Node version : v14.17.2, npm version : 6.14.13</p><blockquote>2. npm i -g lerna //Globally install lerna package</blockquote><p>3. Create one folder “Micro-Frontend_MonoRepo_SPA”</p><p>4. cd Micro-Frontend_MonoRepo_SPA</p><p>And initialise lerna inside the folder:</p><blockquote>5. lerna init</blockquote><p>Once you did it, your folder should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*rrzoQhbKuXmUh0-gxaWAfw.png" /></figure><p>6. We need to tell Lerna we’re using npm with workspaces, so add these one lines to lerna.json:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*C0DHkvcoyh_AzvW8Trveew.png" /></figure><h3>7. <strong>Creating Root Config:</strong></h3><p>To create a microfrontend app for this demo, we’re going to use a command-line interface (CLI) tool called <a href="https://single-spa.js.org/docs/create-single-spa/">create-single-spa</a>.</p><p><em>Framework for bringing together multiple JavaScript microfontends in a frontend application</em></p><p>Run the command:</p><blockquote>npx create-single-spa</blockquote><p>And answer it like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_qhAdKMeVDEsVMjGjjKMA.png" /></figure><blockquote>single-spa root config — App that contains the HTML (EJS) shared between the whole application and register apps. Is the one that orchestrates the micro frontend.</blockquote><p>Next we’ll add a version to the /packages/container/package.json:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*rPXO2BmPP64xD_Foimd6NA.png" /></figure><p>Add your organization name to the root’s /package.json file and add the following scripts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*Z3uqqHDX91izOxk2DYPo7w.png" /></figure><blockquote>8. npm run bootstrap</blockquote><blockquote>9. npm run start</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbyF470Qaa-ZB4Zuvn7_3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*3KRW1-QeCc-9cNrV3grWCQ.png" /></figure><p>Great!, you’ll see default ui from single-spa root config. Ok stop running the server and let’s keep going.<br><strong>You have developed container app. This is default page. Container app will load diff micro-frontends depend on requerment.</strong></p><h3>10. Creating the Micro-Frontend Apps — accounts</h3><p>Let’s, again, from the root directory, run:</p><blockquote>npx create-single-spa</blockquote><p>This time our answers will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPbcwqw2OtoPzVuZNzizQA.png" /></figure><p>Next add version &amp; modify the start script of the new /packages/micro-frontend-account/package.json to include the port:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ndwkbHdMQhgptS3oZCk17g.png" /></figure><p>Now we have to inform our microfrontend-container that it should run this project. For that, we’ll add this line to the packages/container/src/index.ejs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f97DPX-GksjNCxv-z2p3iw.png" /></figure><p>Next modify in ‘packages\container\src\microfrontend-layout.html’ change the application to our apps name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWPM-PhfolGRUnezu5oGHA.png" /></figure><p>Update text in ‘packages\micro-frontend-account\src\root.component.tsx’ :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNFAh2xBjG50stszUqVUEQ.png" /></figure><blockquote>Ok, let’s try:<br>npm run start</blockquote><p>OutPut :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoBAHZOcdX12vq24wayZFw.png" /></figure><p>if you did everything right, you should be able to see your default page from mf-account.</p><p>if you try to open <a href="http://localhost:9001/">http://localhost:9001</a> you will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ztEakxRA020xXTqBuavKzg.png" /></figure><h3>11. Creating the Micro-Frontend Apps — product</h3><p>Let’s, create another micro-frontend mf-product with the same flow:</p><blockquote>A. npx create-single-spa</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s-wVtFqDa645bLcajOTBXw.png" /></figure><p>B. Update \packages\container\src\index.ejs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*biqmtORWgCu1SYFTYQc7Sg.png" /></figure><p>C. Update -/packages\micro-frontend-product\package.json :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7M3w8zgkacOhhWY0Zqc9g.png" /></figure><p>D. Update -/packages\container\src\microfrontend-layout.html :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3TeSidtDY8oYyftP8T9IA.png" /></figure><p>E. Update : /packages\micro-frontend-product\src\root.component.tsx :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Y_Zby0puasglysyHSye7w.png" /></figure><blockquote>F. Run :<br>npm run start</blockquote><p>G. Check — <a href="http://localhost:9000/product">http://localhost:9000/product</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JF16836y9qrEkdDiEnYcEg.png" /></figure><h3>12. Creating the Micro-Frontend Apps — order</h3><p>Let’s, create another micro-frontend mf-order with the same flow:</p><blockquote>A. npx create-single-spa</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llvRhZJluCvmoEFCFUDxKw.png" /></figure><p>B. Update \packages\container\src\index.ejs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4fAjJGszdjkVHvyyFTY_g.png" /></figure><p>C. Update -/packages\micro-frontend-order\package.json :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmEkabbNs9m2php5lkUd1w.png" /></figure><p>D. Update -/packages\container\src\microfrontend-layout.html :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnGjwr6T4vt_HPJVtmyAdA.png" /></figure><p>E. Update : /packages\micro-frontend-order\src\root.component.tsx :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cY98NrNS_LAGDHW6eyNsA.png" /></figure><blockquote>F. Run :<br>npm run start</blockquote><p>G. Check — <a href="http://localhost:9000/product">http://localhost:9000/</a>order</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AW7qd9Ka9mUp7KhY57sJg.png" /></figure><h3>12. Creating the Micro-Frontend Apps — payment</h3><p>Let’s, create another micro-frontend mf-payment with the same flow:</p><blockquote>A. npx create-single-spa</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ef87bvrXYi9aYZz-I6P7A.png" /></figure><p>B. Update \packages\container\src\index.ejs :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfttPIAwgvOhjyWFRAHO6Q.png" /></figure><p>C. Update -/packages\micro-frontend-payment\package.json :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJJvHZFHSRujgx5dnDMVeA.png" /></figure><p>D. Update -/packages\container\src\microfrontend-layout.html :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThTfIIXugoDaj22prbTahw.png" /></figure><p>E. Update : /packages\micro-frontend-payment\src\root.component.tsx :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7GdH16nzsE9izKqDBn7nw.png" /></figure><blockquote>F. Run :<br>npm run start</blockquote><p>G. Check — <a href="http://localhost:9000/product">http://localhost:9000/</a>payment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*utXrW38UHAqgl3cMEp_PbA.png" /></figure><h3>13. Final step — Adding routes in mf-account to load other micro-frontend :</h3><p>A. first we need to install react-router-dom for a specific package =&gt; mf-account</p><blockquote>lerna add react-router-dom — scope=@shopping/mf-account</blockquote><blockquote>B. npm i react-router-dom</blockquote><p>C. Update code in \packages\micro-frontend-account\src\root.component.tsx :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*D2VEapsca0Mn6kMTBcBGVg.png" /></figure><p>D. Create file in C:\Users\DebasisDas\Desktop\Personal\Frontend\1.React\2.Micro-Frontend_MonoRepo_SPA\packages\micro-frontend-account\src:</p><blockquote>\pages\home\index.tsx</blockquote><p>E. Update code in packages\micro-frontend-account\src\pages\home\index.tsx:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGP7IiB2reNcFctKgN12KA.png" /></figure><p>F. Run project — npm run start: <br>all micro frontend running now</p><p>G. <a href="http://localhost:9000/">http://localhost:9000/</a></p><ul><li>Default micro-frontend is container app.</li><li>Container app will load micro-frontend depend on requirement.</li><li>By default container app will load mf-account.</li><li>&lt;Go to product page&gt; -&gt; Will load mf-product</li><li>&lt;Go to order page&gt; -&gt; Will load mf-order</li><li>&lt;Go to payment page&gt; -&gt; Will load mf-payment</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*63TwCMdyfqQotGd-gg3ENA.png" /></figure><p>Congratulation …… you have developed micro-frontend web application.</p><p>Thanks<br>Debasis Das</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67bc244cbece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design pattern : factory design pattern typescript]]></title>
            <link>https://medium.com/@debasisdasnospdii/design-pattern-factory-design-pattern-typescript-9d94c32fd6a5?source=rss-397223dd041b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d94c32fd6a5</guid>
            <dc:creator><![CDATA[Debasis Das]]></dc:creator>
            <pubDate>Tue, 31 Jan 2023 15:55:27 GMT</pubDate>
            <atom:updated>2023-01-31T15:55:27.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design pattern : factory design pattern typescript</h3><p><strong>What is factory design pattern : </strong><br>Factory design pattern is a creational design pattern that separates the logic of creating objects from the client code. The factory class in the factory design pattern is responsible for creating objects based on the request from the client.</p><p>Factory design pattern delegates the responsibility of creating objects to a factory class. Factory class has a factory method responsible for creating the requested object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*wIzi1d9izFPFsqzvrbNQYQ.png" /></figure><p>Code :</p><p>/interface/cloudProvider.interface.ts :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*oCVpESK_thpblPVYb3n6rw.png" /></figure><p>/createFirewall/linode.ts :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3qWqJ1q4nDC_VGpjtDHWA.png" /></figure><p>/createFirewall/upcloud.ts :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GfeVn-T12kSfbeb94EBP8w.png" /></figure><p>index.ts :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsMVsRuGRPwqyTDCmUcY8g.png" /></figure><p>Run : tsc index.ts and node index.js <br>Output : <br>Start…….<br>Firewall created for provider — linode<br>Database updated, after creation firewall — linode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d94c32fd6a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>