<?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 Troy Moreland on Medium]]></title>
        <description><![CDATA[Stories by Troy Moreland on Medium]]></description>
        <link>https://medium.com/@graypes?source=rss-831caef304ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LAjzzuk0CJk13aPpz48dOQ.png</url>
            <title>Stories by Troy Moreland on Medium</title>
            <link>https://medium.com/@graypes?source=rss-831caef304ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:44:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@graypes/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[Checking for “empty” values in JavaScript]]></title>
            <link>https://levelup.gitconnected.com/checking-for-empty-values-in-javascript-fde88c7c69e6?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde88c7c69e6</guid>
            <category><![CDATA[conditional-statements]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 14:41:04 GMT</pubDate>
            <atom:updated>2023-01-16T00:30:21.903Z</atom:updated>
            <content:encoded><![CDATA[<p>Figuring out if a variable is empty can be tricky due to JavaScript’s “truthy” and “falsy” outcomes!</p><blockquote>“The empty vessel makes the loudest noise.” — Plato</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cszh7QmP9vbPl-0c" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Strings</h3><p>Let’s start with strings. What is the value of an empty string? The only way to know is to test the value.</p><pre>const isEmptyString = (str) =&gt; {<br>  if (str === &quot;&quot;) return true<br>  if (!!!str1.length) return true<br>  if (!str1) return true<br>  return false<br>}<br><br>console.log(isEmptyString(&quot;&quot;)) // true</pre><p>Any condition in the code above would work; however, the first &amp; second conditions may be too specific. What if the value contains some whitespace? The better solution would look like this:</p><pre>const isEmptyString = (str) =&gt; {<br>  return !str1.trim()<br>}<br>console.log(isEmptyString(&quot;&quot;))  // true<br>console.log(isEmptyString(&quot; &quot;)) // true</pre><h3>Arrays</h3><p>Arrays are the easiest to check for empty values. The quickest check would look like this:</p><pre>const isEmptyArr = (arr) =&gt; {<br>  return !!!arr.length<br>}</pre><p><em>If the “!!!” is unfamiliar, let me explain. First of all, using “!!” in front of any expression in JavaScript forces it to return true or false (Boolean) based on JavaScript’s truthy/falsy comparisons. Secondly, the “!” by itself is a “not” and, used this way, returns the opposite boolean result. Consider the following examples:</em></p><pre>const str1 = &quot;foo&quot;<br>const str2 = &quot;&quot;<br>console.log(str1)   // foo<br>console.log(!!str1) // true<br>console.log(!!!str1)// false<br>console.log(str2)   // &lt;empty string&gt;<br>console.log(!!str2) // false<br>console.log(!!!str2)// true<br><br>const num1 = 1<br>const num2 = 0<br>console.log(num1)   // 1<br>console.log(!!num1) // true<br>console.log(!!!num2)// false<br>console.log(num2)   // 0<br>console.log(!!num2) // false<br>console.log(!!!num2)// true</pre><h3>Objects</h3><p>There are numerous ways to check to see if an object is empty.</p><pre>const isEmptyObj = (obj) =&gt; {<br>  if (obj === {}) return true<br><br>  if (!Object.keys(obj).length) return true<br><br>  for (let i in obj) return false<br>  return true<br>}</pre><p>I always used the second example until I read an article by a Computer Scientist who proved the last example is the fastest (by a lot!).</p><h3>Solution</h3><p>The ultimate solution is to create a utility function that handles all “is empty” scenarios.</p><pre>const isEmpty = (val) =&gt; {<br>  if (Array.isArray(val) {<br>    return !!!val.length<br>  }<br>  if (typeof val === &#39;object&#39;) {<br>    for (let i in val) return false<br>    return true<br>  }<br>  if (typeof val === &#39;string&#39;) {<br>    return !val.trim()<br>  }<br>  throw new Error(&#39;unknown type&#39;)<br>}<br><br>console.log(isEmpty(&quot;&quot;)) // true<br>console.log(isEmpty([])) // true<br>console.log(isEmpty({})) // true</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde88c7c69e6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/checking-for-empty-values-in-javascript-fde88c7c69e6">Checking for “empty” values in JavaScript</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-World Implementation of Functional JavaScript Design Patterns]]></title>
            <link>https://levelup.gitconnected.com/real-world-implementation-of-functional-javascript-design-patterns-6547d4e68e30?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/6547d4e68e30</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 15:57:55 GMT</pubDate>
            <atom:updated>2022-09-15T19:28:00.452Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CRV_VRvdAFJbfIcD" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=medium&amp;utm_medium=referral">Shahadat Rahman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Problem Statements</h3><ul><li>I am working on a project that is using an SQL database (e.g. PostgreSQL) and the customer decides they want to move to a NoSQL database (e.g. MongooseDb). Now I have to go through my entire project to refactor everything to use this new database.</li><li>I am starting a new project. The customer wants to manage users and products. My last project had similar requirements. I can copy/paste code from my previous project but, due to the way the code was written, there are lots of changes to be made so I may be better off just starting from scratch.</li><li>I have built several projects for numerous customers and I am responsible for maintaining all of these projects. This becomes too much for me to handle alone so I hire more developers. Each customer request for fixes or features is written in their respective project. Even though I may have multiple customers asking for the same feature I end up with different implementations created by different developers. When a fix is implemented, it is likely only done in one of the projects and we may run into the same problem in our other projects in the future.</li></ul><p>These problems result in numerous negative outcomes such as inefficient use of time, inability to scale, and increased security risks, to name a few.</p><h3>Solution Overview</h3><p>As a developer, I create numerous projects with varying architectures. As I work on different projects I want to build upon my “toolkit” to increase my efficiency, reduce mistakes, and simply adhere to best practices. I have created a basic example of this toolkit that implements database integration and model management. There would certainly be more to this toolkit but hopefully, this is enough of a “real” example to get you started on building your own toolkit.</p><p>This sample code implements the Abstract Factory design pattern. The purpose of using this pattern is to adhere to the Open/Closed Principle (OCP) in SOLID. This is implemented such that our “client” will interact with our Abstract Factories rather than interacting directly with numerous Factories. Our “client” code won’t need to change when we add a new Factory. Our Abstract Factories will require minimal or no code changes to implement a new Factory.</p><p>This example has an Abstract Factory called DbStoreFactory and an Abstract Factory called ModelFactory. The goal of the DbStoreFactory is to abstract calls to our databases so that clients don&#39;t need to be aware of what databases we are using, their distinct schemas, and their unique functions. The goal of ModelFactory is to abstract and normalize the operations associated with any model we need to manage. A &quot;model&quot; would be an entity type or collection that we will (likely) store in some database table. For example, we may have a &quot;users&quot; model that defines the properties (attributes or schema) and methods (functions) required to manage a &quot;user&quot;.</p><h3>Model Factory</h3><h4>Overview</h4><p>As mentioned before, the primary purpose of using the Abstract Factory design pattern is to make sure we are implementing the OCP. The secondary benefit to this design pattern is reusability across projects. A perfect example of this is our ModelFactory Abstract Factory.</p><p>When building a new application, one of the first steps is to define your models. Let’s say this application is a blogging application. At a minimum, we need to define a <em>user</em> and <em>post</em> model. Each model would include its properties (e.g. JSON schema) and its methods (e.g. CRUD operations).</p><p>Down the road, we are commissioned to build another application. This application is a social messaging application. Once again, we need models for <em>users</em> and <em>posts</em>. In addition, we need a model for <em>channels</em>. Ideally, we want to reuse our code from the last project and extend it to include the new model.</p><h4>Implementation</h4><p>The first piece of the implementation is to create our Abstract Factory that we will name ModelFactory. Then, for every model, we will create a Concrete Factory, such as UserModelFactory and PostModelFactory.</p><p>The ModelFactory will include any properties or methods that are shared amongst all models. For example, you could assign a type property for all models. The ModelFactory will have a parameter that tells it which model the &quot;client&quot; wants to interface with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJdmRzsWuVCn40v-oMLC4w.png" /></figure><p>Now we can create our UserModelFactory and create the interface with ModelFactory. We need to look at the model parameter to know which model to inject. We could use an if or switch statement but I&#39;ve decided to use an object for a quicker reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbftGk1vsWKsSnWGYxOHzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61k1ogH3QtnTbbW9rmZkfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J26daB5vIf6MrgjfbxNN1g.png" /></figure><p>The second piece of the implementation is in our “client” code. (Client code refers to any code that interfaces with our Factories).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Icq0V8oFpIIDn4d2RE44g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D72ZDKyOZfOgf6W1E2eeRA.png" /></figure><p>From this implementation, you can see that when we instantiated the users model we ended up with the type property and list method from ModelFactory and the create method from the UserModelFactory.</p><p>Now, let’s add our posts model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l19hWednJ4NWaHW_FqJE0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*va7_dWX3VuDd0E6_xc258Q.png" /></figure><p>So we added our new model to our model definitions. Then we created our PostModelFactory. Notice we did <strong>not</strong> have to make any changes to our ModelFactory!</p><p>Now let’s interface with the <em>posts</em> model in our “client”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiVaoCGQa_7chIURmmiYRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-S4E_6mIYt2yWmIM0DcqA.png" /></figure><p>Voila! We “extended” our ModelFactory and made it very simple for the &quot;client&quot; to use because it&#39;s used in the exact same way as with the <em>users</em> model.</p><p>Now we need to add our database integration(s) so our models can perform their CRUD operations.</p><h3>Database Factory</h3><h4><strong>Overview</strong></h4><p>In our Problem Statements, we talked about how a change in database platforms had a significant ripple effect across our entire project. We don’t want that to happen going forward and we will, once again, use the Abstract Factory model and create our DbStoreFactory.</p><blockquote><em>FWIW, I chose this name because I will also be adding a </em><em>FileStoreFactory for interfacing with file storage services and these names make sense to me.</em></blockquote><p>For the sake of this example, let’s say we will be using the Firebase Firestore and Firebase Realtime databases. We won’t actually be coding that integration here but we will show how it will be structured.</p><h4>Implementation</h4><p>The pattern for how this will work is the same pattern we used for the ModelFactory so I will just show the outcome of the DbStoreFactory implementation here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydxH0rs0v0sZewu1b2OeAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mc5dg76NrLv9a-ep-nqmxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHipxPTW4AEW4SuUrlAq-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XrTjgml7ygIvy8WvMNmnQw.png" /></figure><p>There we have our database integrations via the Abstract Factory method. Obviously, this isn’t actually talking to the database platforms but that isn’t the point.</p><p>One subtle difference with DbStoreFactory is that I included the methods that will be found in every Concrete Factory. I like that because I can just go to the DbStoreFactory code to see all of the methods that will be available in the different Concrete Factories.</p><p>Now we need the “client” piece of the implementation. In this case, the model factories are the “client” because that is where we will make the database calls. In this project example, we will be using Firebase Firestore for all models. That means we will instantiate the database session directly in ModelFactory because it is shared across all models. Then we update the list method to use the database integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdnHkco6FhCU5xC4YYpWsQ.png" /></figure><p>From the perspective of ModelFactory, changing a database platform, say from Firebase Firestore to Firebase Realtime, will only require a change to the db property definition so that it points to the new store definition. We just have to ensure that DbStoreFactory provides the normalized set of methods. Meaning that the models only need to worry about the database list method. It is up to the different database factories to translate that to the database platform&#39;s way of returning a list.</p><p>Next, we need to update our model factories to implement the database calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pVMPr71wNeh7NJGLF7FYBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtF1hakWvRfx4rCLWhOpWw.png" /></figure><p>We should never need to change the database code in any of our model factories… ever! We can extend them by adding new methods but we should not change the existing ones once we are deployed.</p><p>There is no need to change our “client” code because the database interfaces are completely abstracted.</p><p>This is what “clean code” looks like when using functional JavaScript. (I’m sure this statement will result in some colorful responses!)</p><p>The complete <a href="https://gist.github.com/34fame/8a5ee6ba96b47aa8d6411839c82dfef0">code can be found here</a>.</p><p>Take care!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6547d4e68e30" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/real-world-implementation-of-functional-javascript-design-patterns-6547d4e68e30">Real-World Implementation of Functional JavaScript Design Patterns</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop repeating code across functions by using wrappers.]]></title>
            <link>https://levelup.gitconnected.com/i-taught-myself-how-to-implement-dry-in-a-dream-1f70507102e2?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f70507102e2</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[dry-principle]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 17:39:13 GMT</pubDate>
            <atom:updated>2022-08-21T11:31:35.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XiXAQdLFUxeTdyOg" /><figcaption>Photo by <a href="https://unsplash.com/@carolynchristine?utm_source=medium&amp;utm_medium=referral">carolyn christine</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It isn’t uncommon for me to dream about coding. I frequently wake up with fresh ideas about something I struggled with the day prior. This morning I woke from a similar dream; however, the epiphany it sparked was much greater than usual.</p><h3>Before the Epiphany</h3><p>Over time, I have started writing functions in my own standard way. A typical function would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2dwx1_HsCxnsL7ZWi5ibQ.png" /></figure><p>This example is only to give you an idea of the structure. Now, I rinse and repeat this as I create additional functions like getRecords, addRecord, updateRecord, deleteRecord, etc.</p><p>Just using my basic example, <strong>I end up repeating over 90% of my code</strong> inside these functions. Every function has a try/catch block. Every function has multiple console calls. I knew this wasn’t ideal. I just didn’t know how to improve it.</p><p>To make matters worse, I’m prone to changing my standard. It might be something as silly as changing catch (error) to catch (e). Then my OCD kicks in and, next thing you know, <strong>I’ve spent an hour just going through and making this change</strong> all over the place.</p><h3>After the Epiphany</h3><p>I am always learning new concepts and recently started putting a lot of effort into understanding best practices such as <strong>SOLID principles and design patterns</strong> in general. I think working through examples of these concepts is what lit the spark for my epiphany.</p><p>Let’s get to it…</p><p>First off, I thought about the fact that you can pass a function as a parameter of another function. So I wanted to see if I could standardize my try/catch block method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqV6mjkQKDsJJTsv-cAIYA.png" /></figure><p>Now, any time I want to “wrap” a function inside my standard try/catch block I simply pass the function into my tryWrapper function. The main benefits of this approach are:</p><ul><li>I’m <strong>no longer repeating the </strong><strong>try/catch code</strong> in every function</li><li>I can alter tryWrapper any time and <strong>the change will be reflected everywhere</strong> it’s used</li></ul><p>Next, I needed to add in my standard for logging messages. The only tricky thing here is that I want the name of the primary function to be displayed in the log message. To accomplish this I created an object that would contain all of my “primary functions”. Then I created a logWrapper in a similar fashion to my tryWrapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoOrJe6vHjQo5aFvwKPajQ.png" /></figure><h3>Conclusion</h3><p>Wow! This brings a whole new meaning to the phrase, “I can do that in my sleep!”</p><p>This is exactly how I dreamed it! So many benefits to this approach:</p><ul><li>Reduces the amount of code</li><li>Reduces development time</li><li>Simplifies troubleshooting</li><li>Provides an extensible framework (e.g. I could add a tryAsyncWrapper())</li><li>Implements several SOLID principles</li></ul><p>Thanks for your time! I always appreciate any feedback!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in <a href="https://levelup.gitconnected.com/">Level Up Coding</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a></li><li>🚀👉 <a href="https://jobs.levelup.dev/"><strong>Top jobs for software engineers</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f70507102e2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/i-taught-myself-how-to-implement-dry-in-a-dream-1f70507102e2">Stop repeating code across functions by using wrappers.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An opinionated tech stack for your next full-stack project]]></title>
            <link>https://levelup.gitconnected.com/an-opinionated-tech-stack-for-your-next-full-stack-project-f6bb8ce317e9?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6bb8ce317e9</guid>
            <category><![CDATA[quasar]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech-stack]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Sat, 07 May 2022 19:52:19 GMT</pubDate>
            <atom:updated>2022-05-08T21:59:15.023Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aFe4r8MQiNs1qqZZ" /><figcaption>Photo by <a href="https://unsplash.com/@lastnameeaster?utm_source=medium&amp;utm_medium=referral">La-Rel Easter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Overview</h3><p>A couple of years ago I would have loved to find this article. It would have saved me countless hours and days struggling to find the right tech stack. There are many options these days for building and hosting your application. This is my opinionated stack primarily based on the following constraints:</p><ul><li>I prefer to use <strong>one</strong> <strong>programming language</strong>. In my case, JavaScript is the answer (TypeScript would also work in this same stack).</li><li>I want to <strong>build clients for multiple platforms</strong> (e.g. Web, Mobile, Desktop) but don’t have the time, or desire, to build each of them as a separate project.</li><li>I don’t want to spend countless hours building <strong>UI components</strong>.</li><li>I want the <strong>benefit of PaaS with low-to-no cost</strong> during the development and early phases of my project.</li><li>I want the ability to <strong>deploy the entire stack automagically</strong> when I push my code commits.</li></ul><h3>Platform-as-a-Service 🔥</h3><p>I’m using <a href="https://firebase.google.com/"><em>Firebase</em></a> (built on <a href="https://cloud.google.com/"><em>Google Cloud Platform</em></a>) which provides services for web hosting, authentication, database (NoSQL &amp; Realtime), file storage, serverless functions, logging, analytics, push notifications, and more!</p><blockquote>Firebase is a very viable platform for startups…</blockquote><p>I have one app with ~500 users and pay nothing per month. I have other apps with fewer users and, all total, I’m currently paying around $.30/month. Obviously, costs are relative and could increment quickly based on the popularity of an application, regardless of platform. My point is <em>Firebase</em> is a very viable platform for startups from a cost (and functionality) perspective.</p><h3>Client 👩‍💼</h3><p>For the client(s), I like <a href="https://quasar.dev/"><em>Quasar Framework</em></a> (built on <a href="https://vuejs.org/"><em>Vue.js</em></a>), mainly because I am able to build all of the clients from one code base (e.g. SPA, PWA, SSR, native <em>iOS</em>, native <em>Android</em>, native <em>Windows</em>, Native <em>macOS</em>, native Linux, browser extensions…). <em>Quasar</em> also provides a fantastic, built-in, UI component library and has many other helpful plugins, extensions, and helper functions.</p><p>The web client builds are deployed to the <em>Firebase Hosting</em> service. I host my code on <a href="https://github.com/"><em>GitHub</em></a> and use <a href="https://github.com/features/actions"><em>GitHub Actions</em></a> to automate the deployment to <em>Firebase</em>.</p><p>The native client builds are deployed to the appropriate app store using each store’s native process (e.g. I deploy <em>iOS</em> apps using <em>XCode</em>). <em>Quasar</em> makes the build process relatively easy with built-in support for <em>Cordova</em>, <em>Capacitor</em>, and <em>Electron</em>.</p><blockquote>For anyone interested in finding out more about <em>Quasar Framework</em>, check out this tutorial video by community favorite, <a href="https://www.youtube.com/channel/UC6eR_ndNgaTeE5t2Ud4ZiHw">Make Apps with Danny</a>:</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGV-D85D9KJQ%3Fstart%3D1%26feature%3Doembed%26start%3D1&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGV-D85D9KJQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGV-D85D9KJQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e05e32fc7e5415df1bd512bb19db2abe/href">https://medium.com/media/e05e32fc7e5415df1bd512bb19db2abe/href</a></iframe><h3>Marketing (www) 🌐</h3><p>If applicable, I build the marketing site in a separate <em>Quasar</em> project and build it as server-side rendering (SSR) to get the SEO benefits; however, most often, I just include these pages as a part of my application and let the users “launch” the app from a call-to-action button.</p><p>I create public routes, layouts, and pages to create anonymous content when users visit “https://www.myappdomain.app”.</p><p>I then create authentication routes, layouts, pages, and components to handle user registration, login, logout, and other related features.</p><p>Finally, I create secure routes, layouts, pages, and components for the application once users are authenticated. <em>Quasar</em> makes it very simple to use different layouts (and/or components) based on the user’s platform. So I can have a mobile layout and a desktop layout while still utilizing the same pages and components.</p><h3>Documentation 📖</h3><p>I can build the documentation embedded in my client (using <em>Quasar’s</em> <a href="https://quasar.dev/app-extensions/discover">QMarkdown app extension</a>); however, because I can deploy updates separately, I typically create a separate docs project using either another <em>Quasar</em> project or something like <a href="https://vuepress.vuejs.org/">VuePress</a>.</p><p>When using a separate docs project, I will normally deploy it to <a href="https://pages.github.com/">GitHub Pages</a> using a custom subdomain such as “https://docs.myappdomain.app”.</p><h3>Server 🌀</h3><p>I build a server project using <a href="https://expressjs.com/"><em>Node/Express</em></a> and the <a href="https://firebase.google.com/docs/admin/setup"><em>Firebase Admin SDK</em></a>. Deploying the server to <em>Firebase Functions</em> gives me options to build REST APIs, pub/sub triggers, database update triggers, and scheduled triggers.</p><blockquote>NOTE: For those of you familiar with Firebase SDK’s, there is some debate as to whether it’s better to make calls to Firebase directly from the client or to have the server make the calls to Firebase and provide a RESTful API to the client. There are valid reasons for both and, more than likely, you’ll need to have a mix. I’ve taken both approaches in projects and I prefer using the server whenever possible and only make calls directly to Firebase from the client when absolutely necessary.</blockquote><blockquote>Examples of when it’s neccessary to use the Firebase client SDK are:<br>1) Logging in with Firebase Authentication methods such as Google or Facebook<br>2) Uploading files to Firebase Storage<br>3) Using Firebase Analytics to capture client traffic</blockquote><h3>Project Structure</h3><p>This is just to give you an idea of what one of my project folders looks like. The purpose is to demonstrate that I’m using a single repo with scripts to run a local development environment, perform builds, and deploy to the appropriate PaaS service.</p><pre>MyProject<br>  L client           // Quasar project<br>    L src            // Quasar code (for all platforms)<br>    L src-*          // auto-created when platforms added<br>    L ...            // other platforms added<br>    L dist<br>      L *            // Web client builds<br>    L quasar.conf.js // Quasar configuration<br>    L package.json   // scripts to run, build, deploy client(s)</pre><pre>  L docs           // Quasar or VuePress project<br>    L src          // Document markdown files<br>    L package.json // scripts to run, build, deploy docs</pre><pre>  L server<br>    L functions    // Node/Express project<br>      L index.js   // code starts here<br>    L package.json // scripts to run, build, deploy server</pre><pre>  L .git         // local &quot;monolythic&quot; repo<br>  L .github      // GitHub actions<br>  L package.json // scripts to run, build, deploy all</pre><h3>Conclusion</h3><p>Choosing a tech stack is the most important decision you make when starting a new project. Making the wrong choices at this stage will result in a significant loss of time, money, and hair. 😢</p><p>All seasoned full-stack developers have an opinion. Everyone comes at this from different perspectives and unique constraints.</p><p>For me, this “opinionated” tech stack has been an evolution of much trial-and-error, and, to this point, has yet to let me down. It is at least worth researching as you try to find your own “opinionated” tech stack! Good luck! 👍</p><p>Hope this helps! I look forward to your comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6bb8ce317e9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/an-opinionated-tech-stack-for-your-next-full-stack-project-f6bb8ce317e9">An opinionated tech stack for your next full-stack project</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling conditional exceptions efficiently when iterating arrays]]></title>
            <link>https://levelup.gitconnected.com/handling-conditional-exceptions-efficiently-when-iterating-arrays-99a6e6e5c664?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a6e6e5c664</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[loops-in-javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Thu, 14 Apr 2022 19:35:27 GMT</pubDate>
            <atom:updated>2022-04-17T11:48:41.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wOXhRnnKvzgcKjJm" /><figcaption>Photo by <a href="https://unsplash.com/@vinikhill?utm_source=medium&amp;utm_medium=referral">NIKHIL</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As usual, I’m writing this story because this topic has given me problems on more than one occasion. How many times have you been iterating through an array and want to do something with the current element only if it meets some criteria? All the time, right?</p><p>I’m not new to programming but I am relatively new to JavaScript. When learning JavaScript I learned about the map() and forEach() methods for iterating arrays. What I didn’t realize until recently is that these methods are actually a part of the array itself. An array is a JavaScript object with numerous properties and methods inherently attached. These methods are NOT loops and therefore lack some functionality of a loop. JavaScript loop statements consist of:</p><ul><li>do…while</li><li>for…in</li><li>for…of</li><li>for</li><li>while</li></ul><h3>Scenario</h3><p>Let me use a real-world use case to further explain my own dilemma. I need to build a process that will run every day and generate invoices; however, I need to separate invoices into “Daily”, “Weekly” and “Monthly” schedules based on the items I’m processing.</p><p>This process will run on the server triggered by a schedule.</p><p>The “Daily” invoice process should process every day and contain all items whose billing schedule is set to daily and occurred today.</p><p>The “Weekly” invoice process should only process on Monday and contain all items whose billing schedule is set to daily and occurred within the last week.</p><p>The “Monthly” invoice process should only process on the first of the month and contain all items whose billing schedule is set to monthly and occurred within the last month.</p><p>Being a good developer, I’m not going to build three separate processes. I’m going to build one process that handles all three scenarios.</p><h3>Using Array Methods</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*SPwrj6Yqx_pz1ZKNB9zD1g.png" /></figure><p>In the scenario above I’m using the Array.prototype.forEach method. There isn’t an obvious problem with this approach because we don’t have all of our code in place.</p><h3>Using Loop Statement</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*mjwuiJcTqpMGkntjwTcdrQ.png" /></figure><p>In this scenario, I’m using the for...of loop statement with a label. Do you notice the subtle difference?</p><blockquote>NOTE: I have found that the for...of loop statement is great when dealing with arrays. You can also use for...in instead of Object.keys(myObject).forEach().</blockquote><p>When using a loop statement I have the ability to use two other important statements that are NOT available in the Array methods: break and continue.</p><p>The point is that the latter example will be more readable over time. When you look at the “Weekly” switch case, you see my (negative) condition and the only statement within the condition is `continue`. Compare that to the first scenario where I’ll have all of my code INSIDE the if condition.</p><blockquote>NOTE: The use of labels is very important when you have nested loops. Labels allow you to specify which loop you are continuing or breaking.</blockquote><h3>Conclusion</h3><p>Most developers agree that conditional statements ( if, switch, etc.) should end as soon as possible. Having pages of statements inside these constructs is difficult to read and maintain.</p><p>The use of break and continue can also speed up processing because the loop instantiation immediately stops rather than continuing to the end of the loop statement.</p><p>I can’t tell you how many times I’ve run into a case where I was getting unexpected results inside a map() or forEach() because my logic towards the end wasn’t always excluding all conditions. This is because my conditional logic was getting unmanageable in size. Using loops with break and continue will certainly help alleviate this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a6e6e5c664" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/handling-conditional-exceptions-efficiently-when-iterating-arrays-99a6e6e5c664">Handling conditional exceptions efficiently when iterating arrays</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify exporting and importing of your JavaScript utility functions]]></title>
            <link>https://levelup.gitconnected.com/simplify-exporting-and-importing-of-your-javascript-utility-functions-2bfcb436c2d9?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bfcb436c2d9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 01:11:39 GMT</pubDate>
            <atom:updated>2022-04-01T13:12:55.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X063JrXWBpFm_puv" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a “good” developer you know not to repeat code in your projects. To accomplish this I typically create utility functions that I can easily call throughout my project.</p><p>This article explains how I structure my utility functions such that new functions are immediately available without the additional export/import steps I use to perform.</p><h3>The “Old” Approach</h3><p>Let’s say I need to handle some date operations. To do this I’ll create a src/utils/dates.js file:</p><pre>exports.startOfDay = (dt) =&gt; {  <br>  dt = dt ? new Date(dt) : new Date()  <br>  return dt.setHours(0,0,0,0) <br>}</pre><p>With this pattern, every function I place in this file will be individually exported. Now I want to make all functions available from a single import. I do this by creating a src/utils/index.js file:</p><pre>const { startOfDay } = require(&#39;./dates&#39;)</pre><pre>module.exports = function useUtils() {  <br>  return { startOfDay } <br>}</pre><p>The problem with this pattern is that I will need to update the index file every time I add or remove a function from my dates file.</p><p>Let’s look at a better approach and the one I use today.</p><h3>The “New” Approach</h3><p>The only change required is in our index file:</p><pre>const dates = require(&#39;./dates&#39;)<br>  <br>module.exports = function useUtils() {  <br>  return { ...dates }<br>}</pre><p>The difference is in two parts. First off, we are importing dates rather than specifying each function using “object destructuring”. The dates variable is an object containing all of the functions found in the dates file.</p><p>Secondly, in the export, we are creating a new function, useUtils() that returns each function within dates using a spread operator. This is the real magic! This ensures that each function found in the dates object is being individually exported.</p><h3>Usage</h3><p>Now let’s take a look at how we would use our utility functions.</p><pre>const useUtils = require(&#39;src/utils&#39;)</pre><pre>const util = useUtils()</pre><pre>const startOfDay = util.startOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(startOfDay) // (1646114400000)</pre><p>The only import is of useUtils. To simplify its use we assign it to the variable util. Now we have access to all functions using the util variable. For example, we can call util.startOfDay().</p><p>Now, let’s say we want to add another date-related function to our dates file:</p><pre>// Existing function<br>exports.startOfDay = (dt) =&gt; {  <br>  dt = dt ? new Date(dt) : new Date()  <br>  return dt.setHours(0,0,0,0) <br>}</pre><pre>// New function<br>exports.endOfDay = (dt) =&gt; {  <br>  dt = dt ? new Date(dt) : new Date()  <br>  return dt.setHours(23,59,59,999) <br>}</pre><p>Our new function endOfDay() is immediately available. Let’s use it!</p><pre>const useUtils = require(&#39;src/utils&#39;)</pre><pre>const util = useUtils()</pre><pre>const startOfDay = util.startOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(startOfDay) // (1646114400000)</pre><pre>// New<br>const endOfDay = util.endOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(endOfDay) // 1646200799999</pre><p>Let’s take this concept one step further. In my project, I need some utility functions for handling different scenarios with strings. To accomplish this I create a new utility file src/utils/strings.js:</p><pre>exports.toCamelCase = (str) =&gt; <em>str.trim</em>()<em>.replace</em>(/[-_\s]+(.)?/g, (_, c) =&gt; (c ? <em>c.toUpperCase</em>() : &#39;&#39;))</pre><pre>exports.toTitleCase = (str) =&gt; <em>str.replace</em>(/<em>^</em>(.)|\s+(.)/g, (c) =&gt; <em>c.toUpperCase</em>())</pre><p>Since this is a new file, I will need to include it in the utility index file:</p><pre>const dates = require(&#39;./dates&#39;)<br>const strings = require(&#39;./strings&#39;)<br>  <br>module.exports = function useUtils() {  <br>  return { ...dates, ...strings }<br>}</pre><p>Of course, I only need to touch the index file this one time. Now any new function I add to the strings file will automatically be included.</p><pre>const useUtils = require(&#39;src/utils&#39;)</pre><pre>const util = useUtils()</pre><pre>const startOfDay = util.startOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(startOfDay) // (1646114400000)</pre><pre>const endOfDay = util.endOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(endOfDay) // 1646200799999</pre><pre>const toCamel = util.toCamelCase(&#39;this_is_not_camel_case&#39;)<br>console.log(toCamel) // thisIsNotCamelCase</pre><pre>const toTitle = util.toTitleCase(&#39;troy moreland&#39;)<br>console.log(toTitle) // Troy Moreland</pre><p>The above code examples are all using CommonJS syntax (e.g. Node.js). Here is one way to implement the same thing using ES6 syntax (e.g. Vue/React).</p><pre>// src/utils/dates.js</pre><pre>export const startOfDay = (dt) =&gt; {  <br>  dt = dt ? new Date(dt) : new Date()  <br>  return dt.setHours(0,0,0,0) <br>}</pre><pre>export const endOfDay = () =&gt; {...}</pre><pre>// src/utils/index.js</pre><pre>import * as dates from &#39;./dates&#39;</pre><pre>export default function useUtils() {<br>  return { ...dates }<br>}</pre><pre>// src/some-other-file.js</pre><pre>import useUtils from &#39;src/utils&#39;</pre><pre>const utils = useUtils()</pre><pre>const startOfDay = util.startOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(startOfDay) // (1646114400000)</pre><pre>const endOfDay = util.endOfDay(&#39;2022-3-1 09:09:00&#39;)<br>console.log(endOfDay) // 1646200799999</pre><pre>const toCamel = util.toCamelCase(&#39;this_is_not_camel_case&#39;)<br>console.log(toCamel) // thisIsNotCamelCase</pre><pre>const toTitle = util.toTitleCase(&#39;troy moreland&#39;)<br>console.log(toTitle) // Troy Moreland</pre><h3>Conclusion</h3><p>In an effort to eliminate code duplication, create some utility functions. This is also nice for reusability across projects.</p><p>Then use the method demonstrated to minimize the overhead of managing your library of functions. Just add, and use!</p><p>Let me know if this has been a helpful post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bfcb436c2d9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/simplify-exporting-and-importing-of-your-javascript-utility-functions-2bfcb436c2d9">Simplify exporting and importing of your JavaScript utility functions</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Missing Chapter for Building Applications on Firebase: Create Different Firebase Environments]]></title>
            <link>https://levelup.gitconnected.com/the-missing-chapter-for-building-applications-on-firebase-7342f450bb6d?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/7342f450bb6d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Thu, 15 Apr 2021 05:31:35 GMT</pubDate>
            <atom:updated>2021-04-15T13:31:36.769Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create different environments for testing, staging, and production</h4><p>You finally bought that course on Udemy to learn <a href="http://firebase.google.com/">Firebase</a>. After all, the price dropped to $11.99! Ok, maybe it was a free YouTube tutorial. Whatever it was, I’ll assume you now understand how to use Firebase services like Hosting, Authentication, Firestore, Functions, and Storage. You even built this <strong><em>amazing</em></strong> To-Do app running solely on Firebase services!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KjQqlqymSyV2Q_Nf" /><figcaption>Photo by <a href="https://unsplash.com/@schmidy?utm_source=medium&amp;utm_medium=referral">Austin Schmid</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Now a new question comes to mind. How do I implement my SDLC process on Firebase?</p><blockquote>I need to have separate environments for testing, staging, and production.</blockquote><p>I had the same question after the initial euphoria wore off of seeing my data in Firestore and my files in Storage. For me, the solution was not trivial. I want to share with you how I was finally able to come up with a setup that I’m truly happy with.</p><p>This tutorial is focused on the configuration of your full-stack application to support concepts of development, testing, staging and production. This tutorial will <strong>not</strong> cover application code or how to use the Firebase SDKs.</p><h3>Prerequisites</h3><p>Due to the topic of this tutorial, I will be making the following assumptions:</p><ul><li>You are a Javascript developer</li><li>You are comfortable with Node.js, NPM, and Yarn</li><li>You are at least familiar with Firebase</li><li>You are comfortable with git and GitHub</li></ul><h3>Setup</h3><p>This section might seem trivial if you feel comfortable with Firebase but I wanted to start from the beginning. A fresh project. Let’s call it, “beefcake”. Yes, that was the first thing that popped into my head. Weird.</p><p>Let’s start with directory structure. Since we are building a full-stack application, I create the following structure. If I don’t specify a working path, assume that you are sitting in the project directory, “beefcake”.</p><pre>beefcake<br>  L client<br>  L server</pre><p>Make sure you have the Firebase tools installed.</p><pre>&gt; npm install -g firebase-tools</pre><p>If you haven’t used Firebase tools on your device yet, you will need to perform the one-time login.</p><pre>&gt; firebase login</pre><h4><strong>Client Configuration</strong></h4><pre>cd client<br>yarn init -y<br>firebase init</pre><ul><li>Select “Hosting” and “Emulators”</li><li>Create a “sandbox” project (e.g. beefcake-sandbox)</li><li>Keep default public directory</li><li>Select “Yes” to rewrite all urls</li><li>Select “N” to automate builds</li><li>Select “Hosting” emulator</li><li>Keep the default port</li><li>Select “N” to enable Emulator UI</li><li>Select “N” to download emulators</li></ul><h4><strong>Server Configuration</strong></h4><pre>cd server<br>firebase init # See answers below and then continue here</pre><pre>cd functions<br>yarn add firebase-admin</pre><pre># If you get a Node engine error...<br>yarn config set ignore-engines true<br>yarn add firebase-admin</pre><ul><li>Select “Firestore”, “Functions”, and “Emulators”</li><li>Select the existing project (e.g. beefcake-sandbox)</li><li>Keep default file names</li><li>Select “JavaScript”</li><li>Select “N” to ESLint</li><li>Select “N” to install dependencies</li><li>Select “Authentication”, “Functions”, “Firestore”, and “Pub/Sub” emulators</li><li>Set Firestore port to “8070” but leave the rest as default</li><li>Select “Y” to enable Emulator UI</li><li>Set Emulator UI port to “4000”</li><li>Select “N” to download emulators</li><li>Return to code block above to finish commands…</li></ul><p>Now our project should have the following directories and files.</p><pre>project<br>  L client<br>    L .firebaserc<br>    L .gitignore<br>    L firebase.json<br>    L package.json<br>    L public<br>  L server<br>    L .firebaserc<br>    L .gitignore<br>    L firebase.json<br>    L firestore.indexes.json<br>    L firestore.rules<br>    L functions<br>      L .gitignore<br>      L index.js<br>      L node_modules<br>      L package.json<br>      L yarn.lock</pre><h3><strong>Verify Setup</strong></h3><p>First let’s verify the client configuration by running the Hosting emulator.</p><pre>cd client<br>firebase emulators:start</pre><p>Open <a href="http://localhost:5000/">http://localhost:5000</a> in your browser. You should see a Firebase page and text indicating the Firebase SDK is in use. You can now stop the emulator with Ctrl-c.</p><p>Before we start the server emulators we need to uncomment some default code. In your editor, open beefcake/server/functions/index.js. Uncomment the helloWorld function.</p><pre>const functions = require(&quot;firebase-functions&quot;);<br><br>// // Create and Deploy Your First Cloud Functions<br>// // https://firebase.google.com/docs/functions/write-firebase-functions<br>//<br>exports.helloWorld = functions.https.onRequest((request, response) =&gt; {<br>  functions.logger.info(&quot;Hello logs!&quot;, {structuredData: true});<br>  response.send(&quot;Hello from Firebase!&quot;);<br>});</pre><p>Now launch the emulators.</p><pre>cd server/functions<br>firebase emulators:start</pre><p>Open <a href="http://localhost:4000/">http://localhost:4000</a> in your browser. You should see the Firebase Emulator Suite page which shows our services running. Open <a href="http://localhost:5001/beefcake-sandbox/us-central1/helloWorld">http://localhost:5001/beefcake-sandbox/us-central1/helloWorld</a> in your browser (your project and zone is likely different but the rest should be the same). You should see “Hello from Firebase!”. This indicates our endpoints served by Functions are working. You can close these emulators now.</p><h3>Development</h3><p>With our client and server emulators operational, we have everything we need to develop our full-stack app, without the costs or delays of using the live cloud services.</p><p>As I said before, the focus of this tutorial is not how to develop your app. We are focused on the approach for moving through our development lifecycle when using Firebase. So let’s fast forward a bit.</p><p>At this point, let’s assume we are “done” with development and we are ready to deploy what we have to Firebase so that others can access the application.</p><h3>Sandbox Deployment</h3><p>Remember that we are not using a production environment yet. Right now we just have our sandbox. We just need to deploy our client and server projects into that environment.</p><p>Let’s start with the client project.</p><pre>cd client<br>firebase deploy</pre><p>Done! For real! Once the deploy is done, you will find a “Hosting URL” on the screen. If you open your browser to that URL, you should see the same page we saw before, only this time, it is being served to us from Firebase.</p><p>The server deployment has one “gotcha”. You have to upgrade your Firebase project from “Spark” to “Blaze”. The “Spark” plan is free, with limitations. The “Blaze” plan provides free usage limits and then bills you for overages. Look over the pricing to make sure you understand the risks. I personally have never had a bill over $2/month and normally it’s less than $1/month.</p><p>As soon as you upgrade, it’s time to deploy!</p><pre>cd server<br>firebase deploy</pre><p>This deployment will take longer than the client. When done, you will see a URL for your “helloWorld” endpoint. Instead of the Emulator Suite, you will now use the <a href="http://console.firebase.google.com/">Firebase console</a>. As long as the “helloWorld” URL works, we are done with the sandbox deployment.</p><p>At this point, you would give stakeholders the client URL and let them experience your glory.</p><blockquote>When working with a team, all of this still applies. Each developer would have a copy of the code (e.g. git). If someone cloned the repository for the first time, they would need to run the firebase init in the client and server directories before emulators or deployments will work.</blockquote><h3>Testing</h3><p>I am not going to cover <em>how</em> you do testing for your application. I simply want to touch on a couple of key points on how Firebase plays into your testing.</p><p>The emulator suite is actually fantastic for testing. For one, you aren’t limited on what you can test, unlike when your application is running in Firebase. Another great thing about the emulators is when you stop and start them again, everything is clean. As in, empty. There is no tool for clearing out data in Firestore. It is not fun during development or testing to deal with your data in the live services. Not with emulators!</p><p>But… What if you do <em>not</em> want to lose your data? What if you need to preload data for testing? Once again, emulators to the rescue! While your emulators are running, you can export the data.</p><pre>cd server<br>firebase emulators:export ./export-dir</pre><p>This performs a dump that can then be imported. You can also instruct the emulators to always to an export before shutting down.</p><pre>cd server<br>firebase emulators:start --import=./export-dir --export-on-exit</pre><p>You will still need to perform some system testing with your application running in Firebase but, for unit and e2e testing, the emulator suite is very handy.</p><h3>Production</h3><p>Now we are finally getting to the gist of this tutorial. We have handled development, testing, and even provided a sandbox for stakeholders.</p><blockquote>How do we roll this into production and still keep what we have for future development, testing, etc.?</blockquote><p>The good news is, our code and where it lives doesn’t need to change. We don’t need to make a new project code folder. We don’t need to run parallel git branches or anything of the sort.</p><p>Long story short, we just need to tell our client and server configurations about the new Firebase project and then be able to set the current project on demand.</p><pre>cd client</pre><pre># Display a list of known projects<br>&gt; firebase use<br>* default (beefcake-sandbox)</pre><pre>&gt; firebase use --add</pre><p>First we used firebase use to see what is currently configured. We can see we have one project configured (“beefcake-sandbox”) with an alias of “default”.</p><p>Next we ran firebase use --add. This tells Firebase we want to add another project. So, create the production project (e.g. “beefcake-prod”) and assign it the alias “prod”.</p><p>Now we just need to do the same in the server project.</p><pre>cd server<br>firebase use --add</pre><p>Be sure to select the existing production project we just created.</p><p>From now on, if we want to deploy our code to production, we need to run firebase use prod first. This sets the context for the Firebase tools.</p><h4><strong>Environment Variables</strong></h4><p>In your application code you will have environment specific variables that also need to be updated when you change between sandbox and production. There are numerous methods to achieve this. I am not suggesting one method over another, but, because it is applicable to this topic, I will show you one way.</p><p>Most of the time I use the dotenv library to manage environment variables. This allows you to put sensitive tokens in separate files and then exclude them in any public repo with your .gitignore file. As such, you would normally create a .env file in your client and server projects. I also create one for each environment. Later we will script copying them on demand.</p><pre>beefcake<br>  L client<br>    .env          # used by dotenv<br>    .env.local    # copy to .env when running emulators<br>    .env.sandbox  # copy to .env on sandbox deploy<br>    .env.prod.    # copy to .env on prod deploy<br>  L server<br>    L functions<br>      .env<br>      .env.local<br>      .env.sandbox<br>      .env.prod</pre><h3>Package Scripts</h3><p>The final piece to this configuration is to simplify things with scripts in our package.json files. We want to make sure we are setting the environments properly while making things really simple to use.</p><p>To this point we haven’t done anything in our project root folder, other than creating the client and server folders. We are going to run our scripts from here which, in turn, will run the proper scripts in the client and server areas.</p><p>We need to initialize the project directory to use scripts and then add a helpful library called npm-run-all to all three spots where we have a package.json file.</p><pre>yarn init -y<br>yarn add -D npm-run-all</pre><pre>cd client<br>yarn add -D npm-run-all</pre><pre>cd ../server/functions<br>yarn add -D npm-run-all</pre><h4>Project Directory Scripts</h4><p>Here is an example set of scripts that would be kept in the project directory’s package.json file. I’m excluding irrelevant portions of that file so don’t take this contents as literal.</p><pre>{<br>  &quot;name&quot;: &quot;project&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;serve:local&quot;: &quot;npm-run-all --parallel client:local server:local&quot;,<br>    &quot;deploy:staging&quot;: &quot;npm-run-all client:deploy:staging server:deploy:staging&quot;,<br>    &quot;deploy:prod&quot;: &quot;npm-run-all client:deploy:prod server:deploy:prod&quot;,<br>    &quot;client:local&quot;: &quot;cd client &amp;&amp; yarn serve:local&quot;,<br>    &quot;client:deploy:staging&quot;: &quot;cd client &amp;&amp; yarn deploy:staging&quot;,<br>    &quot;client:deploy:prod&quot;: &quot;ce client &amp;&amp; yarn deploy:prod&quot;,<br>    &quot;server:local&quot;: &quot;cd server/functions &amp;&amp; yarn serve:local&quot;,<br>    &quot;server:deploy:staging&quot;: &quot;cd server/functions &amp;&amp; yarn deploy:staging&quot;,<br>    &quot;server:deploy:prod&quot;: &quot;cd server/functions &amp;&amp; yarn deploy:prod&quot;<br>  }</pre><h4>Client Directory Scripts</h4><p>The path is client/package.json.</p><pre>{<br>  &quot;name&quot;: &quot;client&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;serve:local&quot;: &quot;npm-run-all use:staging copy-env:local start:local&quot;,<br>    &quot;deploy:staging&quot;: &quot;npm-run-all use:staging copy-env:staging quasar:build:staging firebase:deploy:staging&quot;,<br>    &quot;deploy:prod&quot;: &quot;npm-run-all use:prod copy-env:prod quasar:build:prod firebase:deploy:prod&quot;,<br>    &quot;use:staging&quot;: &quot;firebase use default&quot;,<br>    &quot;use:prod&quot;: &quot;firebase use prod&quot;,<br>    &quot;copy-env:local&quot;: &quot;cp .env.local .env&quot;,<br>    &quot;copy-env:staging&quot;: &quot;cp .env.staging .env&quot;,<br>    &quot;copy-env:prod&quot;: &quot;cp .env.prod .env&quot;,<br>    &quot;start:local&quot;: &quot;firebase emulators:start&quot;,<br>    &quot;firebase:deploy:staging&quot;: &quot;firebase deploy -P default&quot;,<br>    &quot;firebase:deploy:prod&quot;: &quot;firebase deploy -P prod&quot;<br>  }</pre><h4>Server Directory Scripts</h4><p>The path is server/functions/package.json.</p><pre>{<br>  &quot;name&quot;: &quot;server&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;serve:local&quot;: &quot;npm-run-all use:staging copy-env:local start:local&quot;,<br>    &quot;deploy:staging&quot;: &quot;npm-run-all use:staging copy-env:staging firebase:deploy:staging&quot;,<br>    &quot;deploy:prod&quot;: &quot;npm-run-all use:prod copy-env:prod firebase:deploy:prod&quot;,<br>    &quot;use:staging&quot;: &quot;firebase use default&quot;,<br>    &quot;use:prod&quot;: &quot;firebase use prod&quot;,<br>    &quot;copy-env:local&quot;: &quot;cp .env.local .env&quot;,<br>    &quot;copy-env:staging&quot;: &quot;cp .env.staging .env&quot;,<br>    &quot;copy-env:prod&quot;: &quot;cp .env.prod .env&quot;,<br>    &quot;start:local&quot;: &quot;firebase emulators:start&quot;,<br>    &quot;firebase:deploy:staging&quot;: &quot;firebase deploy -P default&quot;,<br>    &quot;firebase:deploy:prod&quot;: &quot;firebase deploy -P prod&quot;<br>  }</pre><h4>Execution</h4><p>Typically you will start things from the project directory. Your options are this point are to run locally by launching all emulators, deploy client and server to the sandbox environment, or deploy client and server to production. As you travel the path of the scripts you will notice there are multiple actions taken to make sure the environments are setup just right for what we want to accomplish. To do all of this by hand would be asking for trouble.</p><pre># Run locally with emulators<br>yarn serve:local</pre><pre># Deploy to sandbox<br>yarn deploy:sandbox</pre><pre># Deploy to production<br>yarn deploy:prod</pre><h3>Conclusion</h3><p>It took a lot of research and trial-and-error before I felt happy with this setup. During my research I found many others asking how to do something like this but I never found an answer that was either complete enough or clear enough for me.</p><p>There are so many courses and tutorials on how to use Firebase in your projects but I haven’t found a single one that handled the need for multiple environments. I wanted this walk-thru to continue where those instructions ended. Please let me know if I nailed it, or whiffed it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7342f450bb6d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-missing-chapter-for-building-applications-on-firebase-7342f450bb6d">The Missing Chapter for Building Applications on Firebase: Create Different Firebase Environments</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Real-Time Updates to your Vue App]]></title>
            <link>https://levelup.gitconnected.com/add-real-time-updates-to-your-vue-app-2448339e6b5b?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/2448339e6b5b</guid>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firestore]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 17:13:12 GMT</pubDate>
            <atom:updated>2020-11-11T12:58:40.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zCi8H1WOved8mudS" /><figcaption>Photo by <a href="https://unsplash.com/@saffu?utm_source=medium&amp;utm_medium=referral">Saffu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve been using <a href="https://firebase.google.com/docs/firestore">Cloud Firestore</a> as my primary database for months now and have been very happy with it.</p><blockquote>Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform. Like Firebase Realtime Database, it keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. Cloud Firestore also offers seamless integration with other Firebase and Google Cloud Platform products, including Cloud Functions.</blockquote><p>Google’s description of Firestore is clear enough, but, for some reason, I have ignored the part about “keeps your data in sync across client apps through realtime listeners”. I think I ignored it because (a) I didn’t think I needed it and (b) I didn’t understand it.</p><p>Having grown up on SQL databases I am very comfortable with writing code to perform all database reads and writes. The concept of real-time updates just sounds like chaos! 😬</p><p>Not only is this not true but I will be using real-time updates from now on. Here’s how!</p><h3>Traditional Queries</h3><p>Until recently I was only pulling data from Firestore using traditional query methods. This is like using “SELECT” in an SQL statement. To retrieve data in the traditional manner, Firestore provides a get() method with several options:</p><ul><li>Retrieve all documents in a collection</li></ul><p>db.collection(&quot;cities&quot;).get()</p><ul><li>Retrieve all documents of a collection group (subcollections across numerous collections)</li></ul><p>db.collectionGroup(&quot;landmarks&quot;).get()</p><ul><li>Retrieve select documents of a group (where clause)</li></ul><p>db.collection(&quot;cities&quot;).where(&quot;capital&quot;, &quot;==&quot;, true).get()</p><ul><li>Retrieve a single document</li></ul><p>db.collection(&quot;cities&quot;).doc(&quot;SF&quot;).get()</p><h3>Real-Time Updates</h3><p>Now for the cool part. To create a real-time listener, Firestore provides the onSnapshot() method. All you do is replace the get() method used in the above examples with the onSnapshot() method. For example:</p><p>db.collection(&quot;cities&quot;).onSnapshot()</p><p>Once invoked, your clients will automatically and immediately receive all changes to in-scope documents in Firestore. It really feels like magic when you see it the first time!</p><h3>Implementation</h3><p>One significant change to this project is that I’ve added the Firebase SDK to the clients (SPA, Cordova, Electron, etc.) to enable the real-time updates. Previously I would only use the Firebase Admin SDK on the server and provide APIs to the client. I don’t raise this as an issue, just a change in my typical setup.</p><p>As a result, we will need to initiate our Firebase connection with the client. I’m using <a href="https://quasar.dev/">Quasar Framework</a> which provides “boot” files that run when the client is started.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ea11ea3c130718b83d06cce3a89d11e/href">https://medium.com/media/4ea11ea3c130718b83d06cce3a89d11e/href</a></iframe><p>Nothing fancy here. We are just connecting to Firebase and exporting the Firestore methods.</p><p>Everything else is handled in the Vuex store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1becb2d672b5dbeca5f101fe246fe0a/href">https://medium.com/media/f1becb2d672b5dbeca5f101fe246fe0a/href</a></iframe><p>Let’s step through this example in more detail.</p><p>First of all, I’m importing my Axios and Firestore instances. Axios is used to make API calls to my server and Firestore, of course, is used to setup my real-time listeners.</p><p>In this scenario, I’m handling user documents. These documents will get stored in the “collection” state.</p><p>For mutations, I only need a way to individually add, update, and delete user documents. The SET_USER mutation will handle adds and updates while DELETE_USER mutation will handle deletes.</p><p>I do have getters in my project but I’ve excluded them here because they have no bearing on the topic.</p><p>I have a total of four actions. The first three, addUser() , updateUser() , and deleteUser() are calling my server API. Notice there are no “commit” statements? Strange, right?? 😕</p><p>The final action, bindUsers() , is our magical call to Firestore to setup our listener. As you can see, every change sent to the client has a type of either “added”, “modified”, or “removed”. With that, and the document itself, we can call our mutations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a704658d5877ce0c40e84f5f6c67f544/href">https://medium.com/media/a704658d5877ce0c40e84f5f6c67f544/href</a></iframe><p>We still need to call our bindUsers() action. I have a component for listing users so I call it in this component’s created() lifecycle method. The listener will remain active until it is detached with the unsubscribe() method or the client is closed.</p><blockquote>NOTE: When you first initiate the listener it will iterate through all in-scope documents in Firestore. In other words, you don’t need to create an action to load your initial state.</blockquote><p>Let’s think about this for a second…</p><ol><li>The end-user submits a new user</li><li>The addUser() store action is called</li><li>The client calls the POST endpoint on the server</li><li>The server creates the new user document in Firestore</li><li>Firestore notifies our client of the newly created user 😮</li><li>The SET_USER mutation adds the user to the user collection state</li><li>The UI is updated to show the newly created user 👏(slow clap)</li></ol><p>You still aren’t impressed?? Ok, picture this:</p><p>I am using the app from my computer’s browser. A co-worker is using the native app on their phone. I add a new user as described above and I see the newly created user in the UI immediately. SO DOES MY CO-WORKER! No refresh required. WHAT?!?! ⭐️ ⭐️ ⭐️ ⭐️ ⭐️</p><p>More articles by <a href="https://medium.com/u/831caef304ef">Troy Moreland</a></p><p><a href="https://graypes.medium.com/">Troy Moreland - Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2448339e6b5b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/add-real-time-updates-to-your-vue-app-2448339e6b5b">Add Real-Time Updates to your Vue App</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Dynamic Forms to your Vue App]]></title>
            <link>https://levelup.gitconnected.com/add-dynamic-forms-to-your-vue-app-609de4005a2b?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/609de4005a2b</guid>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[dynamic-form]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[quasar]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 03:34:20 GMT</pubDate>
            <atom:updated>2020-11-10T17:43:14.404Z</atom:updated>
            <content:encoded><![CDATA[<p>Define form fields once, as schema, and render them anywhere!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nM6p_SCZ9quhRbyj" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How much code does it take for you to render all forms in your application? Do you find yourself adding the same fields to multiple forms? How hard would it be for you to change UI frameworks based on your forms?</p><p>These are just some of the reasons I decided to focus some time to design dynamic forms for my projects.</p><p>There are numerous packages available to provide dynamic forms; however, I was not able to find one that met my needs.</p><h3>Problem</h3><p>I have been using <a href="https://vuejs.org/">Vue.js</a> and <a href="https://quasar.dev/">Quasar Framework</a> for about 6 months now. I love Quasar Framework because it provides all of the UI components I require and it gives me the option to write code once and build it as a web, desktop and/or mobile application. I absolutely love this platform. 😍</p><p>I’m currently working on a decent sized project where I manage numerous types of collections (e.g. Users, Projects, Tasks, etc.). I have several forms for each of these to list, create, update and delete the different collection items. After a time I started to recognize a lot of duplicate code. One area of duplicates I found was in my forms and their components. If I want a form to add a user I would build it and include all of the UI components necessary.</p><pre>&lt;q-form&gt;<br>  &lt;q-input color=&#39;primary&#39; label=&#39;First Name&#39; v-model=&#39;fname&#39; ... /&gt;<br>  &lt;q-input color=&#39;primary&#39; label=&#39;Last Name&#39; v-model=&#39;lname&#39; ... /&gt;&lt;/q-form&gt;</pre><p>The small example here is building a form to gather the first name and last name of this collection (let’s say it is a collection of ‘doctors’).</p><p>Now I need a form to add nurses. I need another form to add administrative staff. Etc. I end up with multiple forms, all of which have a First Name and Last Name field defined.</p><p>In the past I would create component templates. I call them “templates” because when I import them I’m providing their configuration through props. Here is a simple example of what I mean:</p><pre>&lt;!-- components/MyInput.vue --&gt;<br>&lt;template&gt;<br>  &lt;q-input :class=&quot;class&quot; :color=&quot;color&quot; :label=&quot;label&quot; :value=&quot;model&quot; /&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>export default {<br>  props: [&#39;class&#39;, &#39;color&#39;, &#39;label&#39;, &#39;value&#39;]<br>}<br>&lt;/script&gt;</pre><p>My form from above would now look like this:</p><pre>&lt;q-form&gt;<br>  &lt;my-input color=&#39;primary&#39; label=&#39;First Name&#39; value=&#39;fname&#39; ... /&gt;<br>  &lt;my-input color=&#39;primary&#39; label=&#39;Last Name&#39; value=&#39;lname&#39; ... /&gt;&lt;/q-form&gt;</pre><p>There really isn’t much benefit to this approach. In fact, I end up with more lines of code to support than before.</p><blockquote>There is a use case for templates. For example, when you are in a large team and you want to make sure everyone is using the same components. In this case you wouldn’t expose very many options for those components because you purposefully want them to always look and act the same.</blockquote><p>This is an overly simple example but enough to make my points. What if I wanted to populate an attribute besides class (Quasar’s <em>QInput </em>component alone offers dozens of properties)? I would have to add that attribute to my template and my props.</p><blockquote>On a side note, this is exactly why organizations use tools like <em>Storybook</em>. They need a way to document their components all of the props they expose.</blockquote><p>It gets worse before it gets better. My input component template was simple. To demonstrate the other extreme, here is an example using a Quasar Framework component, <em>QDate</em>. You <em>can</em> use this component by itself but normally you want to use it with a popup for a <em>QInput </em>component. Below is the Quasar documentation showing how to define such a component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*RHb8fKjcKo1TmbP6wwxb2A.png" /></figure><p>Excluding the outer template and div elements, it takes 7 nested components to create this date field. To make this into a “templatized” component would require providing props for each component in this nest. I didn’t count but this could easily result in over 100 props in order to support every combination of configuration possible!</p><p>I don’t want to manage component templates anymore. I want to have a schema definition that can fully render my components that supports any UI component along with all of it attributes.</p><h3>Research</h3><p>In my research I came across how <a href="https://vuejs.org/v2/guide/render-function.html">Vue renders</a> the UI and how, as a developer, you can use the same render function in your code. In fact, everything inside of template is rendered this way behind-the-scenes. The render syntax can be a little tough to grasp at first. Here is a small example:</p><pre>&lt;script&gt;<br>export default {<br>  render(h) {<br>    h(&#39;q-input&#39;, {<br>      class: [&#39;text-body1&#39;],<br>      props: {<br>        color: &#39;primary&#39;,<br>        label: &#39;First Name&#39;,<br>        value: &#39;fname&#39;,<br>      }<br>    })<br>  }<br>}<br>&lt;/script&gt;<br></pre><blockquote>NOTE: I purposely left out the template section of this Vue component because it cannot be in the file for the render function to take precedence. I learned this the hard way! 😵</blockquote><p>This is the “raw” Vue render code to present my first name field using the <em>QInput </em>component from Quasar Framework.</p><p>What about my nested example from before? That is also covered by the render function! It isn’t in the example above but later on you will see that each component rendered has an optional children parameter. There is no limit to how many children deep you can go. From the Vue documentation, here is the actual syntax of a render component.</p><pre>// @returns {VNode} <br>createElement(   <br>  // {String | Object | Function}   <br>  // An HTML tag name, component options, or async   <br>  // function resolving to one of these. Required.   <br>  &#39;div&#39;,</pre><pre>  // {Object}   <br>  // A data object corresponding to the attributes   <br>  // you would use in a template. Optional.   <br>  {     <br>    // (see details in the next section below)   <br>  },    </pre><pre>  // {String | Array}   <br>  // Children VNodes, built using `createElement()`,   <br>  // or using strings to get &#39;text VNodes&#39;. Optional.   <br>  [     <br>    &#39;Some text comes first.&#39;,     <br>    createElement(&#39;h1&#39;, &#39;A headline&#39;),<br>    createElement(MyComponent, {<br>      props: {<br>        someProp: &#39;foobar&#39;<br>      }<br>    })<br>  ]<br>)</pre><h3>Prototype</h3><p>The prototype was frustrating but fun to build. Let’s walk through a scenario.</p><p>When the user clicks on an Add button we know their intention (“add”) and context (e.g. “doctor”). We load our <em>Form</em> component. The Form component gathers the schema for this context. The <em>Form</em> component then uses a <em>Field</em> component which renders the field UI based on the schema provided. Easy! 😆</p><p>Working backwards, here is my prototype. We will start with example field schema definition.</p><p><em>fieldSchema.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45783dbad387036bea02f6bf1ea7febd/href">https://medium.com/media/45783dbad387036bea02f6bf1ea7febd/href</a></iframe><p>This particular schema is only defining four fields: name, birthdate, gender and mobile. The name component is the simplest because it contains no children. The birthdate component is the most complex as it is handling eight nested components.</p><p>Even though this file could get really large we are only defining form fields one time for the entire application (and all other projects if we choose to re-use it elsewhere).</p><p>The schema includes all aspects of the UI component definition (component name, styles, attributes, classes, props, etc.). Right now I’m using Quasar Framework components. If I start another project that requires another framework I just modify this file and it’s implemented (at least for all form fields).</p><p>Next let’s look at the form schema definitions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dd391141b590602ae2bceb416fb1228/href">https://medium.com/media/1dd391141b590602ae2bceb416fb1228/href</a></iframe><p>The purpose of the form schema is to map the form fields we want to the current context. The context in this case is a combination of collection and event. In other words, if I create a form to add users then, according to this file, I would have a form with the fields: name, birthdate, and gender.</p><p>Thanks to spread operators it is also very simple to implement inheritance. If my context is adding a person, the fields rendered would be name, birthdate, gender and mobile. This can make for a very efficient schema definition.</p><p>Next is the work horse of the prototype, the field rendering component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a97b18730b161c99017cd01857899e9/href">https://medium.com/media/3a97b18730b161c99017cd01857899e9/href</a></iframe><p>Each of our field schema definitions gets passed into this component as field prop. From this schema the component, in its entirety, is rendered.</p><p>There is nothing hard coded to render any component, regardless of its complexity.</p><p>This implementation also supports every configuration possible for every component and nested component you throw at it.</p><p>Let this sink in a minute. Nothing hard coded. All attributes, props, classes, etc., supported.</p><p>Lastly let’s look at the form component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b917262c1bc07e58621779fcbf634848/href">https://medium.com/media/b917262c1bc07e58621779fcbf634848/href</a></iframe><p>The form component is the orchestrator of our awesome solution. This is the only form component we need in our app. It determines context (with the help of Vue Router and some simple mixins to reduce code), gathers the field schema, renders those fields and returns a fully rendered form to the user.</p><h3>Conclusion</h3><p>I assume this is a lot to digest for many of you at first. I suggest you play with the concept to fully grasp the flexibility something like this offers. I’m hoping it drastically reduces my development time while reducing troubleshooting complexities.</p><p>Based on this solution, what would it take to add a new field to a form? Let’s say we want to track email address for our person context.</p><ol><li>Since we don’t have email address defined in our field schema, let’s start there by adding a new key to the root of our schema object.</li></ol><pre>{<br>  ...</pre><pre>  email: {<br>    component: &#39;q-input&#39;,<br>    label: &#39;Email Address&#39;,<br>    model: &#39;email&#39;,<br>    fieldOptions: {<br>      class: [],<br>      on: { input: true },<br>      attrs: {<br>        placeholder: &#39;Enter your email address&#39;,<br>      },<br>      props: {<br>        filled: true,<br>        rules: [<br>          val =&gt; !!val || &#39;Field is required&#39;,<br>          val =&gt; &lt;enter email validation regex&gt; || &#39;Must be valid <br>              email address&#39;,<br>        ],<br>      },<br>      style: {<br>        width: &#39;200px&#39;,<br>      },<br>    },<br>  }<br>  ...<br>}</pre><p>2. Then we need to add the field to our add person context.</p><pre>export const person = {<br>   ...users,<br>   add: {<br>      ...users.add,<br>      mobile: {},<br>+     email: {},<br>   },<br>   update: {<br>      ...users.update,<br>      mobile: {},<br>+     email: {},<br>    },<br>}</pre><p>That’s it! Next time our add person form displays our email address field will be rendered, including its model, components, style, validation, etc.</p><p>There are several aspects to this implementation that I didn’t cover. If anyone is interested into me diving further into this implementation please don’t hesitate to ask.</p><p>More articles by <a href="https://medium.com/u/831caef304ef">Troy Moreland</a></p><p><a href="https://graypes.medium.com/">Troy Moreland - Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=609de4005a2b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/add-dynamic-forms-to-your-vue-app-609de4005a2b">Add Dynamic Forms to your Vue App</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Recurring Rules for Calendar Dates to your Application]]></title>
            <link>https://levelup.gitconnected.com/add-recurring-rules-for-calendar-dates-to-your-application-401e39b56b2f?source=rss-831caef304ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/401e39b56b2f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recurring]]></category>
            <category><![CDATA[scheduling-software]]></category>
            <category><![CDATA[calendar]]></category>
            <category><![CDATA[rrule]]></category>
            <dc:creator><![CDATA[Troy Moreland]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 01:14:56 GMT</pubDate>
            <atom:updated>2020-11-10T17:44:30.434Z</atom:updated>
            <content:encoded><![CDATA[<h4>Spare yourself the pain and suffering by following my journey (and solution) for adding recurring events to your application.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kyV7qD0OVWeHrDSk" /><figcaption>Photo by <a href="https://unsplash.com/@morningbrew?utm_source=medium&amp;utm_medium=referral">Morning Brew</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>My project has a requirement to allow users to set reminders. Reminders can be a one-time or recurring event for any given subject. One-time events are simple enough but once I started thinking about recurring events I realized it can get complicated real fast. 😕</p><blockquote>“I need to set a reminder starting next Tuesday for every other Monday, Tuesday and Friday on odd months for 10 occurrences…”</blockquote><h3>Research Stage</h3><p>Not knowing exactly what to search for, I set about my research quest. Obviously calendar applications have dealt with recurring events for years so I started there.</p><p>This lead me to <a href="https://tools.ietf.org/html/rfc5545">RFC 5545 Internet Calendaring and Scheduling Core Object Specification</a>. If you are having trouble sleeping I highly recommend pulling up this specification and giving it a read! 😴</p><p>I came to the section entitled “Recurrence Rule” (<a href="https://tools.ietf.org/html/rfc5545#page-124">page 124</a> for those following along). It was here that I discovered the [bizarre] syntax known as RRULE.</p><p>Now I knew what I was searching for so I headed over to <a href="https://npmjs.org/">NPM </a>and did a search for “rrule”. Low and behold I found the <a href="https://www.npmjs.com/package/rrule"><em>rrule.js</em></a> package.</p><blockquote>rrule.js supports recurrence rules as defined in the iCalendar RFC, with a few important differences. It is a partial port of the rrule module from the excellent python-dateutil library. On top of that, it supports parsing and serialization of recurrence rules from and to natural language.</blockquote><h3>Prototyping Stage</h3><p>For my prototype I built a new project using <a href="https://quasar.dev/">Quasar Framework</a> (which also provides a full featured <a href="https://github.com/quasarframework/quasar-ui-qcalendar">Calendar app extension</a>). Quasar Framework runs on top of <a href="https://vuejs.org/">Vue.js</a>.</p><blockquote>NOTE: Everything I’m building here will work with any JavaScript framework and Calendar Component. You will just need to massage the data to fit your components requirements.</blockquote><p>For my test data I settled on creating reminders to take out the trash. I knew my wife would approve! 😄 My trash pickup schedule requires that I put out the trash on the following schedule:</p><ul><li>Take out trash bin every week on Sunday and Wednesday at 9 pm</li><li>Take out recycle bin every week on Wednesday at 9 pm</li><li>Take out bulk trash every month on the 4th Wednesday at 9 pm</li></ul><p>The next step was to translate these reminders into RRule syntax. An RRule object can be created by either parsing RRule JSON or RRule string formats. The creators of this library created a <a href="http://jakubroztocil.github.io/rrule/">demo page</a> that acts as a sandbox for playing with different options and seeing their results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c22723d6523b1af1fddbd610b20ac90/href">https://medium.com/media/5c22723d6523b1af1fddbd610b20ac90/href</a></iframe><p>These are the RRule JSON and String representations of my first chore.</p><ul><li>Frequency is weekly</li><li>Starting tonight @ 9pm</li><li>Time zone set to my local time zone because all values are stored as UTC</li><li>Interval is every week</li><li>Occurring on Wednesdays and Sundays</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce953b3ef5991f38b118053386fd198d/href">https://medium.com/media/ce953b3ef5991f38b118053386fd198d/href</a></iframe><p>My second chore schedule was very similar. The only change necessary was to remove the Sunday occurrence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21816961de5c0c2b7aa0d548ce349459/href">https://medium.com/media/21816961de5c0c2b7aa0d548ce349459/href</a></iframe><p>My last chore had a couple of rule differences.</p><ul><li>Frequency was monthly</li><li>Every 4th Wednesday was defined with the bysetpos value</li></ul><p>I verified these rules (and numerous alternatives) on the demo page so at this point I’m comfortable moving on to coding.</p><h3>Coding Stage</h3><p>At a minimum I needed to facilitate managing reminders and then provide a way to display the recurrence of those reminders in human-readable form.</p><h4>Managing Reminders</h4><p>Managing reminders is just a matter of providing CRUD operations but with the unique addition of handling RRULEs. Creating an RRULE form is not something I’m going to cover here as that topic could be an article on its own.</p><p>So, now the question was how to I store the RRULE for each reminder? I need to save the RRULE in a format that can be saved externally and parsed after retrieval. My two options are the RRULE JSON and String formats. Since the RRULE JSON format requires RRULE expressions I decided to save RRULE in their RRULE string format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*oYqIqln99uvFUzD7RNcmVQ.png" /><figcaption>Reminder Manager Page</figcaption></figure><p>I created a relatively simple page that contains a table component that lists all of my reminders and a form component for adding and editing reminders. I also enable a Delete Button when one or more reminders are selected.</p><p>In the form there are two editable fields: Description and RRule String.</p><p>As you enter a valid RRULE string the RRule Text and Sample Schedule fields will immediately display their values from the <em>rrule.js</em> methods. This is a helpful validation for your String.</p><blockquote>NOTE: To enter the RRule string I used the <em>rrule.js</em> demo page to define my rule and then copied and pasted the resulting string into my form.</blockquote><p>In my Vue.js component I added a watch to trigger for any time the RRule String value is changed. The framework agnostic portion of the code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0292d8589fdd4f4fa7b828310e537a19/href">https://medium.com/media/0292d8589fdd4f4fa7b828310e537a19/href</a></iframe><p>The value from the RRule String field is stored in the rruleString variable. I then use the rrulestr() method to parse the RRule String. If that results in a value RRule object I can use the toText() and all() methods to extract and populate the RRule Text and Sample Schedule fields. These methods are all provided by the <em>rrule.js</em> package and their documentation provided the example for getting the first five occurrences.</p><p>Once Saved, each reminder is stored as a JavaScript object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ba7e2f4286b19f40f7afda96beb9032/href">https://medium.com/media/8ba7e2f4286b19f40f7afda96beb9032/href</a></iframe><h4>Displaying Reminders</h4><p>Now that my reminders are being created, updated and deleted I moved on to the display portion of the code. 😵</p><p>First I like to just display my data in the raw to make sure I’m getting the data I’m expecting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*gP1B9jqpvZm3QG1-J8M9qg.png" /><figcaption>Data in the Raw</figcaption></figure><p>Next I wanted to include the parsed RRULE and to display the next few upcoming reminders for each chore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*mvWQMzMVScANWaKAySm0Tg.png" /><figcaption>Display Chores and Next Five Scheduled Reminders</figcaption></figure><p>This display does show the actual schedule data but the is not ideal for the situation. The display should be grouped by the date and then time and then by chore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*Qj6TnHmKN5zGpB8MunF5zQ.png" /><figcaption>Grouped Results</figcaption></figure><p>That looks better. 🔮🦄 (← that means it was “magic”)</p><p>Notice I changed the time for the “Take out bulk trash” just to make sure the times were grouping properly.</p><p>OK, that’s it! :</p><p>Well… almost. I would feel like I’ve cheated you if I did not include this last part.</p><h3>Working with Dates</h3><p>It took me about 24 hours to build this scenario. It should have taken half that but I ran into problems with date and time inconsistencies.😬</p><p>Working with dates and times can always be problematic, especially when you can’t guarantee that your application and the consumer are in the same time zone. Getting time zone settings wrong can result in a mess. The <em>rrule.js</em> library states numerous times that to use UTC (otherwise known as GMT or Zulu) as it is the basis for local times worldwide.</p><p>First of all, I had to go back and add TZID and my time zone in my RRule string. This is required if I’m entering the local date and time which is normally what happens with end user input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ded77f5695eaa35825bd80266adabebd/href">https://medium.com/media/ded77f5695eaa35825bd80266adabebd/href</a></iframe><p>After this change I was still unable to get the between() method to return the correct results. The results were always outside of my date range. Then I noticed the <em>rrule.js</em> documentation showed the same problem!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*z2ZADwoH43PzRwgB-Rtc4Q.png" /><figcaption><a href="https://github.com/jakubroztocil/rrule">Oops!</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*tZ0WhXMKX_6kYQRDDCG3Jg.png" /><figcaption>Oops, again!</figcaption></figure><p>There was another example in their documentation but why beat a dead horse, am I right? 🐴 ❓</p><p>Notice how the returned dates are outside the between() scope? At least I felt better seeing this knowing it wasn’t just me! 😆</p><p>I spent a little bit of time looking at alternative libraries but soon gave up on that idea. Then I started playing with the <a href="https://momentjs.com/">moment.js</a> library to help calculate future dates. I use this library for date and time related features in all of my projects.</p><p>After hours [of pulling out my hair] I finally dumped the use of JavaScript Date (e.g. new Date())completely and instead relied 100% on <em>moment.js</em> methods. I can’t explain why this worked but it did. For the first time I was getting my expected results from <em>rrule.js</em>. To give you an idea of what I mean, take a look at the function I wrote to handle the grouping of my reminders.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81a58c0036b432e1d335c17aba659a42/href">https://medium.com/media/81a58c0036b432e1d335c17aba659a42/href</a></iframe><blockquote>NOTE: I am also using the <em>lodash</em> library to simplify the sorting, iterating and grouping.</blockquote><p>The reminders variable that is passed into this function contains an array of objects. Each object is a chore and looks like this (the rrule element has already been parsed into an RRule object):</p><pre>{<br>  id: 1,<br>  descr: &#39;Take out the trash&#39;,<br>  rrule: {...}<br>}</pre><p>Now we need to break out some of the upcoming dates from our RRule object, group them by date, group them again by time and then list out the chores that occur within that date and time grouping.</p><p>The groupByDate function (above) does just that and the results look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c10219152c6c69e33512e0b18c5067a8/href">https://medium.com/media/c10219152c6c69e33512e0b18c5067a8/href</a></iframe><h3>Conclusion</h3><p>I hope this article helps you fast track adding recurring events to your application. I feel like everyone can relate to scheduled events since we use them all of the time, even daily. Now you can add them to your own application or, perhaps, this will inspire you to write your own “Reminder” app. 👍</p><p><a href="https://github.com/34fame/rrule-demo">34fame/rrule-demo</a></p><p>More articles by <a href="https://medium.com/u/831caef304ef">Troy Moreland</a></p><p><a href="https://graypes.medium.com/">Troy Moreland - Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=401e39b56b2f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/add-recurring-rules-for-calendar-dates-to-your-application-401e39b56b2f">Add Recurring Rules for Calendar Dates to your Application</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>