<?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[COOX Tech - Medium]]></title>
        <description><![CDATA[Team, Technology &amp; Data Science behind COOX Company - Medium]]></description>
        <link>https://medium.com/coox-tech?source=rss----dd8845c8cdef---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>COOX Tech - Medium</title>
            <link>https://medium.com/coox-tech?source=rss----dd8845c8cdef---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:51:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/coox-tech" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deep dive into React Native’s New Architecture]]></title>
            <link>https://medium.com/coox-tech/deep-dive-into-react-natives-new-architecture-fb67ae615ccd?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb67ae615ccd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Atharva  Patil]]></dc:creator>
            <pubDate>Sat, 22 Jan 2022 14:34:34 GMT</pubDate>
            <atom:updated>2022-01-22T14:34:34.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLDFa6irbp-lvYUoQBvWnw.png" /></figure><p>The React Native team has announced that the new architecture will be rolled out in 2022. Checkout their full blog <a href="https://reactnative.dev/blog/2022/01/21/react-native-h2-2021-recap">here</a>.</p><blockquote>“2022 is going to be the year of the <strong>New Architecture in open source</strong>”</blockquote><p>Since the release is just around the corner, this is a good time to understand what changes are taking place under the hood and how they might affect your React Native App.</p><p>This article aims to cover the most important changes bought by the re-architecture:</p><ol><li>JavaScript Interface(JSI)</li><li>Fabric</li><li>Turbo Modules</li><li>CodeGen</li></ol><h3>Current Architecture</h3><p>Before we get to the new architecture, let’s recap how the current one works.</p><p>Please note that I am only covering points that are relevant to understanding this blog, If you want to learn more about the current architecture, you can checkout <a href="https://betterprogramming.pub/react-native-under-the-hood-281df5f548f"><em>this blog</em></a><em> by Bianca Dragomir.</em></p><h4>In a nutshell:</h4><p>When you run a RN app, all you JavaScript code is bundled together into a package called the JS Bundle. The Native Code is kept separately.</p><p>The Execution of React Native apps happens over three threads:</p><p>1) The JavaScript thread: used by the JS Engine, to run the JS Bundle</p><p>2) The Native/UI thread: used to run the Native Modules and to handle operations like UI Rendering, user gesture events etc.</p><p>3) Additionally there is a 3rd thread called the shadow thread, which is used to calculate the Layout of Elements before rendering them on the host screen</p><p>The Communication between the JS and Native Threads is carried over an entity called the bridge. When sending data through the bridge it has to be batched(optimized) and serialized as JSON. This bridge can only handle asynchronous communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0LTWA_egTnRLRlqXoRUymg.png" /></figure><p><em>Some important terms:</em></p><p>JavaScriptCore:<em> It is the name of a JavaScript Engine, which is used by React Native to execute JS code.</em></p><p>Yoga:<em> It is the name of a Layout engine, which is used to calculate positions of UI elements for the user’s screen.</em></p><h3>1. JavaScript Interface (JSI)</h3><p>In the current architecture, React Native uses the Bridge Module to make communication possible between the JS and Native threads. Every time data is sent across the bridge, it has to be serialized as JSON. When the data is received on the other side it must be decoded as well.</p><p>This means that the JavaScript and Native worlds are unaware of each other <em>(ie. the JS thread cannot directly call a method on the Native thread)</em></p><p>Another important point to note is; messages send over the bridge are asynchronous in nature, which is a good thing for most use cases, but there are certain instances when JS code and native code needs to be in sync.</p><h4>Let’s take an example to better understand the bridge:</h4><p>If the JavaScript thread needs access to some native modules (eg. Bluetooth), it will need to send a message to the native thread. The JS thread will send a serialized JSON message to the bridge. The bridge will optimize this message and send it over to the native thread. The message will be decoded on the native thread, and eventually the required native code will be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R23YGUmEok50UR77u_UZAw.png" /><figcaption>1) JS thread prepares message for the Native Thread<br>2) It is serizlized as JSON before sending across the bridge<br>3) It is decoded when recieved on the other end of the bridge<br>4) Then the native thread executes the required native code</figcaption></figure><p>However, in the New Architecture, the bridge is going to be replaced with a module called <strong><em>JavaScript Interface</em></strong>, which is a lightweight, general-purpose layer, written in C++ that can be used by the JavaScript engine to directly invoke/call methods in the native realm.</p><h4><strong><em>What does general-purpose mean?</em></strong></h4><p>The current architecture uses the JavaScriptCore Engine. The bridge is only compatible with this particular engine. However, this is not the case for JSI. The JavaScript Interface will be decoupled from the Engine, which means that the new architecture enables the use of other JavaScript Engines like Chakra, v8, Hermes etc. Hence the term “<em>general-purpose”</em>.</p><h4><strong>How can JSI enable JavaScript to directly call native methods?</strong></h4><p>Through the JSI, Native methods will be exposed to JavaScript via C++ Host Objects. JavaScript can hold a reference to these objects. And can invoke the methods directly using that reference. This is similar to the web, where JavaScript code can hold a reference to any DOM element, and call methods on it. For Example: when you write:</p><blockquote>const container = document.createElement(‘div’);</blockquote><p>Here, the container is a JavaScript variable, but it holds a reference to a DOM element which was probably initialized in C++. If we call any method on the “container” variable, it will in turn call the method on the DOM element. The JSI will work in a similar way.</p><p>Unlike the bridge, the JSI will allow JavaScript code to hold a reference to Native Modules. And through the JSI, JavaScript can call methods on this reference directly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZqdD2LVpbGrNdJZ0WqY5A.png" /><figcaption>1) JavaScript has a direct reference to a native module<br>2) It calls a method on this native module, via the JavaScript Interface</figcaption></figure><p>To Sum it up, JSI will enable the use of other JavaScript Engines &amp; it will allow for complete interoperability between the threads, the JavaScript code could communicate with the native side directly from the JS thread. This will eliminate the need to serialize JSON messages and will fix the congestion and asynchronous issues on the bridge.</p><p>Another big advantage of the JSI is that it is written in C++. With the power of C++ React Native can target large number of Systems like Smart TVs, Watches etc.</p><h3>2. Fabric</h3><p>Fabric is the rendering system, which will replace the current UI Manager.</p><p>In order to understand the advantages of Fabric, first let’s look at how UI is currently rendered in React Native:</p><p>When your app is run, React executes your code and creates a ReactElementTree in JavaScript. Based on this tree, the Renderer creates a ReactShadowTree in C++.</p><p>This shadow Tree is used by the Layout Engine to calculate positions of UI elements for the host screen. Once the results of Layout calculation are available, the shadow tree is transformed into HostViewTree, which comprises of Native Elements. <em>(For example: The ReactNative &lt;View/&gt; element will be translated into ViewGroup in Android &amp; UIView in iOS respectively)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5a-rvja1slxMZH1_Zunxtg.png" /><figcaption>ReactElementTree (JavaScript) -&gt; ReactShadowTree(C++) -&gt; HostViewTree(Native)</figcaption></figure><h4><strong>Problems with this approach:</strong></h4><p>As we know, all the communication between threads happens over the bridge. Which means slow transfer rates, and unnecessary copying of data.</p><p>For Example: If a ReactElementTree Node happens to be an &lt;Image/&gt;, then the consequent node of the ReactShadowTree will also be an image. But this data will have to be duplicated and stored separately in both the nodes.</p><p>That’s not all. Since the JS and UI threads are not in sync, there are certain use cases when your app can seem laggy as it drops frames. (Example: Scrolling through a FlatList with a huge list of data)</p><h4><strong>What is Fabric?</strong></h4><p>According to the official <a href="https://reactnative.dev/docs/fabric-renderer">ReactNative documentation</a>,</p><blockquote>“Fabric is React Native’s new rendering system, a conceptual evolution of the legacy render system”</blockquote><p>As we have seen in the JSI section of this article, the JavaScript Interface will directly expose native methods to JavaScript, which also includes UI methods. As a result of this, the JS and UI thread can be in sync. This will improve performance for lists, navigation, gesture handling etc.</p><h4>What are the benefits of Fabric?</h4><p>With the new rendering system, user interactions such as scrolling, gestures etc can be prioritized to be executed synchronously in the main thread or native thread. While other tasks such as API requests will be executed asynchronously.</p><p>That’s not all. The new Shadow Tree will be immutable, and it will be shared between the JS and UI threads, for allowing straight interaction from both ends.</p><p>As we have seen, in the current architecture React Native has to maintain two hierarchies/DOM nodes. But since the shadow tree will now be shared among realms, it will help with reducing memory consumption as well.</p><h3>3. Turbo Modules</h3><p>In the current architecture, all the Native Modules used by JavaScript (e.g. Bluetooth, Geo Location, File Storage etc) have to be initialized before the app is opened. This means, even if the user doesn’t require a particular module, it still has to be initialized at start-up.</p><p>Turbo Modules are basically an enhancement over these old Native modules. As we have seen in the previous part of this article, now JavaScript will be able to hold reference to these modules, which will allow JS Code to load each module only when it is required. This will significantly improve start-up time for ReactNative apps.</p><h3>4. CodeGen</h3><p>All this talk of Turbo Modules and Fabric sounds promising, but JavaScript is a Dynamically typed language, and JSI is written in C++, which is a Statically Typed Language. Consequently, there is a need to ensure smooth communication between the two.</p><p>That’s why the new architecture will also include a static type checker called CodeGen.</p><p>By using the typed JavaScript as the source of truth CodeGen will define interface elements used by Turbo Modules and Fabric. It will also generate more native code at build time, instead of run time.</p><h3>Summary</h3><p>If we combine all the changes, the new architecture will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSQREEbL1-alhSP-fH4Nxg.png" /></figure><p>Here the key highlights are:</p><p>• Bridge will be replaced by JSI</p><p>• Ability to swap the JavaScriptCore with other Engines</p><p>• Complete Interoperability between all threads</p><p>• Web-like Rendering system</p><p>• Time sensitive tasks can be executed synchronously</p><p>• Lazy Loading of Turbo Modules</p><p>• Static Type Checking for compatibility between JS and Native Side</p><p>We can be certain that this new structure will give React Native some powerful improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb67ae615ccd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/deep-dive-into-react-natives-new-architecture-fb67ae615ccd">Deep dive into React Native’s New Architecture</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 things I learned as a Software Developer]]></title>
            <link>https://medium.com/coox-tech/7-things-i-learned-as-a-software-developer-3880e0df72ae?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/3880e0df72ae</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[experience]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[1-year]]></category>
            <dc:creator><![CDATA[Vikrant Bhat]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 06:36:19 GMT</pubDate>
            <atom:updated>2020-09-21T06:36:18.963Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*O8ItZ34gZUdWkKC8PCe7Sg.png" /></figure><p>Last week marked my first year as a Software Developer 🎉</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F14udF3WUwwGMaA%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fhappy-movie-dancing-14udF3WUwwGMaA&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2F14udF3WUwwGMaA%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="353" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12788fc626a905e24f4ac7841387965/href">https://medium.com/media/f12788fc626a905e24f4ac7841387965/href</a></iframe><p>I learned a lot of things, but the following 7 stick out. My hope is that at least one of them proves useful in your journey🎢.</p><p>1. <strong>Take notes</strong> ✏️<br>Everyone forgets things. You might have to revisit the StackOverflow solution or a blog that helped you understand a certain concept. Save yourself some time and create a noting system and start writing down helpful resources, advice from managers, how you solved a problem, etc. <br>I personally started noting down links to important resources on an excel sheet (let me know if you have a better workflow!) and it has definitely saved me some googling and re-research time.</p><p>2. <strong>Know the WHY</strong> ⍰<br>Don’t just copy/paste the code without understanding what it does. It might solve your problem at hand, but you will have that knowledge gap moving forward. <br>You don’t want massive technical knowledge debt 5 years down the road!</p><p>3. <strong>Speak Up for Yourself</strong> 🗣<br>No one knows what you need except for you — so don’t expect your managers to read your 🧠. Need more support? Ask for it. Have some ideas? Discuss.</p><p>4. <strong>Mentor Others</strong> 👥<br>You don’t have to wait until you’re mid-level to start teaching or helping others (Even if you teach one thing that stays with them, that is mentoring! — to some, it might sound like a stretch, but it’s good enough to get you started). Others who are a notch or two below your level will benefit from your knowledge. Not only that, but teaching is a great way to solidify your existing skills. 💪🏻</p><p>5. <strong>Ask Questions</strong> ⁉️<br>Don’t be the dev who asks questions every 5 minutes without Googling beforehand. But also don’t be the dev who holds up a feature because they were stuck on a problem and waited 2 days to ask for help.<br>There are no 👏🏻stupid👏🏻questions👏🏻</p><p>6. <strong>Have a Hobby</strong> ⚽️<br>No matter how much coffee you’ve had, your 🧠 isn’t meant to code 24/7. Give your mind rest and space to be creative by doing other activities you enjoy. Otherwise, risk burnout. Besides, having other interests can make you more fun to work with.</p><p>7. <strong>Don’t Take Things Personally</strong> 🙃<br>You are not your code. Learn to view it as temporary. As part of a team, you’ll see it change over time for reasons that have nothing to do with your abilities — the codebase grows, business requirements change, code reviews happen, etc.</p><p>I started with <a href="http://reactjs.org/"><em>React</em></a> on day one, not knowing much about it. But today after a year I can confidently say that I have worked with awesome Javascript technologies &amp; tools ranging from — <em>ReactJS, ReactNative, NodeJS, GatsbyJS, Jest …. firebase, AWS, netlify, vercel</em> and countless others.</p><blockquote>No matter what gets thrown at me, I’ll strive to find a solution for it. After all thats what it means to be a Problem Solver aka Software Developer :)</blockquote><p>I would also like to thank my mentors <a href="https://www.linkedin.com/in/akshatgupta10/">Akshat Gupta</a> &amp; <a href="https://www.linkedin.com/in/rajatjohri007/">Rajat Johri</a> for giving me this wonderful opportunity. Your vision and determination in your respective fields of expertise has given me a unique perspective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3880e0df72ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/7-things-i-learned-as-a-software-developer-3880e0df72ae">7 things I learned as a Software Developer</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write CSV into Amazon S3 bucket without storing it on a local machine.]]></title>
            <link>https://medium.com/coox-tech/write-csv-into-amazon-s3-bucket-without-storing-it-on-a-local-machine-fe729051dac4?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/fe729051dac4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Sudhanshu Sharma]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 07:00:37 GMT</pubDate>
            <atom:updated>2020-09-20T07:00:37.529Z</atom:updated>
            <content:encoded><![CDATA[<p>Due to the increasing need for analytics in every company today, exporting data to CSV is a very important feature in apps today. So in this article, I will put you through how to easily generate CSV with Node.js and csvjson and upload it to AWS S3.</p><p>To upload files to S3, we will need the aws-sdk express csvjsonpackage from npm:</p><pre>npm i aws-sdk express csvjson</pre><p>Now we can start writing our actual code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0a6d02d92ce9f2190a82b2f925a6ad4/href">https://medium.com/media/a0a6d02d92ce9f2190a82b2f925a6ad4/href</a></iframe><p><strong>Each header field specification:</strong></p><p>1.Bucket: My Bucket name on the S3 server.</p><p>2.Key: My file path in which my CSV file will be save.</p><p>3.Body: Content of my CSV file.</p><p>4.ContentType: We will be using ‘text/csv’.</p><p>S3 upload method returns error and data in callback, where the data field contains location, bucket and key of uploaded file. For complete API reference, refer their official <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property">docs</a>.</p><p>If you don’t get any error in the above snippet, your bucket should have the file.</p><p>I hope you found this post useful and please do let me know in case of any question or query. If you like this post, you can clap for it or follow me on <a href="https://medium.com/@sudhanshu__coder">Medium</a> for my latest posts or on <a href="https://twitter.com/sudhanshu_coder">Twitter.</a></p><blockquote>GitHub: <a href="https://github.com/sudhanshu647/upload_csv">Checkout the complete code here</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe729051dac4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/write-csv-into-amazon-s3-bucket-without-storing-it-on-a-local-machine-fe729051dac4">Write CSV into Amazon S3 bucket without storing it on a local machine.</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create and Run Scheduled Jobs with Node.js]]></title>
            <link>https://medium.com/coox-tech/create-and-run-scheduled-jobs-with-node-js-8e54a8750492?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/8e54a8750492</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[cron]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-cron]]></category>
            <dc:creator><![CDATA[Sudhanshu Sharma]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 18:29:34 GMT</pubDate>
            <atom:updated>2020-07-05T17:11:52.147Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wanted to do specific things on your application server at certain times without having to manually run them yourself? This is where scheduled tasks come in handy.</p><p>In this article, we’ll look at how to create and use Cron jobs in Node applications. To do this, we’ll make a simple application that automatically send email from the server. Another advantage of Cron jobs is that you can schedule the execution of different scripts at different intervals from your application.</p><blockquote><em>GitHub: Checkout the complete code </em><a href="https://github.com/sudhanshu647/cron-jobs"><em>here</em></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*pcHAhlF3V0KHQE9EDkMY_Q.png" /></figure><h3>Getting Started</h3><p>In this article, we would be creating a cron job to send emails. Create a simple Node.js project by running the following command in a terminal or bash.</p><pre>mkdir cron-job<br>cd cron-job<br>npm init<br>touch index.js</pre><h4>Install the following dependencies.</h4><pre><em>npm i express node-cron nodemailer</em></pre><p>express - powers the webserver</p><p>node-cron - task scheduler in pure JavaScript for node.js</p><h4>In <em>index.js </em>file, import the above dependencies.</h4><pre>const cron = require(&#39;node-cron&#39;);<br>const express = require(&#39;express&#39;);<br>const nodeMailer = require(&#39;nodemailer&#39;);</pre><p>We will now create a simple Node server by adding:</p><pre>app = express();<br>const port = 3000<br>......<br>......</pre><pre>app.listen(port, () =&gt;<br> console.log(`Server running at <a href="http://localhost:${port}`)">http://localhost:${port}`)</a>);</pre><p>To see how this module works, add the following to your index.js file which displays a message every minute:</p><pre>// schedule tasks to be run on the server<br>cron.schedule(&quot;* * * * *&quot;, function() {<br>  console.log(&quot;Running a task every minute&quot;);<br>});</pre><p>Now, when you run the server, we get the following result:</p><pre>Output<br>Server running at <a href="http://localhost:${port}`)">http://localhost:</a> 3000</pre><pre>Running a task every minute<br>Running a task every minute</pre><p>You have a task running every minute. Stop the server with CTRL+C.</p><p>Once that is done, update the index.js file to add a section that defines the mailer and sets the username and password for a Gmail account:</p><pre>const cron = require(&#39;node-cron&#39;);<br>const express = require(&#39;express&#39;);<br>let nodemailer = require(&quot;nodemailer&quot;);</pre><pre>app = express();<br>const port = 3000;</pre><pre>// create mail transporter<br>let transporter = nodemailer.createTransport({<br>service: &#39;gmail&#39;,<br>auth: {<br>   user: &#39;your_email@gmail.com&#39;,<br>   pass: &#39;your_password&#39;<br>    }<br>});</pre><p><strong>Warning</strong>: You will need to temporarily allow non-secure sign-in for your Gmail account if you’d like to use it for testing purposes <a href="https://myaccount.google.com/security">here</a>. For production applications, configure a specific secure Email account and use those credentials.</p><p>Then add the task to send the messages every minute:</p><pre>cron.schedule(&quot;* 01 * * *&quot;, function () {<br>     console.log(&quot;Runnig a task every minute&quot;);</pre><pre>      let mailOptions = {<br>          from: &quot;support@gmail.com&quot;,<br>          to: &quot;any_user_mail@gmail.com&quot;,<br>          subject: `Cron job`,<br>          text: `Hi there, this email was automatically sent by node cron`<br>        };</pre><pre>transporter.sendMail(mailOptions, function (error, info) {<br>         if (error) {<br>           throw error;<br>         } else {<br>           console.log(&quot;Email successfully sent by cron!&quot;);<br>         }<br>       });<br>});</pre><pre>app.listen(port, () =&gt; <br>console.log(`Example app listening at <a href="http://localhost:${port}`)">http://localhost:${port}`)</a><br>);</pre><p>Now, when you run the server using the command node index.js , you get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*q8ryflbIjk-BJIgXQ59u7w.png" /><figcaption>Output</figcaption></figure><h3>CONCLUSION</h3><p>In this article, you used node-cron to schedule jobs in your Node.js applications.<br>If you came thus far congrats, ✌.<br>Surely, you’ve got questions or issues as you went through this tutorial, kindly drop your comments and you’d be responded to ASAP.<br>Once again thanks for reading, Clap, and share!👌</p><blockquote><em>GitHub: Checkout the complete code </em><a href="https://github.com/sudhanshu647/cron-jobs"><em>here</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e54a8750492" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/create-and-run-scheduled-jobs-with-node-js-8e54a8750492">Create and Run Scheduled Jobs with Node.js</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux-persist (v6) in detail (React)]]></title>
            <link>https://medium.com/coox-tech/redux-persist-v6-in-detail-react-5ef75fcf99b1?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/5ef75fcf99b1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[persistence]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Vikrant Bhat]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 12:57:35 GMT</pubDate>
            <atom:updated>2020-07-04T22:14:27.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*loZ_vyZzMUoEKhOv.gif" /></figure><p>Whenever you reload your app, the javascript process has nothing in memory. You will have to re-initialize state, and maybe set some basic state based on the url (if you are in a browser). Though usually this is what you want but there are many use cases where you might want to persist your redux state even when you reload your browser window.</p><p>This idea of persisting state across refresh in web applications that use redux for global state management can be achieved using the <a href="https://www.npmjs.com/package/redux-persist">redux-persist</a> npm package.</p><p>The complete redux-store or some specific part of it can be persisted in the browser <strong><em>localstorage</em></strong> easily!</p><p>A very common use case for implementing redux-persist in 2020 is:</p><blockquote><strong><em>Offline First.</em></strong><em> Many users may not have stable internet connection. Persistence is the first step of offline support.</em></blockquote><p>Okay so that’s it for the introduction, now let’s set up redux-persist in our react-redux application.</p><p><em>Check </em><a href="https://medium.com/coox-tech/how-to-setup-redux-with-react-2020-adb8cad90234"><em>this</em></a><em> out for setting up a react-redux app or clone this </em><a href="https://github.com/bhatvikrant/react-redux-boilerplate"><em>repo</em></a></p><h3>Step 1 — Install redux-persist</h3><pre>npm install redux-persist</pre><p>or</p><pre>yarn add redux-persist</pre><h3>Step 2 — Configure redux-store</h3><p>The <em>persistConfig</em> object needs <strong>key</strong> and <strong>storage</strong> to work properly since they are mandatory, but it can also take some other key value pairs for more customization, some of them are:</p><blockquote><strong><em>Note</em></strong><em>: if you are using react native then your </em>persistConfig<em> will look like this ( </em><a href="https://github.com/rt2zz/redux-persist#v6-upgrade"><em>see docs</em></a><em>):</em></blockquote><blockquote><em>import AsyncStorage from &quot;@react-native-community/async-storage&quot; const persistConfig = { key: &quot;root&quot; , storage: AsyncStorage, }</em></blockquote><h3>Step 3 — Wrap your root component with <a href="https://github.com/rt2zz/redux-persist/blob/master/docs/PersistGate.md">PersistGate</a></h3><p>If you are using react, wrap your root component (Top level component) with PersistGate. This delays the rendering of your app’s UI until your persisted state has been retrieved and saved to redux.</p><blockquote><strong><em>NOTE</em></strong><em> the </em><em>PersistGate&#39;s loading prop can alse be null, or any react instance, e.g. </em><em>loading={&lt;Loading /&gt;} i.e it can be any react component, so you can add your custom loader as a component here. If null is provided as a value then it simply loads nothing until persisted state is retrieved. (Don&#39;t worry if you don&#39;t have a custom loader yet, it hardly takes fraction of a second to retrieve a simple redux state)</em></blockquote><p>Congratulations! You have successfully completed the setup of redux-persist in your react-app! It was fairly easy, wasn’t it? Let me know your thoughts on <a href="https://twitter.com/vikrantbhat1022">Twitter</a></p><h3>Additional resources</h3><ul><li>Check out <a href="https://www.freecodecamp.org/news/how-to-use-redux-persist-when-migrating-your-states-a5dee16b5ead/">this</a> great article to know how you can do versioning in your persisted localstorage using redux-persist. This usually comes in handy when you make some big changes in your redux state and its not compatible with the previously saved localstorage in production, so redux-persist has this good to have feature for versioning built in.<br> &gt;</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/0*nu9fI-IlDvL-Jgv0" /></figure><ul><li><a href="https://github.com/rt2zz/redux-persist#readme">Docs</a></li><li><a href="https://github.com/rt2zz/redux-persist#api">API</a></li><li><a href="https://medium.com/coox-tech/how-to-setup-redux-with-react-2020-adb8cad90234">How to setup Redux with React (2020)</a></li></ul><p><em>Originally published at </em><a href="https://underreacted.netlify.app/redux-persist/"><em>https://underreacted.netlify.app</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ef75fcf99b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/redux-persist-v6-in-detail-react-5ef75fcf99b1">Redux-persist (v6) in detail (React)</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a progressive web app(PWA) and how to convert your react native app into a PWA using expo.]]></title>
            <link>https://medium.com/coox-tech/what-is-a-progressive-web-app-pwa-and-how-to-convert-your-react-native-app-into-a-pwa-using-expo-11540ff116a?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/11540ff116a</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[pwa-for-ecommerce]]></category>
            <dc:creator><![CDATA[Karan Balodi]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 07:56:09 GMT</pubDate>
            <atom:updated>2020-06-20T07:56:09.487Z</atom:updated>
            <content:encoded><![CDATA[<p>A progressive web app is a website that can be installed on the user device and can be used offline. The idea of a PWA was introduced by Steve Jobs in 2007 but it only came into existence when Google introduced PWA in 2015 which uses modern web features like service workers and web app manifests. Modern websites can easily be converted into a PWA and can be used in any browser. Have you noticed these prompts and tabs when you visit Twitter ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUenBOO1BElfmj57Vrke3Q.png" /></figure><p>If the answer is yes, you are already familiar with PWAs and you have used one before.</p><h4>So what are the benefits of PWA? Why companies like Twitter, Uber, Spotify and Flipkart are using PWA?</h4><ul><li>They are faster.</li><li>They are responsive and work with different screen sizes.</li><li>They work offline.</li><li>They behave like native apps and provide features like push notifications etc.</li><li>You have to maintain a single codebase for iOS , web and Android.</li><li>Progressive web apps has proven to increase user engagement by 70%.</li></ul><h4>Requirements of an application to be considered a PWA.</h4><ul><li>Your website must be served using HTTPS.</li><li>It should be installable on any device.</li><li>It should have an offline page.</li><li>It should have a manifest file and a service worker</li></ul><h3>Progressive web app with expo.</h3><p>Let us first setup our project with expo. Fire up your terminal and use the following command to install expo cli and initialise your project with expo.</p><pre>npm install — global expo-cli<br>expo init my-pwa</pre><p>Choose a blank template and now we are good to move forward. Make a navigation.js file in the root of your directory and now you can start making a beautiful UI and navigator for your project using react native. I will use a simple design for this demo and will share my project on GitHub.</p><p>Once you are done with the design you can run npm start from your working directory and can choose a device to run your project on. This is the resulting application on my iOS simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*xt1L-Z3I7p2GxkNLfDdqNw.png" /></figure><p>To define our web specific design or android specific design we can make use of Platform module provided by React native to detect the Operating System on which the app is running. Below code snippet explains how you can use this module.</p><pre>...<br>import {Platform} from ‘react-native’<br>...<br>functions App(){<br>...<br>if(Platform.OS === &quot;web&quot;){<br>//do something<br>}<br>else if (Platform.OS === &quot;android&quot;){<br>//do something<br>}<br>...<br>}</pre><p>Now that we know how to design and target different platforms we are one step closer to our PWA. Expo mainly does the heavy lifting for us here, all the apps created with expo are automatically progressive web apps. It provides us with offline support and service worker which are two of the four conditions required by a PWA. To add manifest properties we can make the following changes to our app.json file.</p><pre>“web”: {<br>   “backgroundColor”: “#ffffff”,<br>   “description”: “This is a demo app”,<br>   “display”: “standalone”,<br>   “themeColor”: “#008080”,<br>   “splash”: {<br>   “image”: “./assets/images/splash.png”,<br>   “resizeMode”: “contain”,<br>},</pre><p>You can define more properties which depends on the application you are working on. Do checkout this <a href="https://web.dev/add-manifest/">page</a> for more information. Now from your terminal use this command.</p><pre>expo start --web</pre><p>This will create a web-build folder in the root of your project.</p><p><strong>Congratulations 🎉</strong> you have created your first Progressive web app. You can now deploy your app using Netlify and don’t forget to set published directory as web-build. To check if your app is a PWA or not, you can use lighthouse and check if you have a green mark on PWA badge or not and you can also see an install icon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_hQI5acTzcJPmEytRdn9g.png" /></figure><h3><strong>All good things come with a price.</strong></h3><p>Yes there are a certain points to keep in mind and extra code we have to write while using react native for web. Few of the core modules and Api’s are not supported by react native web and you may have to look for alternate implementations like the alert api and modal. While converting your existing app into a pwa you may also come across an issue like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pdVB_UarEVlARRkFj3P1qw.png" /></figure><p>This issue appears in your project when a particular type of module does not support web platform. Here the tooltip module I used is not able to load on the web, to solve these type of issues you can specify under your web property in app.json to ignore this module when building the project for web.</p><pre>“web”:{<br>  ...//manifest properties defined above<br>   &quot;build&quot;:{<br>     &quot;babel&quot;:{<br>       &quot;include&quot;:[module name]<br>     }<br>   }<br>}</pre><h3><strong>Conclusion</strong></h3><p>React native and expo makes the development of PWA’s really easy. A few modules and functionalities are not supported for web but these no’s are decreasing everyday, modules are being build and tested on three platforms now i.e Android, iOS and web which explains that this technology will be greatly used in the future as well to increase user engagement.</p><p>In this article we successfully developed a progressive web app using react native and expo. If you have any questions, please drop a comment or email me at balodikanu124@gmail.com and I will be happy to help you. If you found this article helpful, informative and you enjoyed following along, clap and share with your friends.</p><p>You can check the full code from <a href="https://github.com/karanb1/my-pwa">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11540ff116a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/what-is-a-progressive-web-app-pwa-and-how-to-convert-your-react-native-app-into-a-pwa-using-expo-11540ff116a">What is a progressive web app(PWA) and how to convert your react native app into a PWA using expo.</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Free AWS Services that you can use for bootstrapping your startup]]></title>
            <link>https://medium.com/coox-tech/free-aws-services-that-you-can-use-for-bootstrapping-your-startup-e6ab3ce2353a?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/e6ab3ce2353a</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-free-tier]]></category>
            <category><![CDATA[aws-sqs]]></category>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <dc:creator><![CDATA[Rajat Johri]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 12:08:09 GMT</pubDate>
            <atom:updated>2020-06-10T03:49:52.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>Free AWS Services that you can use to bootstrap your startup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*WKDZdqpWdKCwI_-sADtmUg.png" /></figure><h3>RDS</h3><p>AWS Relational Database Service is a managed Relational DBs service provided by AWS that makes it easy to set up, operate, and scale a relational database in the cloud. It can shed the maintenance, backup and scaling load off your shoulders and you can focus more on the development.</p><h4><em>precautions to take for billing:</em></h4><ol><li>If you have scheduled daily backups then you will be billed for every backup snapshot on the basis of your database size</li><li>in free tier you can only use db.t2.micro instance and not their customized Aurora DB which is more performant and optimized</li></ol><h3>SQS</h3><p>AWS Simple Queue Service is a managed message queues for microservices, distributed systems, and serverless applications. SQS eliminates the complexity and overhead associated with managing and operating message oriented middleware, and empowers developers to focus on differentiating work. Using SQS, you can send, store, and receive messages between software components at any volume, without losing messages or requiring other services to be available.</p><h4>precautions to take for billing:</h4><ol><li>SQS works on polling so you will be billed for polling on SQS even if there is no activity on you SQS. Meaning, higher the number of queues getting polled more will be the billing. But SQS provides 1 million free request every month so it won’t be a problem and it is also very cheap afterwards, $0.40 for 1 million requests.</li></ol><p><strong>AWS S3</strong></p><p>Amazon Simple Storage Service (Amazon S3) is a storage service that offers scalability, data availability, security, and performance. Basically it is used to store the heavy data of your website like images, videos, documents, logs etc that would be costly if you store them in the main machine where your server is hosted.</p><p>You can even host static websites on an S3 bucket. See this <a href="https://medium.com/@omgwtfmarc/deploying-create-react-app-to-s3-or-cloudfront-48dae4ce0af">blog post</a> on how to deploy your React app to Amazon Web Services S3 and CloudFront. If you are looking to add a custom domain, HTTPS and continuous deployment see this <a href="https://medium.com/dailyjs/a-guide-to-deploying-your-react-app-with-aws-s3-including-https-a-custom-domain-a-cdn-and-58245251f081">blog post</a>.</p><h4>precautions to take for billing:</h4><ol><li>You should always set cache headers for your images in S3, other wise you will be billed for every request on your S3 bucket. Put less frequently consumed data in S3 glacier storage to reduce cost.</li></ol><h3>lambda</h3><p>AWS Lambda works on <strong>Function as a service (FaaS)</strong> model, that lets you run your own code on Amazon’s servers, so you don’t need to host the code yourself. Best of all, you don’t pay a dime when your code isn’t being used. You only pay for computation time. Your code can sit on the server for months, and if you don’t touch it, Amazon doesn’t charge you.</p><p>So, you can host your REST APIs or any other event-based architecture on a lambda function and you will be charged only when there is traffic on your APIs. You can also use it to decouple some of the processing in your APIs and let lambda functions do the heavy lifting.</p><blockquote><strong>For example :</strong> Invoice generation, image processing, sending emails/ SMS etc.</blockquote><h4>precautions to take for billing:</h4><ol><li>use lambda functions to process jobs that shouldn’t be delayed and needs to be processed instantly. Do not use lambda for Complex Processing &amp; Long Processing Tasks as they can get timed out and tried again which will only increase your billing. Lambda bills you for every second your code executes and also for the system configuration done by you like RAM size, processing power etc.</li></ol><h3>SNS</h3><p>Amazon Simple Notification Service (SNS) is a highly available, durable, secure, fully managed pub/sub messaging service that enables you to decouple microservices, distributed systems, and serverless applications</p><p>use SNS if you want to implement publisher subscriber communication model. You can subscribe to SNS notifications directly from lambda or via SQS queues which in turn are polled by lambda functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*PdPypjPc_Zu6I0Yd3Tv_7g.png" /><figcaption>A typical setup for SNS, SQS and lambda</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ab3ce2353a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/free-aws-services-that-you-can-use-for-bootstrapping-your-startup-e6ab3ce2353a">Free AWS Services that you can use for bootstrapping your startup</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup Redux with React (2020)]]></title>
            <link>https://medium.com/coox-tech/how-to-setup-redux-with-react-2020-adb8cad90234?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/adb8cad90234</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Vikrant Bhat]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 15:39:59 GMT</pubDate>
            <atom:updated>2020-06-07T15:31:31.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WCDia_pScg9AVUJCeuQ99Q.png" /></figure><p><a href="https://redux.js.org/"><strong>Redux</strong></a> is probably the most<em> popular</em> <em>global state management library</em> for react by far. It eliminates the problem of <a href="https://kentcdodds.com/blog/prop-drilling"><em>prop-drilling</em></a><em> </em>and lets us manage the application state in a scalable way.</p><p>That’s enough introduction, now lets set it up in a react project!</p><p>Note: This article assumes that you understand the basics of redux. If not, please consider checking the <a href="https://redux.js.org/introduction/getting-started"><em>redux documentation</em></a> before moving forward.</p><p><strong>What is the goal of this blog?</strong></p><p>To understand and set up a classic <em>counter</em> example using redux with <a href="https://create-react-app.dev/docs/getting-started/">CRA</a>.</p><p>A bonus section awaits you at the end!</p><p><em>You can clone the final result of this blog from </em><a href="https://github.com/bhatvikrant/react-redux-boilerplate"><em>here</em></a><em>.</em></p><h3><strong>Step 1:</strong> <em>Setup your react project</em></h3><p>You can set up a react project and configure <em>babel</em>, <em>webpack </em>on your own <em>or</em> instead you can use <a href="https://create-react-app.dev/docs/getting-started/"><strong><em>create-react-app</em></strong></a> to spin up a react project, and that is indeed what we are going to do now.</p><pre>$ <strong>npx</strong> <em>create-react-app</em> my-react-redux-app</pre><p>Type the above command in your terminal / command prompt. Before this make sure that you have the latest version of <a href="https://nodejs.org/en/"><strong><em>node</em></strong></a> installed in your machine.</p><p>here, my-react-redux-app is the name of the project folder.</p><pre>$ cd my-react-redux-app</pre><pre>$ npm start</pre><p>Now change the directory <em>(cd) </em>to my-react-redux-app and then start (<em>npm start</em>) the server by typing it in your terminal / command prompt.</p><p>And <em>voila!</em> the react project is now setup. You should be able to see a screen similar to the following in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUm_CRJoXeUZif3QBJ7RsQ.png" /></figure><h3><strong>Step 2: Install redux and react-redux</strong></h3><pre>npm install redux react-redux</pre><p>or</p><pre>yarn add redux react-redux</pre><p>Now that we have installed the packages, we can proceed with the setup.</p><p><a href="https://react-redux.js.org/"><em>react-redux</em></a><em> </em>lets us connect redux with our react application easily.</p><h3><strong>Step 3: Setup Redux Store in your index.js</strong></h3><p>In this step, we will be modifying the <em>topmost</em> component in our react project hierarchy i.e the parent of all components. It is important that we do this step on the topmost component because this ensures that our redux store is available to all the components.</p><p>&gt; Our <strong>index.js </strong>will look like:</p><pre>--------------------------- <strong>index.js </strong>---------------------------<br></pre><pre>import React from &#39;react&#39;;</pre><pre>import ReactDOM from &#39;react-dom&#39;;</pre><pre>import &#39;./index.css&#39;;</pre><pre>import App from &#39;./App&#39;;</pre><pre>// REDUX</pre><pre>import<strong> { Provider } </strong>from<strong> &#39;react-redux&#39;;</strong></pre><pre>import<strong> store </strong>from<strong> &#39;./redux/store&#39;;</strong></pre><pre>ReactDOM.render(</pre><pre><strong>  &lt;Provider store={store}&gt;</strong></pre><pre>    &lt;React.StrictMode&gt;</pre><pre>      &lt;App /&gt;</pre><pre>    &lt;/React.StrictMode&gt;</pre><pre><strong>  &lt;/Provider&gt;</strong>,</pre><pre>document.getElementById(&#39;root&#39;),</pre><pre>);</pre><p>here, we have imported something called ‘‘<strong><em>Provider</em></strong>’’ from <em>react-redux.</em></p><p>‘‘<strong><em>Provider</em></strong>’’ is a component provided to us by the <em>react-redux </em>library. It wraps around our <strong>&lt;App /&gt; </strong>component. As you can see it also takes a prop called <strong><em>store </em></strong>(which is our redux store).</p><blockquote>Before moving ahead, just for the sake of keeping our project structure organized, we will create a folder named <strong>redux</strong> in our src folder, and all of our redux specific code/logic will be inside this folder. This way we are making our project easy to read, test and scalable when the need arises.</blockquote><p>&gt; Now let&#39;s create our store.</p><p>create a file named <strong>store.js </strong>inside the ./src/redux directory. (path — ./src/redux/store.js)</p><pre>------------------------- ./src/redux/<strong>store.js</strong> ---------------------<br></pre><pre>import { <strong>createStore</strong> } from &#39;redux&#39;;</pre><pre>import <strong>rootReducer</strong> from &#39;./rootReducer&#39;;<br></pre><pre>const store = <strong>createStore</strong>(<strong>rootReducer</strong>);<br></pre><pre>export default store;</pre><p>here, we use the <strong>createStore()</strong> function from redux, to create a store! (well that explanation was a bit redundant 😜 as the name itself is quiet self-explanatory). We can see that we have also imported a file called <strong>rootReducer, </strong>which we haven&#39;t created yet, so let&#39;s do that now,</p><p>&gt; create a file named <strong>rootReducer</strong> inside the same directory as the store (i.e. path — ./src/redux/rootReducer.js)</p><pre>--------------------- ./src/redux/<strong>rootReducer.js</strong> -------------------</pre><pre>import { <strong>combineReducers</strong> } from &#39;redux&#39;;<br></pre><pre><em>import counterReducer from &#39;./Counter/counter.reducer&#39;;</em></pre><pre><br>const rootReducer = <strong>combineReducers</strong>({</pre><pre>    counter: counterReducer,</pre><pre>});</pre><pre>export default rootReducer;</pre><p>here, <strong>combineReducers() </strong>as the name suggests combines various reducers into a single reducer. In redux, we can create as many reducers as we want. It is ideal to create a new reducer for every operation that doesn&#39;t depend on any other action. Since the <strong>createStore() </strong>in <em>store.js </em>can take only one reducer, hence <strong>combineReducer()</strong> is used to convert multiple reducers into one.</p><p>With this, we have successfully created our <strong>rootReducer, </strong>but we can see that we have imported a file called <strong>counterReducer</strong> which again we haven&#39;t created yet😗. I know, I know it is a bit tedious but trust me and hang in there! You just have to do this once while setting up redux. Once the setup is done, it is a very smooth experience from there onwards.</p><p><strong>counterReducer</strong> is the reducer function for the counter example that we talked of at the start. From the next step onwards we will start implementing our counter example.</p><h3>Step 4: Setup counter reducer/actions/types</h3><p>Firstly, let&#39;s create a folder called <strong>Counter </strong>in our redux folder (path — ./src/redux/Counter).</p><p>Inside the Counter folder, let&#39;s create 3 files —</p><ol><li>counter.types.js</li><li>counter.actions.js</li><li>counter.reducer.js</li></ol><p>the file names are pretty self-explanatory of what they signify. (<em>let me know if you have any confusion with this, in the comments section below</em>)</p><p>let&#39;s create our <strong>types</strong> for the counter first. We will be needing two types, one for incrementing the counter and the other for decrementing.</p><pre>--------------- ./src/redux/Counter/<strong>counter.types.js</strong> ---------------</pre><pre>export const <strong>INCREMENT</strong> = &#39;INCREMENT&#39;;</pre><pre>export const <strong>DECREMENT</strong> = &#39;DECREMENT&#39;;</pre><p>here, we export both the constants, so that they can be imported in other files.</p><p>Next, let&#39;s create <strong>actions</strong> for the counter.</p><pre>--------------- ./src/redux/Counter/<strong>counter.actions.js</strong> -------------<br></pre><pre>import { INCREMENT, DECREMENT } from &#39;./counter.types&#39;;<br></pre><pre>export const <strong>increaseCounter</strong> = () =&gt; {</pre><pre>    return {</pre><pre>        type: INCREMENT,</pre><pre>    };</pre><pre>};</pre><pre>export const <strong>decreaseCounter</strong> = () =&gt; {</pre><pre>    return {</pre><pre>       type: DECREMENT,</pre><pre>    };</pre><pre>};</pre><p>here, we import our types from <strong>counter.types.js</strong> file and pass them as types in their respective actions.</p><p>Now, let&#39;s create the <strong>reducer</strong> for our <em>counter</em> example.</p><pre>------------------ ./src/redux/<strong>counter.reducer.js</strong> ------------------<br></pre><pre>import { INCREMENT, DECREMENT } from &#39;./counter.types&#39;;</pre><pre><br>const <strong>INITIAL_STATE</strong> = {</pre><pre>    count: 0,<br>};</pre><pre>const <strong>reducer</strong> = (state = <strong>INITIAL_STATE</strong>, action) =&gt; {</pre><pre>    switch (action.type) {</pre><pre>        case INCREMENT:</pre><pre>           return {</pre><pre>             ...state, count: state.count + 1,</pre><pre>           };</pre><pre>        case DECREMENT:</pre><pre>           return {<br>              ...state, count: state.count - 1,</pre><pre>           };</pre><pre>         default: return state;</pre><pre>    }</pre><pre>};</pre><pre>export default <strong>reducer</strong>;</pre><p>here, firstly we import our types at the top. then we declare a constant called <strong><em>INITIAL_STATE </em></strong>this is going to be the default state for this specific reducer. After this, we create a function called <strong><em>reducer</em></strong> which takes two arguments — state, action. The State takes an initial value of INITIAL_STATE, and action receives any data (payload) that is passed from our action creator from <strong>counter.actions.js </strong>file.</p><p>Inside the reducer function, we use a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch"><strong><em>switch-case</em></strong></a> from javascript and inside each case, we return the updated state. We use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"><strong>spread operator (…)</strong></a> to copy the state into our new object and then add what we want to change in the state.</p><blockquote><strong><em>⚠️</em> <em>Always remember</em>: </strong>We never mutate the original state! Every time we have to make a change we return a new state object.</blockquote><p>And in the end, we export our reducer, which is then imported in the <strong><em>rootReducer.js </em></strong>file.</p><p>With this, our reducer for the counter is ready! From the next step onwards we will write some JSX to display the increment and decrement buttons on our web app.</p><h3>Step 5: JSX for increment / decrement buttons</h3><p>To demonstrate the use of redux in our web app we will have to show something on our web app. So we will be writing some basic JSX and then afterward we will connect it with our redux store.</p><p>&gt; Let&#39;s open the <strong>App.js</strong> file (path — ./src/app.js)</p><p>Replace the existing boilerplate code with the following in your App.js</p><pre>-------------------------- ./src/<strong>App.js</strong> ----------------------------</pre><pre>import React from &#39;react&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>function <strong>App</strong>() {</pre><pre>return (</pre><pre>  &lt;div className=&#39;App&#39;&gt;</pre><pre>    <strong> &lt;div&gt;Count: 0&lt;/div&gt;</strong></pre><pre><strong>     &lt;button&gt;Increase Count&lt;/button&gt;</strong></pre><pre><strong>     &lt;button&gt;Decrease Count&lt;/button&gt;</strong></pre><pre>  &lt;/div&gt;</pre><pre> );</pre><pre>}<br></pre><pre>export default <strong>App</strong>;</pre><p>here, we have just added two buttons that do nothing at the moment and we display a static count value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*DL1LzMJeozJYUW77Ji2mNw.png" /><figcaption>This is what you should be able to see in your browser</figcaption></figure><p>Now, let&#39;s connect the redux state and actions to this component in the next step.</p><h3>Step 6: Connect redux state/actions to a component</h3><p>Now that everything else is set up, the final step is to use the redux state and actions in our component.</p><pre>import React from &#39;react&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>import { <strong>connect</strong> } from &#39;react-redux&#39;;</pre><pre>import { <strong>increaseCounter</strong>, <strong>decreaseCounter</strong> } from &#39;./redux/Counter/counter.actions&#39;;</pre><pre><br>function App(props) {</pre><pre>return (</pre><pre>   &lt;div className=&#39;App&#39;&gt;</pre><pre>     &lt;div&gt;Count: {props.count}&lt;/div&gt;</pre><pre>     &lt;button <strong>onClick={() =&gt; props.increaseCounter()}</strong>&gt;Increase        Count&lt;/button&gt;</pre><pre>     &lt;button <strong>onClick={() =&gt; props.decreaseCounter()}</strong>&gt;Decrease Count&lt;/button&gt;</pre><pre>  &lt;/div&gt;</pre><pre> );</pre><pre>}</pre><pre>const <strong>mapStateToProps</strong> = (<strong>state</strong>) =&gt; {</pre><pre>return {</pre><pre>   count: state.counter.count,</pre><pre> };</pre><pre>};</pre><pre>const <strong>mapDispatchToProps</strong> = (<strong>dispatch</strong>) =&gt; {</pre><pre>return {</pre><pre>  <strong> increaseCounter: () =&gt; dispatch(increaseCounter()),</strong></pre><pre><strong>   decreaseCounter: () =&gt; dispatch(decreaseCounter()),</strong></pre><pre>  };</pre><pre>};</pre><pre>export default <strong>connect(mapStateToProps, mapDispatchToProps)(App);</strong></pre><p>here, we import the <strong>connect </strong>function from the <em>react-redux</em> library, we also import our <strong>increaseCounter</strong> and <strong>decreaseCounter </strong>actions.</p><p>The connect function is a <a href="https://reactjs.org/docs/higher-order-components.html"><strong>Higher Order Component (HOC)</strong></a><strong>, </strong>it basically takes a component and adds some more props to it and then returns the same component with newly added props. Check the last line of App.js file where we export the component, we can see that connect is being used here as follows,</p><pre>export default <strong>connect(mapStateToProps, mapDispatchToProps)(App);</strong></pre><p>connect takes two functions as arguments which are <strong><em>mapStateToProps</em></strong> and <strong><em>mapDispatchToProps</em></strong>.</p><p>Now let&#39;s see what these two functions do,</p><pre>const <strong>mapStateToProps</strong> = (<strong>state</strong>) =&gt; {</pre><pre>   return {</pre><pre>     count: state.counter.count,</pre><pre>   };</pre><pre>};</pre><pre>const <strong>mapDispatchToProps</strong> = (<strong>dispatch</strong>) =&gt; {</pre><pre>   return {</pre><pre><strong>     increaseCounter: () =&gt; dispatch(increaseCounter()),</strong></pre><pre><strong>     decreaseCounter: () =&gt; dispatch(decreaseCounter()),</strong></pre><pre>   };</pre><pre>};</pre><p><strong>mapStateToProps</strong> function as the name suggests maps the redux state to the props of the component it is declared in. So this basically adds whatever state you return from this function to your component. In our <em>counter example</em>, I have returned <strong><em>count</em></strong> from the redux state and hence now I <em>can access count from props inside my App component.</em></p><p><strong>mapDispatchToProps</strong> function does a very similar thing, but instead of adding state to props, it adds our <strong>actions </strong>to props! Whatever actions we return from this function are added to our component. And as you can see that in our example I have returned two actions i.e <strong>increaseCounter</strong> and <strong>decreaseCounter, </strong>hence we are able to access them from our props and then I release our actions on the respective button click.</p><p>With this now we have a fully functional react-redux app! If you liked the blog or have any queries, please let me know in the comments!</p><h3>BONUS: Adding redux-dev-tools to the project</h3><p>&gt; First, Download the <strong><em>chrome browser redux extension</em></strong> from <a href="https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en">here</a></p><p>&gt; Second, install the redux dev tools package from npm to your project, using the following command,</p><pre>npm install --save redux-devtools-extension</pre><p>&gt; Third, update your <strong>store.js</strong> to use the <strong>composeWithDevtools</strong> as follows,</p><pre>------------------------- ./src/redux/<strong>store.js</strong> ---------------------<br></pre><pre>import { <strong>createStore</strong> } from &#39;redux&#39;;</pre><pre>import { <strong>composeWithDevTools</strong> } from &#39;redux-devtools-extension&#39;;</pre><pre>import <strong>rootReducer</strong> from &#39;./rootReducer&#39;;<br></pre><pre>const store = <strong>createStore</strong>(</pre><pre>    <strong>rootReducer</strong>,</pre><pre>    <strong>composeWithDevTools()</strong>,</pre><pre>);<br></pre><pre>export default store;</pre><p>and that&#39;s it! Now you can access chrome dev tools for redux!</p><p>The chrome dev tools for redux looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhhRoO-hjRg7yw1FGfe2fw.png" /></figure><p><em>You can clone the final result of this blog from </em><a href="https://github.com/bhatvikrant/react-redux-boilerplate"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adb8cad90234" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/how-to-setup-redux-with-react-2020-adb8cad90234">How to setup Redux with React (2020)</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Send mail using Node.js, Express.js with Nodemailer]]></title>
            <link>https://medium.com/coox-tech/send-mail-using-node-js-express-js-with-nodemailer-93f4d62c83ee?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/93f4d62c83ee</guid>
            <category><![CDATA[gmail]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nodemailer]]></category>
            <dc:creator><![CDATA[Sudhanshu Sharma]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 19:03:18 GMT</pubDate>
            <atom:updated>2020-06-03T19:03:18.804Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="nodemailer" src="https://cdn-images-1.medium.com/max/530/1*IuofHiczqmwi1bdeSvN4fA.png" /></figure><h3>Before we start…</h3><blockquote>GitHub: Checkout the complete code <a href="https://github.com/sudhanshu647/nodejs-mailsending">here</a></blockquote><p>Let’s take a moment to review the tools we’re going to be using:</p><p><a href="https://nodejs.org/en/"><strong><em>NodeJS</em></strong></a>: We’re going to use this to run JavaScript code on the server. I’ve decided to use the latest version of Node, v12.16.3 at the time of writing.</p><p><a href="https://expressjs.com/"><strong><em>Express</em></strong></a><strong><em>: </em></strong>As per their website, Express is a “Fast, unopinionated, minimalist web framework for Node.js”.</p><p><a href="https://nodemailer.com/about/"><strong><em>Nodemailer:</em></strong></a><strong><em> </em></strong>Nodemailer is a single module with zero dependencies for Node.js, designed for sending emails.</p><p><a href="https://www.getpostman.com/docs/introduction"><strong><em>Postman</em></strong></a><strong>: </strong>A Chrome app that we’ll use to practically test our API.</p><h3>Let’s start!</h3><p>Assuming you’ve already installed <a href="https://nodejs.org/">Node.js</a>, create a directory <strong>nodemailerDemo</strong> to hold your application and make that your working directory.</p><p>Let’s npm init before installing our packages!</p><p>$ npm init</p><h3>Express Setup:</h3><p>Install Express and a few of its dependencies</p><p>$ npm install -save express body-parser .</p><p>let&#39;s install nodemailer .</p><pre>npm install nodemailer</pre><p>Then, open up your package.json file and create a command to run the server. That command will be created under the scripts section. Edit your package.jsonin the scripts section as follows:</p><pre>&quot;scripts&quot;: {   <br>       &quot;start&quot;: &quot;node ./index.js&quot;,<br>       &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  }</pre><h3>Let’s create our server</h3><p>Add this to your <strong>index.js</strong> file</p><pre>const express = require(&quot;express&quot;);<br>const bodyParser = require(&#39;body-parser&#39;);<br>const nodemailer = require(&#39;nodemailer&#39;);</pre><pre>const app = express();<br>app.use(bodyParser.json());</pre><pre>app.use(bodyParser.urlencoded({ extended: false }));</pre><pre>const route = express.Router();<br>const port = process.env.PORT || 5000;</pre><pre>app.use(&#39;/v1&#39;, route);<br>app.listen(port, () =&gt; {</pre><pre>    console.log(`Server listening on port ${port}`);</pre><pre>});</pre><p>Now run the application by below command.</p><pre>$ npm start</pre><p>Our server started on port 5000.</p><p>Next In index.js file require the nodemailer</p><pre>var nodemailer = require(&#39;nodemailer&#39;);</pre><p>nodemailer needs a transport service using which it can send emails. In this example, I am using Gmail.</p><p>inside your node.js file write</p><pre>// create reusable transporter object using the default SMTP transport</pre><pre>const transporter = nodemailer.createTransport({<br>port: 465,               // true for 465, false for other ports<br>host: &quot;smtp.gmail.com&quot;,<br>   auth: {<br>        user: &#39;youremail@gmail.com&#39;,<br>        pass: &#39;password&#39;,<br>     },<br>secure: true,<br>});</pre><p>Now we need a second configuration object where we will be configuring our email details.</p><pre>const mailData = {</pre><pre>from: &#39;youremail@gmail.com&#39;,  // sender address<br>  to: &#39;myfriend@gmail.com&#39;,   // list of receivers<br>  subject: &#39;Sending Email using Node.js&#39;,<br>  text: &#39;That was easy!&#39;<br>  html: &#39;&lt;b&gt;Hey there! &lt;/b&gt;<br>         &lt;br&gt; This is our first message sent with Nodemailer&lt;br/&gt;&#39;,<br>};</pre><h3>Attachments in Nodemailer</h3><p>We can add attachments in Nodemailer using the following main properties:</p><pre>// An array of attachments<br>        attachments: [<br>            {<br>                filename: &#39;text notes.txt&#39;,<br>                path: &#39;notes.txt<br>            },<br>         ]</pre><p>Now the last bit is actually sending the email we can do that by using the sendMail method provided by the transporter object we created above.</p><pre>transporter.sendMail(mailOptions, function (err, info) {<br>   if(err)<br>     console.log(err)<br>   else<br>     console.log(info);<br>});</pre><p>sendMail takes two argument <strong>mailOptions </strong>and a callback function which will be called when the mail is sent. The callback function will be called when either email sent successfully our an error occurred.</p><p>Before sending your email using Gmail you have to allow non-secure apps to access Gmail you can do this by going to your Gmail settings <a href="https://myaccount.google.com/lesssecureapps">here</a>.</p><p>And that’s how we send emails in node js using nodemailer and Gmail.</p><h3>Nodemailer examples</h3><p>Let’s review and test a full message created with Nodemailer.</p><p><strong><em>Example 1. First, send a text mail using postman, Now we send to, subject, text via postman post request.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*c7eEAV0_4uB3sVnV0WT_iw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*g18qpOhKpahUg-WhZHNnYw.png" /></figure><p>We just successfully send a text mail.</p><p><strong><em>Example 2. Send a text mail with image and text file attachments</em></strong></p><figure><img alt="attachmail" src="https://cdn-images-1.medium.com/max/791/1*lLeAqGbs2HmbVpMeEkKuuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*k_mkt_YxnBAcTszrazQGlg.png" /></figure><p>We just successfully send a mail with image and text file attachments.</p><h3>CONCLUSION</h3><p>We just successfully send mail using noedemailer and express.js in our application.<br>If you came thus far congrats, ✌.<br>Surely, you’ve got questions or issues as you went through this tutorial, kindly drop your comments and you’d be responded to ASAP.<br>Once again thanks for reading, Clap, and share!👌</p><blockquote>GitHub: Checkout the complete code <a href="https://github.com/sudhanshu647/nodejs-mailsending">here</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93f4d62c83ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/send-mail-using-node-js-express-js-with-nodemailer-93f4d62c83ee">Send mail using Node.js, Express.js with Nodemailer</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Sequelize for Node.js, Express.js and MySQL Applications]]></title>
            <link>https://medium.com/coox-tech/getting-started-with-sequelize-for-node-js-express-js-and-mysql-applications-e657dfa29d0a?source=rss----dd8845c8cdef---4</link>
            <guid isPermaLink="false">https://medium.com/p/e657dfa29d0a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[sequelize]]></category>
            <dc:creator><![CDATA[Sudhanshu Sharma]]></dc:creator>
            <pubDate>Sun, 24 May 2020 18:09:45 GMT</pubDate>
            <atom:updated>2020-05-24T17:55:35.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="nodejs image" src="https://cdn-images-1.medium.com/max/811/1*SEfonxxMIktyFJWwA_oTTg.png" /></figure><h3>Before we start…</h3><p>Let’s take a moment to review the tools we’re going to be using:</p><p><a href="https://nodejs.org/en/"><strong><em>NodeJS</em></strong></a>: We’re going to use this to run JavaScript code on the server. I’ve decided to use the latest version of Node, v12.16.3 at the time of writing.</p><p><a href="https://expressjs.com/"><strong><em>Express</em></strong></a><strong><em>: </em></strong>As per their website, Express is a “Fast, unopinionated, minimalist web framework for Node.js”.</p><p><a href="https://www.npmjs.com/"><strong><em>NPM</em></strong></a><strong>:</strong> for the package management (both server, frontend, and development packages). It’ll be easier to maintain one package management system, than using <em>NPM</em> and <em>Bower</em> together.</p><p><a href="https://www.postgresql.org/docs/9.5/static/index.html"><strong><em>MySQL</em></strong></a><strong>:</strong> This is a powerful open-source database that we’re going to use to store our Todos.</p><p><a href="https://sequelize.org/master/"><strong><em>Sequelize</em></strong></a><strong>:</strong> In addition, we’re going to use Sequelize, which is a database ORM that will interface with the Mysql database for us.</p><p><a href="https://www.getpostman.com/docs/introduction"><strong><em>Postman</em></strong></a><strong>: </strong>A Chrome app that we’ll use to practically test our API.</p><h3>Let’s start!</h3><p>Assuming you’ve already installed <a href="https://nodejs.org/">Node.js</a>, create a directory to hold your application and make that your working directory.</p><p>Let’s npm init before installing our packages!</p><p>$ npm init</p><h3>Express Setup:</h3><p>Install Express and a few of its dependencies</p><p>$ npm install -save express body-parser morganapp.js.</p><p>Let’s install nodemon so we can restart our app every time when we update it</p><pre>npm install nodemon</pre><p>Then, open up your package.json file and create a command to run the server. That command will be created under the scripts section. Edit your package.jsonin the scripts section as follows:</p><pre>......</pre><pre>&quot;scripts&quot;: {</pre><pre>    &quot;start&quot;: &quot;nodemon ./index.js&quot;,<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },</pre><pre>.....</pre><h3>Sequelize Setup</h3><p>For this part, we are going to require a working MySQL installation.</p><p>Next, we are going to require <a href="http://docs.sequelizejs.com/en/latest/">Sequelize</a>. This is an <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> that will interface with the MYSQL database for us.</p><p>We are going to be making use of the <a href="https://github.com/sequelize/cli">Sequelize CLI</a> package to bootstrap the project for us. It will also help us generate <a href="https://en.wikipedia.org/wiki/Schema_migration">database migrations</a>.</p><p>Let’s begin by installing Sequelize CLI package.</p><pre>$ npm install -g sequelize-cli</pre><h3>Install sequelize</h3><p>At this point, we are going to need to install the actual Sequelize package, alongside its dependencies.</p><p>Sequelize is an easy-to-use multi SQL dialect ORM for Node.js. We gonna use MySQL as our database. So let install Sequelize ORM and mysql2 dialect.</p><pre>$ sequelize init // final, Initializes project with sequelize cil</pre><p>If you inspect your directory right now, you will realize that the above command just created the directories and generated the boilerplate code. Your directory structure should now look like this.</p><pre>sequelizeSetup<br>── index.js</pre><pre>├── package.json</pre><pre>├── config</pre><pre>│   └── config.json</pre><pre>├── migrations</pre><pre>├── models</pre><pre>│   └── index.js</pre><pre>└── seeders</pre><p>Let’s consider, for example, the <strong>sequelizeSetup/models/index.js</strong> file that was autogenerated.</p><figure><img alt="config.json" src="https://cdn-images-1.medium.com/max/765/0*sk-uLgFfpuffgjiY.png" /></figure><p>In this file, we are requiring the modules we’re going to be using. Then, we’re reading the configuration specific to our current Node environment. If we don’t have a Node environment defined, we’re defaulting to development. Then, we are establishing a connection with our database, after which we read our models folder.</p><h3>Database Configurations</h3><p>Now config.json file which is located at config\config.json and update your database details.</p><figure><img alt="config.json" src="https://cdn-images-1.medium.com/max/377/0*FOqsTsYTZOt-YTdZ.png" /></figure><h3>Creating the first Model (and Migration)</h3><p>Once we have properly configured CLI config file we are ready to create our first migration. It’s as simple as executing a simple command.</p><p>We will use model:generate command. This command requires two options:</p><ul><li>name: the name of the model;</li><li>attributes: the list of model attributes.</li></ul><p>Let’s create a model named User.</p><pre>npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string</pre><p>This will generate a user.js file in the sequelizeSetup/models folder as well as a &lt;date&gt;-create-company.js migration file in the sequelizeSetup/migrations folder. &lt;date&gt; will be the date the model was generated.</p><p>The generated user.js model code is:</p><figure><img alt="user.js model" src="https://cdn-images-1.medium.com/max/601/0*dtJQgJwPVRK_RNly.png" /></figure><p>and user migration code is:</p><figure><img alt="user.js migration" src="https://cdn-images-1.medium.com/max/588/1*cSG0BE2FvCdo9zfPIBFsbQ.png" /></figure><p>When we run these migrations, the up function will be executed. It will take care of creating the table and it&#39;s associated columns for us. If, for whatever reason, we needed to rollback (undo) the migration, the down function would be executed and it would undo whatever the up function did, thus returning the our database to the same state it was in before we performed the migration.</p><p>These migrations are a representation of how we want our models to look like in the database. Sequelize automatically generates the id, createdAt and updatedAt fields for you. In addition to that, any time a model is saved, the updatedAt field is automatically updated to reflect the new update time.</p><p>With the models and migrations in place, we’re now ready to persist the models to the database by running the migrations. To do this, we run the following command:</p><pre>$ sequelize db:migrate</pre><p>This will discover the migrations in our migrations folder and execute them. If you try running the same command again, it would not execute any migrations since it’s clever enough to know that all of the current migrations have been executed.</p><h3>Creating Controllers and Routing</h3><h4>Creating User Controller</h4><p>Create a user.js file inside sequelizeSetup/controllers/. Inside this file.userController will be responsible for creating, listing, updating and deleting company.</p><p>Let create a user. <strong>sequelizeSetup/controllers/user.js</strong></p><figure><img alt="user.js controller" src="https://cdn-images-1.medium.com/max/630/0*LP6_Adslp6jUh6fK.png" /></figure><p>The above code snippet creates a new user and if successful, it returns it. If it encounters an error, it returns that error instead.</p><p>This create function is designed to be a <a href="https://expressjs.com/en/guide/routing.html">route handler</a> for whichever Express route we&#39;ll choose to attach it to. The req parameter is the incoming request from the client. The res parameter is the response we&#39;re preparing to eventually send back to the client in <em>response</em> to their <em>request</em>.</p><p>Next, we create an index.js file inside sequelizeSetup/controllers, where we&#39;re going to be exporting our controllers from. I find this helpful since it helps me consolidate my imports (require statements) from once central place.</p><p><strong>server/controllers/index.js</strong></p><pre>const user = require(&#39;./user&#39;);module.exports = {<br>       user<br>   }</pre><h3>Let’s consume the API calls with Express</h3><p>Next, we need to add an API route that maps to this functionality. Create a routesfolder inside the sequelizeSetup folder. Inside the new routes folder, create an index.jsfile. We are going to place all our routes in this index.js file. However, in a real-world application, you might want to split up your routes and place them in different folders.</p><p>Inside sequelizeSetup/routes/index.js add the following code:</p><figure><img alt="user.route" src="https://cdn-images-1.medium.com/max/630/0*khm_x10X03oNiyHJ.png" /></figure><p>This will add two new routes, a welcome route at /api and a route to create user at /api/user.</p><p>If we post some data to /api/user, we are telling our application to run the userController.create function, which will take the request object, extract the posted data and create a user. In this case, we say that the userController.create function is the POST route handler for the /api/user endpoint.</p><h3>Let’s create our server</h3><p>Create a file in the root folder and call it index.js.</p><pre>const express = require(&#39;express&#39;);</pre><pre>const logger = require(&#39;morgan&#39;);</pre><pre>const bodyParser = require(&#39;body-parser&#39;);</pre><pre><strong>// This will be our application entry. We&#39;ll setup our server here.</strong></pre><pre>const http = require(&#39;http&#39;);</pre><pre><strong>// Set up the express app</strong></pre><pre>const app = express();</pre><pre><strong>// Log requests to the console.</strong></pre><pre>app.use(logger(&#39;dev&#39;));</pre><pre><strong>// Parse incoming requests data (https://github.com/expressjs/body-parser)</strong></pre><pre>app.use(bodyParser.json());</pre><pre>app.use(bodyParser.urlencoded({ extended: false }));</pre><pre><strong>// Setup a default catch-all route that sends back a welcome message in JSON format.&quot;</strong></pre><pre>var models = require(&#39;./models&#39;);</pre><pre>const port = parseInt(process.env.PORT, 10) || 3000;</pre><pre>app.set(&#39;port&#39;, port);</pre><pre>console.log(&quot;server started on &quot;,port)</pre><pre>models.sequelize.sync().then(function () {</pre><pre>app.listen(port);</pre><pre>});</pre><pre>require(&#39;./routes&#39;)(app);</pre><pre>app.get(&#39;*&#39;, (req, res) =&gt; res.status(200).send({</pre><pre>message: &#39;Welcome to the beginning of nothingness.&#39;,</pre><pre>}));</pre><pre>module.exports = app;</pre><p>We are in the last step.</p><pre>now run the application by below command.</pre><pre>$ npm start</pre><figure><img alt="server started" src="https://cdn-images-1.medium.com/max/549/1*yrDi6ajFpOeqjUDbM4MN0Q.png" /></figure><p>our application server started on port no 3000.</p><h3>TESTING WITH POSTMAN</h3><p>Next, we open up Postman and issue a POST request to create a new user as in the image below.</p><h4>Create User: POST <a href="http://localhost:3000/api/user">http://localhost:3000/api/user</a></h4><figure><img alt="postman response" src="https://cdn-images-1.medium.com/max/967/0*bAhydvsHJAvZZSDu.png" /></figure><h3>CONCLUSION</h3><p>We just successfully setup sequelize in our application.<br>If you came thus far congrats, ✌.<br>Surely, you’ve got questions or issues as you went through this tutorial, kindly drop your comments and you’d be responded to ASAP.<br>Once again thanks for reading, Clap, and share!👌</p><blockquote>GitHub: Checkout the complete code <a href="https://github.com/sudhanshu647/sequelize-setup">here</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e657dfa29d0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coox-tech/getting-started-with-sequelize-for-node-js-express-js-and-mysql-applications-e657dfa29d0a">Getting Started with Sequelize for Node.js, Express.js and MySQL Applications</a> was originally published in <a href="https://medium.com/coox-tech">COOX Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>