<?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 Suraj Verma on Medium]]></title>
        <description><![CDATA[Stories by Suraj Verma on Medium]]></description>
        <link>https://medium.com/@gadgetvala?source=rss-c50d9d66c77d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KH1zXmaXyvP9OqMaybowFw.jpeg</url>
            <title>Stories by Suraj Verma on Medium</title>
            <link>https://medium.com/@gadgetvala?source=rss-c50d9d66c77d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:53:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gadgetvala/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[Decentralized Application (DApp) using Flutter and Solidity]]></title>
            <link>https://gadgetvala.medium.com/decentralized-application-dapp-using-flutter-and-solidity-c7167ff15748?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7167ff15748</guid>
            <category><![CDATA[deccentralized]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[dapps]]></category>
            <category><![CDATA[web3]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Wed, 17 May 2023 02:05:29 GMT</pubDate>
            <atom:updated>2023-05-17T02:05:29.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*73WIo0LxQCBt8Jk9m964Lg.png" /></figure><p>The realm of blockchain technology and the cryptocurrency domain is currently at the forefront of global trends. The proliferation of buzzwords such as NFTs, ETFs, DApps, and DeFi serve as evident indicators of this phenomenon.</p><p>Even within the realm of mobile and web technologies, the notion of decentralized applications and the decentralized web has gained significant traction, and it is imperative for individuals to stay abreast of these developments in order to remain current.</p><p>Before delving further, it is essential to provide brief definitions of some of the terminologies that will be encountered in this article.</p><h3>What is a smart contract?</h3><p>As we are aware, a contract typically refers to an agreement between two parties. Smart contracts, however, go beyond traditional agreements as they are written in code and stored on a blockchain network, making them verifiable, irreversible, and self-executing.</p><p>According to <a href="https://www.investopedia.com/terms/b/blockchain.asp">Investopedia</a>, a blockchain network is a distributed database that is shared among the nodes of a computer network, storing information in a digital format.</p><p>In this article, I will guide you through the process of implementing a decentralized application by utilizing the Solidity programming language to construct a basic smart contract. Additionally, I will outline the steps involved in integrating it with the client side of our application using Flutter.</p><h3>Getting started</h3><p>In this tutorial, we will be constructing a basic smart contract for conducting a simple voting process between two values, “alpha” and “beta”. For the purpose of this tutorial, we will not delve into complex functionalities such as user verification or vote count limitations. Our focus will be on creating a straightforward smart contract using Solidity and integrating it into our application with <a href="https://flutter.dev/"><strong><em>Flutter</em></strong></a>, a UI toolkit that offers fast and flexible UI development capabilities.</p><p>To begin, we will need to download and utilize <a href="https://metamask.io/"><strong><em>MetaMask</em></strong></a>, a popular Ethereum wallet. You can add the <a href="https://metamask.io/"><strong><em>MetaMask</em></strong></a> extension to your preferred browser (such as <a href="https://www.google.com/intl/en_in/chrome/"><strong><em>Chrome</em></strong></a>) by clicking on the provided link.</p><p>Once <a href="https://metamask.io/"><strong><em>MetaMask</em></strong></a> is installed, you can create and set up your crypto wallet. As this is a learning exercise, we recommend changing your network from Ethereum Mainnet to Rinkeby Test Network.</p><p>Once you have successfully set up your wallet, it’s important to obtain some test Ether to cover gas fees for transactions involving our smart contract. One approach is to utilize the <a href="https://faucet.rinkeby.io/"><strong><em>Rinkeby Faucet</em></strong></a>, which provides detailed instructions on how to acquire test Ether.</p><p>Next, we will begin writing our smart contract in Solidity using <a href="https://remix.ethereum.org/"><strong><em>Remix</em></strong></a>, an online integrated development environment (IDE) similar to <a href="https://dartpad.dev/"><strong><em>DartPad</em></strong></a> for Dart.</p><p>If the folders displayed on the left-hand side of the IDE are confusing, you have the option to delete them and create a new file. For our purposes, we will create a new file named <strong><em>“voting.sol”</em></strong>, with the <strong><em>“.sol”</em></strong> extension representing Solidity, much like <strong><em>“.dart”</em></strong> is used for creating Dart and Flutter classes.</p><pre>pragma solidity 0.6.6;<br><br>contract Voting {<br>    int alpha;<br>    int beta;<br><br>    constructor() public {<br>        alpha  = 0;<br>        beta = 0;<br>    }<br><br>    function getTotalVotesAlpha() view public returns(int) {<br>        return alpha;<br>    }<br><br>    function getTotalVotesBeta() view public returns(int){<br>        return beta;<br>    }<br><br>    function voteAlpha () public{<br>        alpha = alpha+1;<br>    }<br><br>    function voteBeta () public{<br>        beta = beta+1;<br>    }<br>}</pre><p>Next, we will dive into comprehending the framework of this straightforward smart contract.</p><pre>pragma solidity 0.6.6;</pre><p>Line 3 in our code exemplifies the declaration of a contract, akin to class declaration in other programming languages.</p><pre>int alpha;<br>int beta;</pre><p>In addition, there are two variable declarations denoting integers, <strong><em>alpha</em></strong> and <strong><em>beta</em></strong>, within the code.</p><pre>constructor() public {<br>   alpha  = 0;<br>   beta = 0;<br>}</pre><p>Following the variable declarations, we encounter the constructor declaration, which is responsible for initializing the fields whenever an instance of this class is created.</p><pre>function getTotalVotesAlpha() view public returns(int) {<br>    return alpha;<br>}<br><br>function getTotalVotesBeta() view public returns(int){<br>    return beta;<br>}</pre><p>Subsequently, we encounter two functions above that perform similar actions. The first function retrieves the value of <strong><em>alpha</em></strong>, while the second function retrieves the value of beta. Upon closer inspection, you’ll notice the <strong><em>“view”</em></strong> attribute attached to them, signifying that these functions are read-only and do not alter any fields within the contract.</p><p>In Solidity, access modifiers are utilized to determine the scope of functions or fields. In our case, the functions have a public access modifier, enabling them to be called externally from the contract.</p><p>Finally, the <strong><em>return</em></strong> type is indicated prior to the curly braces in our function.</p><p>The remaining portion of our function merely increments the values of our fields by 1.</p><p>Now, proceed to click on the <strong><em>“Compile”</em></strong> option located in the left-hand pane of our Integrated Development Environment (IDE).</p><p>After successfully compiling your smart contract, select the <strong><em>“Deploy”</em></strong> and Run tab as depicted in the image below. Then, switch your environment from <strong><em>JavaScript VM</em></strong> to <strong><em>Injected Web3</em></strong>.</p><p>Once you have completed these steps, you can select the <strong><em>“Compile”</em></strong> tab again and choose one or more functions from the smart contract that you wish to test and observe the results directly in the terminal.</p><p>After successfully developing our smart contract, we require a blockchain server to operate on. There are various methods to achieve this, with one option being to utilize <a href="https://trufflesuite.com/ganache/"><strong><em>Ganache</em></strong></a> for running a personal blockchain. However, for the sake of simplicity, we will be utilizing <a href="https://www.infura.io/"><strong><em>Infura</em></strong></a>, a platform that offers access to blockchain networks like Ethereum.</p><p>Simply create an account on the platform and generate a project, which will provide you with a URL. Take note of this URL and ensure that you change the network of the created project from <strong><em>Mainnet</em></strong> to <strong><em>Rinkeby</em></strong>.</p><p>Beneath the network, there are two links available for selection. Once you choose either of them, you’re all set to proceed. The subsequent step involves creating a new Flutter project and including the specified dependencies in our <strong><em>pubspec</em></strong> file.</p><pre>web3dart: ^2.3.3<br>http: ^0.13.4</pre><p>The screen design will be minimalistic, featuring two buttons for casting votes for either <strong><em>alpha</em></strong> or <strong><em>beta</em></strong>, with the cumulative scores prominently displayed above the buttons.</p><p>We begin by initializing the following variables:</p><pre>late Client httpClient;<br><br>late Web3Client ethClient;<br><br>// Ethereum address<br>final String myAddress = &quot;0x8fF1b659bDC9D6eF5d99823B155cfdf47eF2944d&quot;;<br><br>// URL from Infura<br>final String blockchainUrl = &quot;https://rinkeby.infura.io/v3/4e577288c5b24f17a04beab17cf9c959&quot;;<br><br>// Store the value of alpha and beta<br>var totalVotesA;<br>var totalVotesB;</pre><p>Within our initState callback, we will initialize our httpClient and Web3client, and then invoke a method to fetch the values of alpha and beta from our smart contract.</p><pre>@override<br>void initState() {<br>  httpClient = Client();<br>  ethClient = Web3Client(<br>      blockchainUrl,<br>      httpClient);<br>  getTotalVotes();<br>  super.initState();<br>}</pre><p>To grasp the functionality of <strong><em>getTotalVotes</em></strong>, let’s examine the following functions and analyze each of them.</p><p>Prior to that, we will return to the <a href="https://remix.ethereum.org/"><strong><em>Remix IDE</em></strong></a> and copy the ABI of our smart contract from the Solidity Compiler tab, as illustrated in the image above. We will then proceed to our Flutter IDE and create a new file, naming it <strong><em>contract.json</em></strong>, which will be placed in our <strong><em>assets</em></strong> folder. Subsequently, we will add it to our <strong><em>pubspec</em></strong> file and execute the <strong><em>flutter pub get</em></strong> command.</p><p>To add assets to your application, add an assets section, like this:</p><pre> assets:<br>  - assets/contract.json</pre><pre><br>Future&lt;DeployedContract&gt; getContract() async {<br>  // Obtain our smart contract using rootbundle to access our json file<br>  String abiFile = await rootBundle.loadString(&quot;assets/contract.json&quot;);<br><br><br>  String contractAddress = &quot;0xee3F5a4361ec47C57394Fc028C3fBCCd0e9f1B5d&quot;;<br><br><br>  final contract = DeployedContract(ContractAbi.fromJson(abiFile, &quot;Voting&quot;),<br>      EthereumAddress.fromHex(contractAddress));<br><br>  return contract;<br>}<br><br>Future&lt;List&lt;dynamic&gt;&gt; callFunction(String name) async {<br>  final contract = await getContract();<br>  final function = contract.function(name);<br>  final result = await ethClient<br>      .call(contract: contract, function: function, params: []);<br>  return result;<br>}<br><br>Future&lt;void&gt; getTotalVotes() async {<br>  List&lt;dynamic&gt; resultsA = await callFunction(&quot;getTotalVotesAlpha&quot;);<br>  List&lt;dynamic&gt; resultsB = await callFunction(&quot;getTotalVotesBeta&quot;);<br>  totalVotesA = resultsA[0];<br>  totalVotesB = resultsB[0];<br><br>  setState(() {});<br>}</pre><p>Create a contract instance by utilizing the <strong><em>DeployedContract</em></strong> class from our <a href="https://pub.dev/packages/web3dart"><strong><em>web3dart</em></strong></a> package, which requires the <strong><em>ABI</em></strong> file, the name of our smart contract (e.g., Voting), and the contract address as input, and then returns it from our function.</p><p>Please note that to obtain the contract address, you can refer to your Remix IDE, navigate to the Deploy and Run tab, and click on the copy icon located below the Deployed Contracts, as depicted below.</p><p>The subsequent function will be utilized to invoke a function within our smart contract:</p><pre>final result = await ethClient<br>      .call(contract: contract, function: function, params: []);</pre><p>The line above demonstrates how we establish a connection to our smart contract using the call extension from the <strong><em>EthereumClient</em></strong> class in <strong><em>web3dart</em></strong>. The outcome of this operation is a list that contains the returned values from the function.</p><pre>Future&lt;List&lt;dynamic&gt;&gt; callFunction(String name) async {<br>  final contract = await getContract();<br>  final function = contract.function(name);<br>  final result = await ethClient<br>      .call(contract: contract, function: function, params: []);<br>  return result;<br>}</pre><p>Lastly, in the <strong><em>getTotalVotes</em></strong> method, we will utilize the <strong><em>callFunction</em></strong> to invoke functions such as <strong><em>getTotalVotesAlpha</em></strong> and <strong><em>getTotalVotesBeta</em></strong>, which we have defined in our smart contract. It is crucial to ensure that the function names passed match exactly with those in our deployed contract.</p><p>After receiving the values of our votes, the subsequent action is voting. Similar to our previous steps, we will construct a request using the ABI file by calling the functions within it. However, unlike the previous <strong><em>read</em></strong> requests, voting involves a <strong><em>write</em></strong> request. Therefore, we will utilize our private key from <a href="https://metamask.io/"><strong><em>MetaMask</em></strong></a>, or any other private key if it’s a test account, and instead of using call, we will use <strong><em>sendTransaction</em></strong>. This will require passing our private key, a transaction object, and specifying the chainId, which in our case (<strong><em>Rinkeby</em></strong>) is <strong><em>4</em></strong>.</p><pre>Future&lt;void&gt; vote(bool voteAlpha) async {<br>  snackBar(label: &quot;Recording vote&quot;);<br>  <br>  // Obtain private key for write operation<br>  Credentials key = EthPrivateKey.fromHex(<br>      &quot;f6417d3d4c5cc294ace85aa196fcde0ca792550e085f65fff459423e597ff306&quot;);<br><br>  // Obtain our contract from abi in json file<br>  final contract = await getContract();<br><br>  // Extract function from json file<br>  final function = contract.function(<br>    voteAlpha ? &quot;voteAlpha&quot; : &quot;voteBeta&quot;,<br>  );<br><br>  // Send transaction using the our private key, function and contract<br>  await ethClient.sendTransaction(<br>      key,<br>      Transaction.callContract(<br>          contract: contract, function: function, parameters: []),<br>      chainId: 4);<br>  ScaffoldMessenger.of(context).removeCurrentSnackBar();<br>  snackBar(label: &quot;verifying vote&quot;);<br>  <br>  // Set a 20 seconds delay to allow the transaction to be verified before trying to retrieve the balance<br>  Future.delayed(const Duration(seconds: 20), () {<br>    ScaffoldMessenger.of(context).removeCurrentSnackBar();<br>    snackBar(label: &quot;retrieving votes&quot;);<br>    getTotalVotes();<br><br>    ScaffoldMessenger.of(context).clearSnackBars();<br>  });<br>}</pre><p>Following that, we introduce a delay of <strong><em>20</em></strong> seconds in order to account for the transaction verification time before retrieving our balance once again.</p><p>Once all the necessary configurations are in place, upon running your project, you will observe the expected outcome as shown.</p><h3><em>Conclusion</em></h3><p>In conclusion, this basic implementation of a smart contract serves as a starting point for further exploration and learning. You can enhance this implementation by adding interesting features such as authentication, preventing multiple votes from a single user, and implementing effective state management approaches in your application.</p><p>To delve deeper into Solidity, you can refer to their <a href="https://docs.soliditylang.org/en/v0.8.19/"><strong><em>documentation</em></strong></a> available here for further learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7167ff15748" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-threading in Node.js.]]></title>
            <link>https://gadgetvala.medium.com/multi-threading-in-node-js-b4570a4deb69?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4570a4deb69</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Fri, 05 May 2023 04:15:34 GMT</pubDate>
            <atom:updated>2023-05-05T04:15:34.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VAeIvm7Qvgrgtc8N-HZcVg.jpeg" /></figure><p>Originally, JavaScript was designed for simple tasks on the web, such as form validation or creating mouse trails. It wasn’t until 2009 when Ryan Dahl, the creator of Node.js, made it possible for developers to use JavaScript for backend development.</p><p>Backend languages typically support multithreading and offer various mechanisms for synchronizing values between threads and other thread-related features. However, implementing these capabilities in JavaScript would require changing the entire language, which was not Dahl’s original intention. To work around this limitation and enable multithreading in JavaScript, he had to devise a workaround. Let’s delve into the details…</p><h3><strong>Understanding the Inner Workings of Node.js</strong></h3><p>Node.js operates based on the single-threaded event loop paradigm. In order to fully grasp how Node.js functions, it is crucial to comprehend the concept of threads within Node, the event loop that forms the core of Node.js, and have a clear understanding of its basic architecture, including whether it is single-threaded or multi-threaded.</p><h3>Threads in Node.js</h3><p>In Node.js, a thread refers to an independent execution context within a single process. It is a lightweight unit of processing that can operate concurrently with other threads within the same process. Each thread has its own execution pointer and stack, but shares the process heap.</p><p>Node.js employs two types of threads: a main thread managed by the event loop, and multiple auxiliary threads in the worker pool. In the context of Node.js, the terms “auxiliary thread” and “thread” are used interchangeably to refer to worker threads.</p><p>The main thread in Node.js is the initial execution thread that is launched when Node.js starts. It is responsible for executing JavaScript code and handling incoming requests. On the other hand, a worker thread is a separate execution thread that runs in parallel with the main thread.</p><h3>Does Node.js Operate in a Multithreaded or Single-Threaded Manner?</h3><p>The term “single-threaded” refers to a program that has only one thread of execution, allowing it to perform tasks sequentially. On the other hand, “multi-threaded” implies a program with multiple threads of execution that can perform tasks concurrently.</p><p>Each thread operates independently and task allocation is managed by the operating system. However, both approaches have their challenges. In single-threaded processes, tasks are executed in sequence, and a blocking operation can delay the execution of other tasks. In contrast, in multi-threaded processes, synchronization and coordination between multiple threads can be challenging.</p><p>Node.js is considered single-threaded as it has a single main event loop that processes JavaScript operations and handles I/O. However, Node.js provides additional features that, when used correctly, can offer advantages similar to multithreading. To understand how Node.js achieves this and how to handle the challenges associated with this approach.</p><p>The main element in Node.js’ single-threaded architecture is the event loop, which makes Node.js powerful despite being a single-threaded runtime. As mentioned before, there are two types of threads in Node.js, with the main thread utilizing the event loop.</p><p>The event loop is a mechanism that registers callbacks (functions) to be executed in the future and operates in the same thread as the JavaScript code. When a JavaScript operation blocks the thread, the event loop is also blocked.</p><p>The worker pool is an execution model that spawns and manages separate threads, which synchronously perform tasks and return results to the event loop. The event loop then executes the provided callback with the result. The worker pool is primarily used for asynchronous I/O operations, such as interactions with the system’s disk and network, and is implemented in <strong><em>libuv</em></strong>. Although there may be a slight delay when Node.js needs to communicate internally between JavaScript and C++, it is hardly noticeable.</p><p>With both the event loop and the worker pool mechanisms, we are able to write code that handles asynchronous operations effectively in Node.js.</p><pre>fs.readFile(path.join(__dirname, &#39;./package.json&#39;), (err, content) =&gt; {<br> if (err) {<br>   return null;<br> }<br> console.log(content.toString());<br>});</pre><p>The <strong><em>fs</em></strong> module mentioned earlier instructs the worker pool to use one of its threads to read the contents of a file and notify the event loop when it’s done. The event loop then executes the provided callback function with the file contents. This example illustrates non-blocking code, where we don’t have to wait synchronously for a task to complete. Instead, we tell the worker pool to read the file and call the provided function with the result, allowing the event loop to continue executing other tasks while the file is being read.</p><p>However, there may be situations where synchronous execution of complex operations is needed. Functions that take a long time to run can block the thread, potentially decreasing the throughput of the server or even causing it to freeze. In such cases, delegating the work to the worker pool may not be possible.</p><p>Fields that require complex calculations, such as AI, machine learning, or big data, have traditionally faced challenges in using Node.js efficiently due to the operations blocking the main (and only) thread, resulting in an unresponsive server. However, this changed with the introduction of multiple thread support in Node.js v10.5.0.</p><h3>Introducing &quot;worker_threads&quot;</h3><p>The <strong><em>worker_threads</em></strong> module is a package that enables the creation of fully functional multi-threaded Node.js applications.</p><p>A thread worker is a section of code typically extracted from a file and executed in a separate thread.</p><p>It’s worth noting that the terms thread worker, worker, and thread are often used interchangeably and refer to the same concept.</p><p>To begin using thread workers, we need to import the worker_threads module. We can then create a function that assists us in spawning these thread workers, and further discuss their properties.</p><pre>type WorkerCallback = (err: any, result?: any) =&gt; any;<br>export function runWorker(path: string, cb: WorkerCallback, workerData: object | null = null) {<br> const worker = new Worker(path, { workerData });<br> worker.on(&#39;message&#39;, cb.bind(null, null));<br> worker.on(&#39;error&#39;, cb);<br> worker.on(&#39;exit&#39;, (exitCode) =&gt; {<br>   if (exitCode === 0) {<br>     return null;<br>   }<br>   return cb(new Error(`Worker has stopped with code ${exitCode}`));<br> });<br> return worker;<br>}</pre><p>To instantiate a <strong><em>worker</em></strong>, we need to create an instance of the Worker class. The first argument should be a file path that contains the code for the worker, and the second argument should be an object that includes a property called workerData. This <strong><em>workerData</em></strong> is the data that we want the thread to have access to when it starts executing.</p><p>It’s important to note that regardless of whether we are using JavaScript directly or a language that transpiles to JavaScript (such as TypeScript), the file path should always point to files with <strong><em>.js</em></strong> or <strong><em>.mjs</em></strong> extensions.</p><p>I would also like to highlight why we are using a callback approach instead of returning a promise that would be resolved when the <strong><em>message</em></strong> event is triggered. This is because workers can emit multiple <strong><em>message</em></strong> events, not just one.</p><p>As demonstrated in the example above, communication between threads is event-driven, meaning we are setting up listeners to be invoked once a specific event is sent by the worker.</p><p>Here are some of the most common events:</p><pre>worker.on(&#39;error&#39;, (error) =&gt; {});</pre><p>The <strong><em>error</em></strong> event is triggered whenever an unhandled exception occurs within the worker. As a result, the worker is terminated, and the error can be accessed as the first argument in the provided callback function:</p><pre>worker.on(&#39;exit&#39;, (exitCode) =&gt; {});</pre><p>The <strong><em>exit</em></strong> event is emitted when a worker exits. If the worker called <strong><em>process.exit()</em></strong>, the <strong><em>exitCode</em></strong> will be provided to the callback function. If the worker was terminated using <strong><em>worker.terminate()</em></strong>, the exit code would be set to<em> </em><strong><em>1</em></strong>:</p><pre>worker.on(&#39;online&#39;, () =&gt; {});</pre><p>The message event is emitted when a worker sends data to the parent thread. Now, let’s examine how data is shared between threads.</p><h3><strong>There are two approaches to utilizing workers:</strong></h3><p>There are two approaches to leveraging worker threads in order to harness the benefits they provide.</p><p>The first approach is to spawn a worker, execute its code, and send the result back to the parent. However, this approach has significant overhead costs, including the creation of a new worker thread, the memory overhead of managing each thread, and the resources required to start and manage threads. While tasks can be accomplished using this approach, it may not be efficient, especially in large-scale Node-based systems. To address the challenges associated with this approach, a second, more commonly used industry practice is often employed.</p><p>The second approach is to implement a worker pool, which mitigates the drawbacks of the first approach by creating a pool of worker threads that can be reused for multiple tasks. Instead of creating a new worker thread for each task, a pool of workers is created, and tasks are assigned to them.</p><p>In technical terms, a worker pool can be considered an abstract data type that manages a pool of worker threads. Each worker thread in the pool is assigned a task, and the thread executes the task in parallel with other threads.</p><p>There are multiple ways of assigning tasks within a worker pool, and the pool acts as a manager by distributing tasks to the worker threads, collecting results from them, and facilitating communication among the threads within the pool.</p><p>Implementing a worker pool can involve using different data structures and algorithms, such as task queues and message passing systems. The choice of a specific data structure depends on various factors, including the number of worker threads required, the nature of the tasks, and the level of communication needed among the threads.</p><h3>Implementing the worker pool</h3><p>In Node, a worker pool can be implemented using built-in features or third-party tools. The node’s built-in <strong><em>worker-threads</em></strong> module provides support for worker threads, which can be used to create a worker pool. Additionally, there are several libraries available that can complement the worker pool by providing high-level APIs for worker threads and additional support for task scheduling and thread management.</p><p>These libraries automate the process of scheduling tasks and managing threads, making it easier to implement a worker pool. To illustrate, here is an example code that utilizes the built-in <strong><em>worker-threads</em></strong> feature of Node:</p><pre>const { Worker, isMainThread, parentPort } = require(&#39;worker_threads&#39;);<br><br>if (isMainThread) {<br>  // Main thread code<br>  // Create an array to store worker threads<br>  const workerThreads = [];<br>  // Create a number of worker threads and add them to the array<br>  for (let i = 0; i &lt; 4; i++) {<br>    workerThreads.push(new Worker(__filename));<br>  }<br>  // Send a message to each worker thread with a task to perform<br>  workerThreads.forEach((worker, index) =&gt; {<br>    worker.postMessage({ task: index });<br>  });<br>} else {<br>  // Worker thread code<br>  // Listen for messages from the main thread<br>  parentPort.on(&#39;message&#39;, message =&gt; {<br>    console.log(`Worker ${process.pid}: Received task ${message.task}`);<br>    // Perform the task<br>    performTask(message.task);<br>  });<br>  function performTask(task) {<br>    // … operations to be performed to execute the task<br>  }<br>}</pre><p>The code above consists of two parts: one for the main thread and the other for the worker thread. In the main thread portion, necessary members are imported from the module, and if the current execution context is in the main thread, an array is created to store four workers. Subsequently, a new message with a task to be performed is sent to each of the worker threads.</p><p>In the worker thread portion, messages from the main thread are listened for using the on method of the parentPort property. Once a message is received, the process ID along with the task is logged, and then the task is passed to a function that applies appropriate methods to perform the task.</p><h3>What are the key advantages of utilizing threads?</h3><p>Threading is a powerful tool that can greatly impact a program’s performance, responsiveness, and overall efficiency. When utilized effectively, threads can significantly improve a program’s ability to meet user demands and deliver optimal results.</p><p>In Node.js, threading is a valuable feature for developers as it enables the splitting of a process into multiple independent execution streams. When used correctly, threading can enhance the speed, efficiency, and responsiveness of a program.</p><p>Some of the main benefits of using threads are:</p><ul><li>Improved performance: Threads allow for concurrent execution of multiple tasks, resulting in faster overall program execution compared to running tasks sequentially.</li><li>Responsiveness: Threads can prevent compute-heavy tasks from blocking or delaying the execution of other operations, ensuring the program remains responsive to user input and other tasks.</li><li>Resource sharing: Threads in Node.js can share resources, such as variables, allowing for concurrent processing and faster execution of the program.</li><li>Ease of programming: Threading eliminates the limitations of single-threaded architecture in Node.js, making programming more efficient and scalable.</li><li>Improved scalability: Threads are easily scalable, making it simpler to build high-performance and scalable Node.js applications that can handle increased load without difficulty.</li></ul><h3>Conclusion</h3><p>The <strong><em>worker_threads</em></strong> module offers a straightforward approach to incorporating multi-threading support into our applications. By offloading intensive CPU computations to separate threads, we can greatly enhance our server’s throughput. The availability of official threads support is likely to attract more developers and engineers from fields such as AI, machine learning, and big data to start leveraging the power of Node.js in their projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4570a4deb69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolates & Multithreading in Flutter]]></title>
            <link>https://gadgetvala.medium.com/isolates-multithreading-in-flutter-6b9e6513f71c?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9e6513f71c</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[isolate]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[background-location]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Tue, 02 May 2023 08:32:17 GMT</pubDate>
            <atom:updated>2023-05-02T08:32:17.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GoMPySt3ZeKwSWCu0MUAng.png" /></figure><p>Flutter is a powerful framework for creating cross-platform applications that can seamlessly run on various devices and ecosystems. These apps often involve common tasks such as fetching data from the network, serializing it, and displaying the results in a user-friendly UI.</p><p>Developers who work with mobile platforms are aware that certain operations within this process can be resource-intensive and should either be asynchronous or run on separate threads to prevent overloading the main thread, which handles critical tasks like the event loop, and can result in suboptimal performance.</p><p>While Flutter provides useful APIs like <strong><em>Streams</em></strong> and <strong><em>Futures</em></strong> for building asynchronous behavior, these may not be sufficient to completely prevent performance issues. In this article, we will explore how to leverage multithreading in Flutter to offload tasks to background threads and alleviate the load on the main thread.</p><h3>Concurrency vs Asynchronous in Flutter</h3><p>In Flutter, you can implement asynchronous behavior in your functions and utilize <strong><em>Stream</em></strong> APIs using <strong><em>async/await</em></strong>. However, the concurrency of your code is determined by the underlying threading infrastructure that Flutter offers.</p><h3>Gaining insight into the threading infrastructure of Flutter</h3><p>First and foremost, Flutter incorporates thread pools at a VM (Virtual Machine) level to manage tasks like Network I/O.</p><p>Furthermore, instead of exposing threads directly, Flutter employs a distinct concurrency mechanism known as isolates. In Flutter, the root isolate is responsible for running the UI and the majority of your code.</p><h3>What do we mean by “Flutter isolates”?</h3><p>An isolate in Flutter is a higher-level abstraction built on top of threads, similar to an <strong><em>event loop</em></strong>, but with some key differences:</p><ul><li>Each isolate has its own memory space.</li><li>Isolates cannot share mutable values with other isolates.</li><li>Data transmitted between isolates is duplicated.</li></ul><p>Isolates are designed to run independently of each other, which offers benefits such as simplified garbage collection in the Dart VM.</p><p>It’s important to note that if a parent isolate creates child isolates, the child isolates will terminate if the parent isolate does. Additionally, regardless of the isolate hierarchy, the parent isolate cannot access the memory of the child isolate.</p><p>There are several components commonly associated with isolates, including:</p><ul><li><strong><em>ReceivePort</em></strong>: This is used by an isolate to receive data, and another instance can be used by the parent isolate to send data to the spawned isolate.</li><li><strong><em>Control port</em></strong>: This is a special port that provides capabilities such as pausing or terminating the isolate to its owner.</li><li><strong><em>Capability</em></strong>: These are object instances used for isolate authentication. When sending control port commands like <strong><em>pause</em></strong> or <strong><em>terminate</em></strong>, the corresponding instances of <strong><em>Capability</em></strong> that were used when the isolate was created are required for the command to succeed.</li></ul><h3>Approach 1: Utilizing the compute Method</h3><p>As stated previously, there are multiple methods to create isolates in Flutter. One straightforward approach is to utilize the <strong><em>compute</em></strong> function, which executes the code in a separate isolate and returns the results to the main isolate.</p><p>For example, if we have a <strong><em>Person</em></strong> class that needs to be deserialized from a JSON object:</p><pre>class Person {<br>  final String name;<br>  Person(this.name);<br>}</pre><p>We can incorporate the deserialization code in the following manner:</p><pre>Person deserializePerson(String data) {<br> // JSON decoding is a costly thing its preferable  <br> // if we did this off the main thread<br>  Map&lt;String, dynamic&gt; dataMap = jsonDecode(data);<br>  return Person(dataMap[&quot;name&quot;]);<br>}</pre><p>To utilize it with the compute function, we simply need to:</p><pre>Future&lt;Person&gt; fetchUser() async {<br>  String userData = await Api.getUser();<br>  return await compute(deserializePerson, userData);<br>}</pre><p>Internally, this approach will create a new isolate, execute the decoding logic within it, and then return the result to the main isolate. It is well-suited for tasks that are infrequent or one-time occurrences, as the isolate cannot be reused.</p><h3>Approach 2: Utilizing Isolate.spawn</h3><p>This approach is one of the fundamental ways to work with isolates, and it is worth noting that the <strong><em>compute</em></strong> function also utilizes this method internally.</p><p>The deserialization code can be implemented as follows:</p><pre>Future&lt;Person&gt; fetchUser() async {<br>      ReceivePort port = ReceivePort();<br>      String userData = await Api.getUser();<br>      final isolate = await Isolate.spawn&lt;List&lt;dynamic&gt;&gt;(<br>          deserializePerson, [port.sendPort, userData]);<br>      final person = await port.first;<br>      isolate.kill(priority: Isolate.immediate);<br>      return person;<br>}<br><br>void deserializePerson(List&lt;dynamic&gt; values) {<br>    SendPort sendPort = values[0];<br>    String data = values[1];<br>    Map&lt;String, dynamic&gt; dataMap = jsonDecode(data);<br>    sendPort.send(Person(dataMap[&quot;name&quot;]));<br>}</pre><p>To begin with, we need to create an instance of <strong><em>ReceivePort</em></strong>, which enables us to listen for responses from the isolate.</p><p>The <strong><em>spawn</em></strong> function requires two parameters:</p><ol><li>A callback function that is executed within the new isolate (in our case, <strong><em>deserializePerson</em></strong>).</li><li>The parameter that the <strong><em>deserializePerson</em></strong> function accepts.</li></ol><p>We combine the port and serialized data into a list and transmit it. Subsequently, we utilize <strong><em>sendPort.send</em></strong> to return the value to the main isolate and await it using <strong><em>port.first</em></strong>. Finally, we terminate the isolate to complete the cleanup.</p><h3>Optimizing the Reusability of Isolates in Flutter</h3><p>While the previous example is ideal for one-time tasks, we can improve the reusability of the isolate we created above by setting up two ports for bidirectional communication. This allows us to send more data to deserialize while simultaneously listening to the port stream for the results. To achieve this, we can make some adjustments to our deserializing function as follows:</p><pre>void deserializePerson(SendPort sendPort) {<br>  ReceivePort receivePort = ReceivePort();<br>  sendPort.send(receivePort.sendPort);<br>  receivePort.listen((message) {<br>    Map&lt;String, dynamic&gt; dataMap = jsonDecode(message);<br>    sendPort.send(Person(dataMap[&quot;name&quot;]));<br>  });<br>}</pre><p>As evident from the updated code, the first item emitted by our function is a <strong><em>SendPort</em></strong>, which allows the calling function to continuously send data to our new isolate. It’s worth noting that <strong><em>SendPort</em></strong> supports a limited number of data types, including lists, maps, <strong><em>SendPort</em></strong>, and <strong><em>TransferrableTypedData</em></strong>, in addition to primitive data types.</p><p>This approach is suitable for scenarios where we need to perform repetitive tasks in the background frequently, such as decoding JSON from an API. By implementing these changes, we can conveniently send new responses and obtain the deserialized response from the same isolate, enhancing the reusability of the isolate.</p><h3>Delving into the “flutter_isolate” package</h3><p>Bidirectional communication allows for reusing isolates, but there are cases where we need to implement a thread pool-like behavior, where a set of isolates is instantiated once and then reused as needed. Thankfully, Flutter’s isolate package provides us with useful utility tools for this purpose, and one of them is the <strong><em>LoadBalancer</em></strong> API. This class allows us to create and manage a pool of isolates, automatically delegating tasks to free isolates as they become available.</p><p>To utilize the LoadBalancer API, we simply need to include the isolate package in our <strong><em>pubspec.yaml</em></strong> file, like this:</p><pre>dependencies:<br>  isolate: 2.1.1</pre><p>Next, we can update our <strong><em>UserService</em></strong> class to utilize the runner provided by the <strong><em>LoadBalancer</em></strong> API:</p><pre>class UserService{<br>  LoadBalancer? balancer;<br><br>  Future&lt;Person&gt; fetchUser() async {<br>    String userData = await Api.getUser();<br>    balancer ??= await LoadBalancer.create(5, IsolateRunner.spawn);<br>    return await balancer!.run(deserializeJson , userData, load: 1);<br>  }<br><br>  Person deserializeJson(String data) {<br>    Map&lt;String, dynamic&gt; dataMap = jsonDecode(data);<br>    return Person(dataMap[&quot;name&quot;]);<br>  }<br>}</pre><p>In this example, we have created a pool of five isolates and reused them for decoding tasks. The LoadBalancer API’s <strong><em>run</em></strong> function also allows us to specify an optional parameter called load, which represents the estimated <strong><em>load</em></strong> that the decoding task would have on the isolate.</p><p>This method can be useful when we want to run tasks with varying computational costs, such as when one task is more computationally expensive than others. For instance, consider the following code:</p><pre>LoadBalancer? balancer;<br><br>Future&lt;Person&gt; fetchInitialUsers() async {<br>  String userData = await Api.getUsers(count: 5);<br>  balancer ??= await LoadBalancer.create(2, IsolateRunner.spawn);<br>  return await balancer!.run(deserializeUsers, userData, load: 1);<br>}<br><br>Future&lt;Person&gt; fetchSecondaryUsers() async {<br>  String userData = await Api.getUsers(count: 15);<br>  balancer ??= await LoadBalancer.create(2, IsolateRunner.spawn);<br>  return await balancer!.run(deserializeUsers, userData, load: 3);<br>}</pre><p>Observe how we have assigned loads to <strong><em>fetchInitialUsers</em></strong> as <strong><em>1</em></strong> and <strong><em>fetchSecondaryUsers</em></strong> as <strong><em>3</em></strong>, proportionate to the number of users being deserialized. When <strong><em>fetchInitialUsers</em></strong> is initially called, the first isolate will handle the deserialization. At the same time, if <strong><em>fetchSecondaryUsers</em></strong> is called, the load balancer will detect that the first isolate is busy with its assigned load of <strong><em>1</em></strong> and transfer the task to the second isolate. If the second isolate is free with a load of <strong><em>0</em></strong>, it will run the task with a load of <strong><em>3</em></strong>. The load balancer ensures that any new task is queued to the isolate with the lowest load.</p><p>Load balancers can be useful in scenarios where recurring tasks require multiple isolates. For example, an image loader that needs to downsize images based on a target view size can use a balancer pool to queue all downsizing tasks. This prevents overwhelming the main isolate and avoids penalties associated with frequently spawning new isolates.</p><h3>Incorporating isolates with stream APIs</h3><p>Flutter provides an <strong><em>asyncMap</em></strong> operator that allows us to integrate isolates with our existing streams.</p><p>For instance, if we are working with chunked data from a file, which is typically represented as a stream for memory efficiency, we can connect the file-read stream to a load-balanced isolate using asyncMap. This allows the code to run in the background while the recipient of the stream can collate the data on the UI/main isolate, similar to switching threads in reactive programming.</p><p>We can use this approach within an existing stream as demonstrated below:</p><pre>//let&#39;s say we have to compute an md5 of a string along with a salt<br>encryptionSaltStream()<br>.asyncMap((salt) =&gt;<br> // Assuming our load balancer is already created   <br>    balancer!.run(generateMd5, salt.toString() + userData)<br>);</pre><p>This would be a practical scenario where we want to scale down a set of images. We can emit the URLs as a stream, read the file(s) in the isolate, perform the scaling operation in the background, and then collect the updated file path in the receiver.</p><h3>Best practices for working with isolates</h3><p>Creating multiple isolates may initially seem advantageous, but it’s crucial to recognize that spawning isolates comes with a cost that can vary depending on the device. While isolates are ideal for tasks like image manipulation, the overhead may not be justified for simpler use cases.</p><p>Another consideration is that data shared between isolates is duplicated, which can lead to increased memory usage when dealing with larger datasets. To mitigate this, Flutter provides <strong><em>TransferrableTypedData</em></strong>, which acts as a byte wrapper that can be transferred between isolates without the additional overhead. It’s recommended to utilize this feature when processing large files in isolates to optimize memory usage.</p><h3>Conclusion</h3><p>In this article, we have explored the concept of isolates and how they can be used to introduce concurrency into our code, freeing up the UI thread from unnecessary overhead. However, it’s essential to profile our applications to determine if isolate-spawning is a suitable approach, as it may come with a significant cost that could outweigh the benefits in certain cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9e6513f71c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Advanced Enum in Flutter 3.0]]></title>
            <link>https://gadgetvala.medium.com/mastering-advanced-enum-in-flutter-3-0-e6f2b42a74b0?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6f2b42a74b0</guid>
            <category><![CDATA[superenum]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[flutter-3]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 03:58:48 GMT</pubDate>
            <atom:updated>2023-04-24T03:58:48.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8Pf4M5rhEZFltnw__3A_w.jpeg" /></figure><p>Flutter 3.0 has brought about highly anticipated changes, particularly in how enums are used, which many Flutter developers have been eagerly waiting for! This is especially exciting for those who are familiar with more powerful enum implementations in other programming languages and have been missing similar capabilities in Flutter projects.</p><p>Gone are the days of using static methods, method extensions, and utility classes. With the new built-in enum features in Flutter, everything can now be implemented in one place.</p><p>As this is a relatively new development, and most of us are accustomed to older approaches for handling enums, there may be many projects that require refactoring in this aspect. In this article, I will provide a comprehensive overview of what you need to know about enums in Flutter 3.0.</p><h3>What is an enum?</h3><p>Enum, short for enumerated type, is a data type that consists of a limited set of predefined values. In Dart, an <strong><em>enum</em></strong> is a special type of class that is used to represent a fixed number of constant values.</p><p>Here is an example of an <strong><em>enum</em></strong> class:</p><pre>enum OperatingSystem { macOS, windows, linux }</pre><p>Before we continue, it’s important to remember a key point from the Dart documentation, which I’ll quote here because it provides a concise summary of <strong>enums</strong>:</p><p><em>Enums in Dart automatically inherit from the Enum class and are also sealed, which means they cannot be subclassed, implemented, mixed in, or directly instantiated.<br><br>Although abstract classes and mixins can explicitly extend or implement Enum, they can only be utilized in an enum declaration to create objects that implement the type of that class or mixin.</em></p><h3>How enums worked before Flutter 3.0</h3><p>Let’s consider the example above where the enum represents different platforms on which Flutter is available. Suppose we want to add a property that indicates whether a specific platform can build an app for iOS devices.</p><p>There are several approaches to achieve this. The first solution is to create an extension method, as shown below:</p><pre>extension OperatingSystemExtension on OperatingSystem {<br>        bool switch (this) {<br>            case OperatingSystem.macOS: <br>        return true;<br>      case OperatingSystem.windows: <br>      case OperatingSystem.linux: <br>        return false; <br>    }<br>  }<br>}</pre><p>Alternatively, you can convert an enum to a class with an internal constructor and utilize static constants as <strong><em>“enum”</em></strong> values:</p><pre>class OperatingSystem {<br>  final _value;<br>  const OperatingSystem._internal(this._value);<br>  toString() =&gt; &#39;OperatingSystem.$_value&#39;;<br>  static const macOS = const OperatingSystem._internal(&#39;macOS&#39;);<br>  static const windows = const OperatingSystem._internal(&#39;windows&#39;);<br>  static const linux = const OperatingSystem._internal(&#39;linux&#39;);<br>}</pre><p>Lastly, another option is to use a utility or helper class with a static method. However, in my opinion, this approach may not be considered best practice compared to the other two options.</p><pre>class OperatingSystemHelper{<br>  static bool canBuildForIos(OperatingSystem os){<br>    switch(os){<br>      case OperatingSystem.macOS: <br>        return true;<br>      case OperatingSystem.windows: <br>      case OperatingSystem.linux: <br>        return false; <br>    }<br>  }</pre><p>Doesn’t it look messy? It seems like there’s a lot of redundant code that is separate from the enum itself, making it harder to maintain than it should be.</p><p>Furthermore, if you want to apply a mixin or an interface to enable custom sorting out of the box, you’ll be out of luck with the old version of Enum, as it would also have to exist separately.</p><p>Sure, you can store everything in one file and it’s not a big deal. In fact, we’ve been living with it for some time now. But if there’s a better way to write the code, why not opt for that approach?</p><h3><strong><em>So, what are the eagerly anticipated enhancements to Enums?</em></strong></h3><pre>enum OperatingSystem {<br>  macOS(true, true),<br>  windows(false, true),<br>  linux(false, true);<br>  const OperatingSystem(this.canBuildForIos, this.canBuildForAndroid);<br>  final bool canBuildForIos;<br>  final bool canBuildForAndroid;<br>}</pre><p>Isn’t it much improved? Now, a constructor can have named or positional parameters, just like any other class, as long as it remains a const constructor. (Note: If it’s not a const, it won’t compile and will generate a warning, so no need to worry). Additionally, Enums can have methods just like any other class.</p><pre>enum OperatingSystem {<br>  macOS(true, true),<br>  windows(false, true),<br>  linux(false, true);<br><br>  const OperatingSystem(this.canBuildForIos, this.canBuildForAndroid);<br><br>  final bool canBuildForIos;<br>  final bool canBuildForAndroid;<br><br>  bool get isBestOperatingSystemForFlutterDevelopment =&gt; canBuildForIos &amp;&amp; canBuildForAndroid;<br>}</pre><p>However, it’s important to note that a generative constructor must be <strong><em>const</em></strong>, which means it can only be used for additional getters.</p><p>Furthermore, if a constructor needs to be <strong><em>const</em></strong>, then all instance variables must also be final. Factory constructors are limited to returning one of the fixed <strong><em>enum</em></strong> instances.</p><p>Of course, it’s worth mentioning that Flutter supports more platforms than the simplified example used here, and there is no objectively superior operating system for Flutter development.</p><p>With enhanced <strong><em>enums</em></strong>, they now resemble normal classes, allowing for the implementation of interfaces and <em>mixins</em>.</p><pre>mixin Foo {<br>  bool get canBuildForIos;<br>}<br><br>enum OperatingSystem with Foo implements Comparable&lt;OperatingSystem&gt;{<br>  macOS(true, true),<br>  windows(false, true),<br>  linux(false, true);<br><br>  const OperatingSystem(this.canBuildForIos, this.canBuildForAndroid);<br>  <br>  final bool canBuildForAndroid;<br><br>  bool get isBestOperatingSystemForFlutterDevelopment =&gt; canBuildForIos &amp;&amp; canBuildForAndroid;<br><br>  @override<br>  final bool canBuildForIos;<br><br>  @override<br>  int compareTo(OperatingSystem other) =&gt; name.length - other.name.length;<br>}</pre><h3>Generics</h3><p>Enhanced <strong><em>enums</em></strong> also enable the use of generics for enums, as shown in the following example:</p><pre>enum OperatingSystem&lt;T&gt; {<br>  macOS&lt;String&gt;(&#39;Yes I can&#39;),<br>  windows&lt;int&gt;(0),<br>  linux(false);<br><br>  const OperatingSystem(this.canBuildForIos);<br>  final T canBuildForIos;<br>}<br><br>print(OperatingSystem.values.map((e) =&gt; e.canBuildForIos));<br><br>//reuslts in<br>//(Yes I can, 0, false)</pre><p>As you may have noticed with Linux, type inference works seamlessly with enhanced enums.</p><h3><em>Constraints</em></h3><p>Constraints should be noted when working with enhanced enums:</p><ul><li>Enhanced enums cannot extend other classes, as they automatically extend Enum.</li><li>It is not possible to override index, hashCode, or the equality operator, but this is in line with default enum implementations.</li><li>All instances of the enum must be declared at the beginning, and there must be at least one instance to ensure readability.</li></ul><p>In summary, with enhanced enums, we can declare final instance variables and getters, and we can also implement interfaces. Other constraints that come with this feature are intuitive to understand when considering the nature of enums.</p><h3>What makes enhanced enums an improvement?</h3><p>What are the advantages of enhanced enums compared to static classes in terms of limitations?</p><pre>class OperatingSystem {<br>  final _value;<br>  final bool canBuildForIos;<br>  const OperatingSystem._internal(this._value, this.canBuildForIos);<br><br>  toString() =&gt; &#39;OperatingSystem.$_value&#39;;<br><br>  static const macOS = const OperatingSystem._internal(&#39;macOS&#39;, true);<br>  static const windows = const OperatingSystem._internal(&#39;windows&#39;, false);<br>  static const linux = const OperatingSystem._internal(&#39;linux&#39;, false);<br>}<br><br>enum OperatingSystem {<br>  macOS(true),<br>  windows(false),<br>  linux(false);<br><br>  const OperatingSystem(this.canBuildForIos);<br>  final bool canBuildForIos;<br>}</pre><p>When comparing these two approaches, one stands out as more readable, concise, and aligned with its intended use. Additionally, using enhanced enums can help avoid potential issues with switch statements against enum instances, as enums provide warnings if all values are not covered. This is in contrast to custom classes where such warnings may not be generated. Thus, enums have an advantage in terms of readability and compile-time warnings, making them a preferable choice in these aspects.</p><h3>What steps can I take to refactor my current enums?</h3><p>If you currently utilize extensions, you can easily transfer the relevant code to the <strong><em>enum</em></strong> class if it involves a getter or a final property. However, if your code relies on <strong><em>BuildContext</em></strong> for <strong><em>localizations</em></strong>, it may still need to remain in a method extension, depending on your localization solution.</p><p>Similarly, if you are using classes with an internal constructor, you can update the code to the new <strong><em>enum</em></strong> format, unless it doesn’t meet your requirements.</p><h3>Is it possible to utilize enhanced enums to define a singleton?</h3><p>It’s an interesting feature that enhanced enums can be used to create singletons with less code compared to traditional approaches. However, this approach requires the constructor to be const and all instance variables to be final, which may not offer significant benefits or practical use cases for singletons in most scenarios.</p><p>Furthermore, functions defined within such enums would be free from side effects, making them equivalent to top-level static functions. Considering Dart’s code style preference for top-level functions over classes with only static members, this approach may not be the most preferred practice.</p><pre>//preferred<br>String get usecase =&gt; &quot;Am I am useless? true&quot;;<br><br>//enum way <br><br>enum OperatingSystem {<br>  uselessSingleton(true);<br><br>  const OperatingSystem(this.canBuildForIos);<br>  final bool canBuildForIos;<br><br>        String get usecase =&gt; &quot;Am I am useless? $canBuildForIos&quot;;<br>}<br><br>//same result<br>print(usecase);<br>print(OperatingSystem.uselessSingleton.usecase);</pre><h3>Conclusion</h3><p>In conclusion, enhanced enums have been a long-requested feature by the Flutter development community, and I appreciate how they have been released with clear communication and an easy-to-use solution that addresses many of our pain points.</p><p>While the concept of enhanced enums is not complicated, it’s important to pay attention to them as it’s easy to forget about their existence. Despite their numerous use cases, many tutorials may be outdated regarding enhanced enums, so staying updated with these changes is helpful.</p><p>I recommend considering the adoption of enhanced enums in existing projects and refactoring enums where applicable. Any constraints will result in compile-time errors, which will be highlighted by your IDE, alleviating concerns about regressions.</p><p>For those who are particularly interested in the technical details and inner workings of enhanced enums, <a href="https://github.com/dart-lang/language/blob/d16704ae6c9a5fd8f30b7ba9d33a5ab650c7447d/accepted/future-releases/enhanced-enums/feature-specification.md">here</a> is a comprehensive specification for further reference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f2b42a74b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker-Compose essentials for your projects.]]></title>
            <link>https://medium.com/mobioxy/docker-compose-essentials-for-your-projects-5070f672417d?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5070f672417d</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 10:59:07 GMT</pubDate>
            <atom:updated>2023-04-10T10:59:07.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iRBYTH5JCILKsN5nu5Hxg.png" /></figure><h3>About Docker-Compose</h3><p>docker-compose is a powerful tool that enables you to define and deploy multi-container Docker applications. By using a YAML file (docker-compose.yml), you can specify your application’s services, networks, volumes, and other configurations, and with just one command, docker-compose will launch and manage all the containers defined in the file.</p><p>Essentially, docker-compose provides an isolated environment where your application’s services can run seamlessly together. This is especially beneficial for complex applications with multiple services or dependencies like databases and message queues. Additionally, docker-compose simplifies scaling your application by allowing you to easily add or remove instances of services as required.</p><h3><strong>Docker Compose offers several benefits for developers, including:</strong></h3><ul><li>Application definition: Docker Compose allows developers to define their entire application stack in a single file, making it easy to share and version control the application’s architecture.</li><li>Multi-container deployment: Docker Compose enables the deployment of multi-container applications by defining each service separately, allowing for seamless communication between containers.</li><li>Simplicity: Docker Compose simplifies container management, allowing developers to start, stop, or restart their entire application stack with just one command.</li><li>Replication: Docker Compose’s scaling feature makes it effortless to replicate application services horizontally, increasing capacity as needed.</li><li>Consistency: Docker Compose ensures consistency across different development environments, eliminating issues related to “works on my machine” and facilitating easier debugging.</li></ul><p>In summary, Docker Compose streamlines the development and deployment of multi-container applications, maintaining consistency and reproducibility across different environments.</p><h3>Installation of Docker in Mac</h3><p>Beginning with Docker Desktop 4.3.0, we have removed the hard requirement to install <strong>Rosetta 2</strong>. There are a few optional command line tools that still require Rosetta 2 when using Darwin/AMD64. See the <a href="https://docs.docker.com/desktop/troubleshoot/known-issues/">Known issues section</a>. However, to get the best experience, we recommend that you install Rosetta 2. To install Rosetta 2 manually from the command line, run the following command:</p><pre>softwareupdate --install-rosetta</pre><h3>Install interactively</h3><ol><li>Double-click Docker.dmg to open the installer, then drag the Docker icon to the Applications folder.</li><li>Double-click Docker.app in the <strong>Applications</strong> folder to start Docker.</li><li>The Docker menu displays the Docker Subscription Service Agreement window.</li><li>Select <strong>Accept</strong> to continue.</li><li>From the installation window, select either:</li></ol><ul><li><strong>Use recommended settings (Requires password)</strong>. This let’s Docker Desktop automatically set the necessary configuration settings.</li><li><strong>Use advanced settings</strong>. You can then set the location of the Docker CLI tools either in the system or user directory, enable the default Docker socket, and enable privileged port mapping. See <a href="https://docs.docker.com/desktop/settings/mac/#advanced">Settings</a>, for more information and how to set the location of the Docker CLI tools.</li></ul><p>6. Select <strong>Finish</strong>. If you have applied any of the above configurations that require a password in step 5, you are asked to enter your password to confirm.</p><h3>Docker-Compose Commands</h3><ul><li><strong>docker-compose up:</strong> Constructs, (re)creates, initiates, and attaches to containers for a specific service.</li><li><strong>docker-compose build:</strong> Builds or rebuilds services.</li><li><strong>docker-compose start:</strong> Launches existing containers for a service.</li></ul><h3>Stopping and removing containers</h3><ul><li><strong>docker-compose down:</strong> Ceases and removes containers, networks, images, and volumes.</li><li><strong>docker-compose stop:</strong> Halts currently running containers without deleting them.</li></ul><h3>Listing and managing containers</h3><ul><li><strong>docker-compose ps:</strong> Provides a list of containers managed by the current Docker Compose project.</li><li><strong>docker-compose logs:</strong> Shows log output from services.</li><li><strong>docker-compose exec:</strong> Executes a command in a running container.</li></ul><h3>Docker Compose YAML Commands</h3><p>The Docker Compose configuration file is authored in YAML format, and it contains various example commands that are utilized in docker-compose.yml files:</p><ul><li><strong>version:</strong> Specifies the version of the Compose file syntax.</li><li><strong>services:</strong> Defines containers.</li><li><strong>image:</strong> Specifies the name(s) of the image(s) to be used for creating the container(s).</li><li><strong>ports:</strong> Exposes ports from container(s) to the host.</li><li><strong>volumes:</strong> Defines shared or persistent data storage locations between containers or the host machine.</li><li><strong>links:</strong> Establishes dependencies between services.</li><li><strong>environment:</strong> Sets environment variables.</li></ul><p>These are just a few examples of the many commands provided by Docker<br> Compose. For more information, you can check out the <a href="https://docs.docker.com/compose/reference/">official documentation</a>.</p><h3><strong>Using Docker-Compose</strong></h3><p>We will establish a connection between the small project and the database, utilizing DockerCompose to execute the Fast API container along with the database.</p><p>Please refrain from making changes to the Dockerfile, but update the main.py and requirements.txt files with the specified contents.</p><pre>#requirements.txt<br>fastapi<br>uvicorn<br>databases<br>psycopg2-binary<br>asyncpg</pre><ul><li>The databases package is a Python library that offers a user-friendly and straightforward interface for interacting with relational databases using the async/await syntax. It streamlines common database operations such as querying, inserting, updating, and deleting data from various relational databases including SQLite, MySQL, PostgreSQL, Oracle, and more. Additionally, the databases package comes with built-in support for SQL Alchemy Core, which empowers developers to leverage its powerful features such as schema and dialects.</li><li>The psycopg2-binary library is a Python package that enables connectivity between Python programs and PostgreSQL databases. It is built on top of the psycopg2 package, which serves as a C wrapper around the PostgreSQL client library, and is designed to be both efficient and user-friendly.</li><li>The asyncpg library, on the other hand, is a Python module specifically designed for asynchronous access to PostgreSQL databases. It offers an easy-to-use API that supports both synchronous and asynchronous programming models, allowing developers to create high-performance database applications in Python. The module utilizes the async io framework for all of its asynchronous network I/O, making it highly suitable for concurrent applications.</li></ul><pre>#main.py<br>from fastapi import FastAPI<br>import databases<br><br>app= FastAPI()<br><br>DATABASE_URL = &quot;postgresql://db_user:db_password@postgres:5432/db&quot;<br>database=databases.Database(DATABASE_URL)<br><br>@app.get(&quot;/&quot;)<br>async def index():<br>    return {&quot;response&quot;:&quot;Hello World&quot;}<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup():<br>    await database.connect()<br>    print(&quot;connected to db!&quot;)<br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown():<br>    await database.disconnect()<br>    print(&quot;db connection closed!&quot;)</pre><p>The provided code establishes a database connection in Python using the databases package. The DATABASE_URL variable specifies the URL where the database is hosted, and the Database class from databases is used to create a client that connects to it.</p><p>In this specific example, a PostgreSQL database located at postgres:5432 is being used, with a user of db_user and a password of db_password. The name of the connected database is db.</p><p>Once the client is created, it can be utilized to execute SQL queries against the connected database.</p><p>The functions <strong>async def startup()</strong>: … and <strong>async def shutdown()</strong>: … are responsible for connecting to and closing the database connection respectively when the FastAPI app starts up and shuts down.</p><p>Now, it’s time to utilize Docker Compose. Please navigate to the project folder and create a .yml file using the following command:</p><p>cd ~/Desktop/simplefastapi &amp;&amp; touch docker-compose.yml</p><p>Then, add the specified contents to the newly created yml file.</p><pre>version: &quot;3.9&quot;<br><br>services:<br>  postgres:<br>    image: postgres:latest<br>    container_name: postgres<br>    volumes:<br>      - db_data:/var/lib/postgresql/data/<br>    ports:<br>      - &quot;5432:5432&quot;<br>    environment:<br>      - POSTGRES_USER=db_user<br>      - POSTGRES_PASSWORD=db_password<br>      - POSTGRES_DB=db<br>  fastapi:<br>    build:<br>      context: .<br>      dockerfile: Dockerfile<br>    container_name: fastapi<br>    ports:<br>      - &quot;80:80&quot;<br>    depends_on:<br>      - postgres<br><br>volumes:<br>  db_data:</pre><p>The provided code is a docker-compose file that outlines two services, namely postgres and fastapi. The postgres service employs the official PostgreSQL Docker image to create a container that runs PostgreSQL.</p><p>The following are the details of the docker-compose file:</p><p>For the postgres service:</p><ul><li><strong>“image: postgres:latest”</strong> specifies the usage of the latest version of the official PostgreSQL image from Docker Hub.</li><li><strong>“container_name: postgres”</strong> sets the name of the container as “postgres” for easy identification in logs and commands.</li><li><strong>“volumes: — db_data:/var/lib/postgresql/data/”</strong> creates a named volume named “db_data” which will be used to persistently store PostgreSQL data files. It also mounts this volume on the container’s “/var/lib/postgresql/data/” directory, where PostgreSQL stores its database files by default.</li><li><strong>“ports: — 5432:5432”</strong> maps the host machine’s port 5432 to the container’s port 5432, enabling connections to PostgreSQL from outside the container.</li><li><strong>“environment”</strong> sets the environment variables within the PostgreSQL container, including POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB, which are used to create a new PostgreSQL user and database with the specified credentials.</li></ul><p>For the fastapi service:</p><ul><li><strong>“build”</strong> specifies the build context (the current directory “.”) and the name of the Dockerfile (“Dockerfile”) to be used for building the image.</li><li><strong>“container_name: fastapi”</strong> sets the name of the FastAPI container as <strong>“fastapi”</strong>.</li><li><strong>“ports: — 80:80”</strong> maps the host machine’s port 80 (HTTP) to the container’s port 80, allowing access to the API through HTTP requests.</li><li><strong>“depends_on: — postgres”</strong> specifies that the postgres service should be started before the fastapi service.</li></ul><p>Finally, <strong>“volumes: db_data”</strong> simply declares the <strong>“db_data”</strong> volume, which was defined earlier for PostgreSQL, to ensure its proper creation when the compose file is deployed.</p><h3><strong>Build and Run Containers</strong></h3><p>To initiate the containers, we execute the <strong>“docker-compose up — build -d” </strong>command, which will build the Docker images as defined in the docker-compose file prior to starting the containers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5070f672417d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobioxy/docker-compose-essentials-for-your-projects-5070f672417d">Docker-Compose essentials for your projects.</a> was originally published in <a href="https://medium.com/mobioxy">Mobioxy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Security practices with Node.js]]></title>
            <link>https://medium.com/mobioxy/best-security-practices-with-node-js-a1dba35e840a?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1dba35e840a</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 10:57:30 GMT</pubDate>
            <atom:updated>2023-04-10T10:57:30.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Node.js is extremely popular nowadays, primarily as a back-end server for web applications. However, in the world of microservices, you can find it pretty much everywhere, playing different and important roles in a bigger application stack.</p><p>The Node.js platform is inherently secure, but because it uses third-party open source packages through its package management system (npm), which from the security point of view, provides more opportunities to open back doors. Additionally, the more popular the framework, the more chance that hackers will try to find vulnerabilities. Therefore, you should always take Node.js security seriously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*pxOxny2qtNB0Gb_LsRD95A.gif" /></figure><h3>1. Implement Secure Headers</h3><p>Express is designed for creating web applications — not securing your Node.js server from vulnerabilities. The defaults leave the HTTP headers mostly open, in part, to assist with the <strong>rapid application development</strong>. This is where Helmet.js steps in.</p><p>Helmet.js fills in the gap between Node.js and Express.js by securing HTTP headers that are returned by your Express apps. HTTP, by design, is open in nature and <strong>highly insecure</strong>. It can leak sensitive information about your app and leave your data open to anyone with some tech skills to see.</p><p><a href="https://www.npmjs.com/package/helmet"><strong><em>Helmet</em></strong> </a>helps you secure your Express apps by setting various HTTP headers. <em>It’s not a silver bullet</em>, but it can help!</p><h3>2. Secure your application from XSS Attacks.</h3><p>Cross-site scripting (XSS) is a code injection attack on web applications. Attackers use vulnerable websites to inject malicious code or a script. The XSS allows the attacker to inject the <strong>malicious </strong>code using script languages such as JavaScript.</p><p>The malicious code is executed on the user’s browser. The attacker then can access cookies, passwords, and other confidential information saved by the browser.</p><p>A web application is<strong> vulnerable</strong> to XSS if the user input is not encoded appropriately. When the user input is encoded incorrectly, the malicious script is sent to users and executed.</p><p>Improper input validation and <strong>sanitization </strong>of data provided by the web application user are the leading causes of XSS attacks.</p><p>Use<strong><em> </em></strong><a href="https://www.npmjs.com/package/xss-clean"><strong><em>xss-clean</em></strong></a> middleware to sanitize user input coming from POST body, GET queries, and url params. Works with <a href="http://expressjs.com/">Express</a>, <a href="http://restify.com/">Restify</a>, or any other <a href="https://github.com/senchalabs/connect">Connect</a> app.</p><h3>3. Secure your application from XSS Attacks with MongoDB Database.</h3><p><strong>NoSQL</strong> databases provide looser consistency restrictions than traditional SQL databases. By requiring fewer relational constraints and consistency checks, NoSQL databases often offer performance and scaling benefits. Yet these databases are still <strong>potentially vulnerable</strong> to injection attacks, even if they aren’t using the traditional SQL syntax. Because these NoSQL injection attacks may execute within a <a href="https://en.wikipedia.org/wiki/Procedural_programming">procedural language</a>, rather than in the <a href="https://en.wikipedia.org/wiki/Declarative_programming">declarative SQL language</a>, the potential impacts are greater than traditional <strong>SQL injection</strong>.</p><p>Use <a href="https://www.npmjs.com/package/express-mongo-sanitize"><strong><em>Express Mongoose Sanitize</em></strong></a> middleware which sanitizes user-supplied data to prevent MongoDB Operator Injection.</p><h3>4. Compress response data.</h3><p><strong>Compression </strong>in <strong>Node.js</strong> and <strong>Express.js</strong> decreases the amount of downloadable data from a website or app. By using this compression, we can improve the performance of our Node.js applications as our payload size is dramatically reduced above 70%.</p><p><strong>Compression </strong>generally refers to code that has been modified using a data compression algorithm. Unlike <strong>minification </strong>that ends up providing perfectly valid code, compressed code must be unzipped before use.</p><p>With each <strong>HTTP request/response</strong>, browsers and web servers can add Headers to include additional information about the asset being searched for or received. When the browser sends in the <strong>Request Header</strong> the <strong>accept-encoding</strong> option specifies which content encoding formats or compression algorithms it supports.</p><p>Use <a href="https://www.npmjs.com/package/compression"><strong><em>compression</em></strong></a> middleware to compress the response.</p><h3>5. Compress response data.</h3><p>The idea behind timeouts is that in scenarios where a program has to wait for something to happen (such as a response to an HTTP request), the waiting is aborted if the operation cannot be completed within a specified duration. This allows for a more efficient control of sever resources as stuck operations or stalling connections are not allowed continued use of limited resources.</p><p>Use <a href="https://www.npmjs.com/package/connect-timeout"><strong><em>connect-timeout</em></strong></a> middleware to control over request timeouts.</p><h3>Summary</h3><p>Securing web applications is important, but tight deadlines sometimes prevent us from properly executing at any given stage. That’s why it’s important to consider security at every step of the software development lifecycle, from conception all the way to production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1dba35e840a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobioxy/best-security-practices-with-node-js-a1dba35e840a">Best Security practices with Node.js</a> was originally published in <a href="https://medium.com/mobioxy">Mobioxy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTTP Requests & Refresh Token with DIO in Flutter]]></title>
            <link>https://medium.com/mobioxy/http-requests-refresh-token-with-dio-in-flutter-4048e0d3307f?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4048e0d3307f</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[refresh-token]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[network]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 07:52:42 GMT</pubDate>
            <atom:updated>2023-04-10T10:55:31.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZ0AXn6kvyUTm14uapaqUA.jpeg" /></figure><p>This article will showcase the utilization of the DIO package in a Flutter application for performing GET and POST requests, along with the implementation of refresh tokens to sustain a continuous user session. The topics that will be covered include:</p><ol><li>Setting up DIO</li><li>Creating a DIO instance with interceptors</li><li>Making GET and POST requests</li><li>Implementing automatic token refresh with DIO interceptors</li></ol><p><strong>1. Setting up DIO</strong></p><p>First, add the DIO package to your <strong>pubspec.yaml</strong> file:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  dio: ^4.0.0</pre><p>Then, run “<strong>flutter pub get”</strong> to install the package.</p><p><strong>2. Creating a DIO instance with interceptors</strong><br>To generate a DIO instance with interceptors, begin by importing the DIO package:</p><pre>import &#39;package:dio/dio.dart&#39;;</pre><p>Next, create a DIO instance with a predefined configuration:</p><pre>Dio dio = Dio(<br>  BaseOptions(<br>    baseUrl: &#39;https://your-api-url.com&#39;,<br>    connectTimeout: 5000,<br>    receiveTimeout: 3000,<br>  ),<br>);</pre><p><strong>3. Making GET and POST requests</strong></p><p>With a DIO instance at our disposal, we can proceed to utilize it for executing both GET and POST requests. Take a look at the following example, which demonstrates how to make a GET request:</p><pre>Future&lt;void&gt; fetchData() async {<br>  try {<br>    Response response = await dio.get(&#39;/path/to/your/endpoint&#39;);<br>    print(response.data);<br>  } on DioError catch (e) {<br>    print(e.message);<br>  }<br>}</pre><p>For performing a POST request, the post method can be utilized in the following manner:</p><pre>Future&lt;void&gt; postData() async {<br>  try {<br>    Response response = await dio.post(<br>      &#39;/path/to/your/endpoint&#39;,<br>      data: {&#39;key&#39;: &#39;value&#39;},<br>    );<br>    print(response.data);<br>  } on DioError catch (e) {<br>    print(e.message);<br>  }<br>}</pre><p><strong>4. Implementing automatic token refresh with DIO interceptors</strong></p><p>In order to implement automatic token refresh, we will add an interceptor to the DIO instance that will handle the token refresh logic whenever a 401 (Unauthorized) response is detected from the server.</p><p>To begin with, create a function that is responsible for refreshing the access token:</p><pre>Future&lt;String&gt; refreshToken() async {<br>  // Perform a request to the refresh token endpoint and return the new access token.<br>  // You can replace this with your own implementation.<br>  return &#39;your_new_access_token&#39;;<br>}</pre><p>Next, add an interceptor to the DIO instance:</p><pre>dio.interceptors.add(<br>  InterceptorsWrapper(<br>    onRequest: (options, handler) {<br>      // Add the access token to the request header<br>      options.headers[&#39;Authorization&#39;] = &#39;Bearer your_access_token&#39;;<br>      return handler.next(options);<br>    },<br>    onError: (DioError e, handler) async {<br>      if (e.response?.statusCode == 401) {<br>        // If a 401 response is received, refresh the access token<br>        String newAccessToken = await refreshToken();<br><br>        // Update the request header with the new access token<br>        e.requestOptions.headers[&#39;Authorization&#39;] = &#39;Bearer $newAccessToken&#39;;<br><br>        // Repeat the request with the updated header<br>        return handler.resolve(await dio.fetch(e.requestOptions));<br>      }<br>      return handler.next(e);<br>    },<br>  ),<br>);</pre><p>With the inclusion of this interceptor, your application will seamlessly handle the refreshment of the access token and automatically retry requests upon receiving a 401 response.</p><p>Congratulations! You have successfully implemented a DIO instance with interceptors to manage GET and POST requests, as well as automatic token refresh. This approach will ensure a persistent user session and enhance the overall user experience in your Flutter application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4048e0d3307f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobioxy/http-requests-refresh-token-with-dio-in-flutter-4048e0d3307f">HTTP Requests &amp; Refresh Token with DIO in Flutter</a> was originally published in <a href="https://medium.com/mobioxy">Mobioxy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build APK using GitHub Action (CI/CD)]]></title>
            <link>https://medium.com/mobioxy/build-apk-using-github-action-ci-cd-7d4a12f0f5ce?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d4a12f0f5ce</guid>
            <category><![CDATA[apk]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 03:58:49 GMT</pubDate>
            <atom:updated>2022-12-30T03:58:49.276Z</atom:updated>
            <content:encoded><![CDATA[<p>With Android app development a challenge came to share APK every time you make changes in your code to the tester and client!! It is not a big task but it’s a repetitive task.</p><p>In this blog, we will talk about how we can solve above problems by generating APK using GitHub actions. So Let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*GDMWjZuD27b86u3b9RSHzg.gif" /></figure><h3>Prerequisite</h3><ol><li>Basic understanding of GitHub.</li><li>Basic of <a href="https://www.taniarascia.com/how-to-create-and-use-bash-scripts/">bash</a> scripting.</li></ol><h3><strong>Let’s Start:</strong></h3><ol><li>Create a “.github” folder in the root dir.</li><li>Then create a new folder named “workflows” in the “.github” folder.</li><li>Create a “main.yml” file in the “.github/workflows/” folder.</li></ol><p>4. Added the Below code in the “main.yml” file</p><pre>name: Build Release APK Files<br>on:<br>  push:<br>    branches:<br>      - develop<br>jobs:<br>  build:<br>    name: Build &amp; Release<br>    runs-on: ubuntu-latest<br>    steps:<br>      # Checkout Repository<br>      - uses: actions/checkout@v3<br><br>      # Setup Java for Flutter<br>      - uses: actions/setup-java@v3<br>        with:<br>          java-version: &quot;17.x&quot;<br>          distribution: &quot;temurin&quot;<br>          cache: gradle<br><br>      # Install Flutter command<br>      - uses: subosito/flutter-action@v2<br>        with:<br>          channel: &quot;stable&quot;<br>      - run: flutter --version<br>      - run: flutter clean<br>      - run: flutter pub get<br>      - run: flutter build apk --release<br><br>      # Add APk to assets<br>      - name: Push to Releases<br>        uses: ncipollo/release-action@v1<br>        with:<br>          artifacts: &quot;build/app/outputs/flutter-apk/app-release.apk&quot;<br>          tag: v1.0.${{ github.run_number }}<br>          token: ${{ secrets.TOKEN_SECRET }}</pre><p>5. Next Step, is to Generate Github Repo Token, You can generate Personal Token from GitHub Settings &gt; Developer Settings &gt; Personal Access Token &gt; Generate New Token &gt; (Need Repo scope).</p><p>6. Add this token to Github Secrets, with the name “TOKEN_SECRET” and the value would be the token you have generated.</p><p>Now Whenever you push your code to develop branch it will automatically build the app and add to assets.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d4a12f0f5ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobioxy/build-apk-using-github-action-ci-cd-7d4a12f0f5ce">Build APK using GitHub Action (CI/CD)</a> was originally published in <a href="https://medium.com/mobioxy">Mobioxy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Flutter Web App to Firebase hosting using GitHub Action (CI/CD)]]></title>
            <link>https://medium.com/mobioxy/deploy-flutter-web-app-to-firebase-hosting-using-github-action-ci-cd-a2c7bb3554b5?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2c7bb3554b5</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 05:00:11 GMT</pubDate>
            <atom:updated>2022-12-02T05:00:11.981Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploy flutter web project to Firebase hosting whenever you push code to a certain branch</p><p>Flutter is growing in its popularity from day to day, and now it is even easier to spin it off with web support. We are in a state where companies are releasing software and solutions within minutes, and they are doing so by following the Continuous integration (CI) and continuous delivery (CD) set of operating principles.</p><p>A CI/CD pipeline makes the automatic delivery of your software more frequent, reliable, and secure. It focuses on higher code quality, and that’s why it is vital for a mobile developer or team.</p><p>In this tutorial, you’ll learn how to deploy your Flutter web app following CI/CD principles with GitHub Actions as a tool for Firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ts2Sz0WUw4_6WKWOa2isGA.gif" /></figure><h3>What is GitHub Actions?</h3><p>GitHub Actions is a CI/CD tool that helps you build, test, and deploy your changes on production directly from your repository. You can use it to set up app releases on certain events like committing a tag in a certain branch of your repository.</p><p>Additionally, one doesn’t have to create a workflow for common things across the projects as GitHub has a marketplace from which you can use existing workflows developed by others.</p><p>The GitHub Actions workflow uses .yml (“YAML Ain’t Markup Language”) files, which will be stored in the .github directory at the root of your project.</p><p>Additionally, GitHub Actions supports different environments and containers like Linux, macOS, Windows, and even VMS.</p><h3>Getting started</h3><p><strong>Step 1: Let Host over flutter web app to Firebase hosting</strong></p><ol><li>Create a New project on <a href="https://firebase.google.com/"><em>Firebase</em></a><em>.</em></li><li>After that install<a href="https://firebase.google.com/docs/cli"><em> firebase-</em>tools</a>, to Install <a href="https://firebase.google.com/docs/cli"><em>firebase-</em>tools</a> first install <a href="https://nodejs.org/en/"><em>node.js</em></a><em>.</em></li><li>After installing firebase-tools, run “firebase login” it will redirect you to the web to login into firebase.</li><li>After Firebase login, run “firebase init” in the root path of your project. then you get a screen like below and select hosting.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*WY_BtaODAnoejcz3zNPWKg.jpeg" /></figure><p>5. After Selecting Hosting you will get the screen to select a project, use the existing project because we already created it from on firebase console. Then select the project name which you have created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*jUl9243bYNzG1OUVDZ3XIg.jpeg" /></figure><p>6. After selecting the project it will ask you for the build folder give “build/web” because after building the web app it will be located in the build/web folder after that type yes because we have a single app page then no we don’t wanna set up automatic deploy right now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*K-r3vhF-fJi0E6DDjfO4nw.jpeg" /></figure><p>7. Firebase is set up in your project. Now build your flutter web project by running the command “flutter build web” after this command run “firebase deploy”. It will deploy your flutter web app to firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*OO7w-13zSuaTpCO7w1Je0Q.gif" /></figure><p>We have deployed our app to Firebase, but wait this stuff is too repetitive every time you change the code you need to build it and again deploy it to firebase, it sucks right, let’s automate this.</p><p><strong>Step 2: Let setup CI/CD with GitHub action to Deploy it to Firebase.</strong></p><ol><li>For CI/CD with GitHub first, create “.github” in the root project folder.</li><li>In the .github folder create another folder named “workflows” and in workflows create a new file called “main.yml”</li><li>Now copy and paste this code in main.yml</li></ol><pre>name: Build and Deploy Web App<br>on:<br>  push:<br>    branches:<br>      - main<br>jobs:<br>  hosting:<br>    name: Deploy Website<br>    runs-on: ubuntu-latest<br>    steps:<br>      # Checkout Repository<br>      - uses: actions/checkout@v3<br><br>      # Install Flutter command<br>      - uses: subosito/flutter-action@v2<br>        with:<br>          channel: &quot;stable&quot;<br>      - run: flutter --version<br><br>      # Build Website<br>      - name: Build Website<br>        run: |<br>          flutter clean<br>          flutter pub get<br>          flutter build web<br>        working-directory: ./<br><br>      # Deploy Firebase Hosting<br>      - name: Deploy Firebase Hosting<br>        uses: w9jds/firebase-action@master<br>        with:<br>          args: deploy --only hosting:PROJECT_NAME<br>        env:<br>          FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}<br>          PROJECT_PATH: ./</pre><p>4. In the above yml file just change your “project name” in the Deploy Firebase Hosting block, you will get the project name from Firebase URL.</p><p>5. After this we need to Firebase CI Token, to get it run “firebase login:ci” it will give you a Firebase token, save that token somewhere.</p><p>6. After that go to GitHub repository setting &gt; Secrets &gt; Actions. Add new secrets with the name “FIREBASE_TOKEN” and then the value will be the key that we get in the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMBzUnn4z1KXT8Iv8GaEJA.png" /></figure><p>Viola! We have done it Now just push the code to GitHub. Now every time you push the code to the main branch it will automatically build the code and deploy it to firebase.</p><p>Follow me for more: <a href="https://github.com/gadgetvala">Github</a>, <a href="https://linkedin.com/in/gadgetvala">Linkedin</a>, <a href="https://instagram.com/gadgetvala">Instagram</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0PB_JCJmxrDDB32IOKv9sw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2c7bb3554b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobioxy/deploy-flutter-web-app-to-firebase-hosting-using-github-action-ci-cd-a2c7bb3554b5">Deploy Flutter Web App to Firebase hosting using GitHub Action (CI/CD)</a> was originally published in <a href="https://medium.com/mobioxy">Mobioxy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Dynamic Assets with AWS S3]]></title>
            <link>https://medium.com/mobioxy/securing-dynamic-assets-with-aws-s3-64fef4feaf6e?source=rss-c50d9d66c77d------2</link>
            <guid isPermaLink="false">https://medium.com/p/64fef4feaf6e</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[presigned-url]]></category>
            <dc:creator><![CDATA[Suraj Verma]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 12:08:00 GMT</pubDate>
            <atom:updated>2022-11-23T12:08:00.323Z</atom:updated>
            <content:encoded><![CDATA[<p>From small businesses to international online retailers who generate a large amount of data, are looking to move to the cloud for increased data availability, better data security, and a smaller financial footprint.</p><p>However, when it comes to choosing where to store data in the cloud, there are many choices. Amazon Simple Storage Service (S3) is a popular cloud storage service with critical features like encryption, access control, and high availability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*2GOMAkM6NxV4J97kCtnQLg.png" /></figure><h4>Working with AWS S3</h4><p>To start using this AWS cloud service, you simply need to sign up for an AWS account. AWS resources, including S3, are managed through a web application known as the AWS Management Console. This customizable home page provides a single place to access everything you need to manage AWS tasks.</p><p>Amazon S3 objects are organized in buckets. Buckets are the main containers in S3, and every object must be stored in one. All of S3’s main features, such as the interfaces and APIs, can act either on buckets or individual objects.</p><p>When users upload data, they create bucket and bucket name first, then move however many objects they need into it. AWS S3 uses an Object Key, along with a version identifier, to uniquely identify objects in a bucket. This helps users to organize data.</p><p>Organizations may use naming conventions to identify data owners, improve access control, and make the store more navigable for end users.</p><p>Amazon S3 users can work with the console or web-service interfaces to access raw objects or buckets.</p><h4>Let’s start,</h4><p>I’ll use Node.js and aws-SDK in this turtorial to explain how pre-signed URLs work with the bucket!</p><h4><strong><em>So what are pre-signed URLs anyway?</em></strong></h4><p>A pre-signed URL is a URL that you can provide to your users to grant temporary access to a specific S3 object. Using the URL, a user can either READ the object or WRITE an Object. The URL contains specific parameters which are set by your application. A pre-signed URL uses three parameters to limit access to the user.</p><ul><li>Bucket: The bucket that the object is in (or will be in)</li><li>Key: The name of the object</li><li>Expires: The amount of time that the URL is valid</li></ul><p><strong>In General use case you need three type of function to work it</strong></p><ul><li>Get a Pre-signed Url for uploading the Object</li><li>Get a Pre-signed Url to view the Object</li><li>Delete Object from the bucket</li></ul><p>Let’s code this function :</p><h4><strong>Step 1: Setup S3 Object</strong></h4><p>Here, First, i have to import S3 and then create an S3Config Object with That variables</p><pre>import S3 from &#39;aws-sdk/clients/s3&#39;;<br><br>const REGION = process.env.S3_REGION;<br>const BUCKET_NAME = process.env.BUCKET_NAME;<br>const ACCESS_KEY = process.env.ACCESS_KEY;<br>const SECRET_KEY = process.env.SECRET_KEY;<br>const URL_TIMEOUT = 1200; // In Seconds<br><br>const S3Config = new S3({<br>  region: REGION,<br>  accessKeyId: ACCESS_KEY,<br>  secretAccessKey: SECRET_KEY,<br>  signatureVersion: &#39;v4&#39;<br>});</pre><h4>Step 2: Create Get a Pre-signed Url for uploading the Object Function</h4><p>This function will take three parameter folder path, filename, and file extension. A folder Path is a path where we want to store the file. After that, we need Content-Type based on File Extension. Here, I made a helper function that will return content-type based on file extension.</p><pre>const getPresignedUrlForUpload = async (folderPath, filename, fileExtn) =&gt; {<br>  let uploadURL = &#39;&#39;;<br>  let contentType = MimeTypesHelper.mimeTypes[fileExtn]; // Function which return ContentType based on File Extensions<br>  let uploadPath = `${folderPath}/${filename}${fileExtn}`;<br><br>  const uploadParams = {<br>    Bucket: BUCKET_NAME,<br>    Key: uploadPath,<br>    ContentType: contentType,<br>    Expires: URL_TIMEOUT<br>  };<br><br>  try {<br>    uploadURL = await S3Config.getSignedUrlPromise(&#39;putObject&#39;, uploadParams);<br>  } catch (error) {<br>    return {<br>      error: true,<br>      message: error.message<br>    };<br>  }<br><br>  return {<br>    error: false,<br>    data: {<br>      url: uploadURL,<br>      fileName: uploadPath<br>    }<br>  };<br>}</pre><h4>Step 3: Create Get a Pre-signed Url to view the Object Function</h4><p>This function will take only one parameter file path. A file path is a path that we got in earlier in step 2. We need to pass that file path here and it will return a view link for a particular object.</p><pre>const getPresignedUrlForView = async (filepath) =&gt; {<br>  let url = &quot;&quot;;<br><br>  const params = {<br>    Bucket: BUCKET_NAME,<br>    Key: filepath,<br>    Expires: 60,<br>  };<br><br>  try {<br>    url = await S3Config.getSignedUrlPromise(&quot;getObject&quot;, params);<br>  } catch (error) {<br>    return {<br>      error: true,<br>      message: error.message,<br>    };<br>  }<br><br>  return {<br>    error: false,<br>    data: {<br>      url: url,<br>      fileName: filepath.split(&quot;/&quot;)[-1],<br>    },<br>  };<br>};</pre><h4>Step 4: Create Delete Object Function</h4><p>This function will take only one parameter file path. A file path is a path that we got in earlier in step 2. We need to pass that file path here and it will be the file on that path.</p><pre>const deleteFile = async (filepath) =&gt; {<br>  const params = {<br>    Bucket: BUCKET_NAME,<br>    Key: filepath,<br>  };<br><br>  try {<br>    const checkFile = await checkFileExistOrNot(filepath);<br>    if (!checkFile) return;<br>    await S3Config.deleteObject(params).promise();<br>    return;<br>  } catch (err) {<br>    throw new Error(&quot;File not Found ERROR : &quot; + err);<br>  }<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*8ZBzINRnFNnP3Y-NZV-5rQ.gif" /></figure><p><em>That’s it for this article! I hope you enjoyed it, and leave a few claps if you did. Follow me for more Flutter &amp; Web Development articles and comment for any feedback you might have about this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64fef4feaf6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mobioxy/securing-dynamic-assets-with-aws-s3-64fef4feaf6e">Securing Dynamic Assets with AWS S3</a> was originally published in <a href="https://medium.com/mobioxy">Mobioxy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>