<?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 Dre May on Medium]]></title>
        <description><![CDATA[Stories by Dre May on Medium]]></description>
        <link>https://medium.com/@drewword?source=rss-effad8ca3b27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1UEz_-EOf_dyc4WZvLuzRg.png</url>
            <title>Stories by Dre May on Medium</title>
            <link>https://medium.com/@drewword?source=rss-effad8ca3b27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:03:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drewword/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[A Rules Engine in 11 Lines of JS]]></title>
            <link>https://drewword.medium.com/a-rules-engine-in-11-lines-of-js-f00d9ea7dae7?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/f00d9ea7dae7</guid>
            <category><![CDATA[rules]]></category>
            <category><![CDATA[rules-engine]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[drools]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 18:58:06 GMT</pubDate>
            <atom:updated>2022-08-10T18:58:06.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKPjURn9gk4OEJiyOtyw8w.png" /></figure><p>The concept of a rules engine will inevitably come up at some point if you are a developer. The flurry of phrases from business people and developers alike will range from “You can’t write that many IF statements” all the way to “We need to foster citizen developers to get this out of IT”.</p><p>This will lead to a search for [insert language here] rules engines, on Github or just a general Google search. Scouring through the ads of commercial companies, the allure of a rule engine becomes mysterious and mystical in nature. Of course Drools / JBOSS Rules will show up in that list, and you will have to figure out how to Dockerize it and stitch it into your environment.</p><h3>Peeling back the onion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpGldhK5HHiFH-5sGWQ6uQ.png" /></figure><p>So what if we try to peel back the onion? Is a Rules Engine just a more elegant way of organizing a bunch of IF statements? It seems potentially similar to the <strong><em>Chain of Responsibility design pattern</em></strong>, but does it completely fit here? I decided to take a look, using some pseudo code. But when I was done, I took a second look, and it appears I had built an actual functional rules engine. In only 12 lines of JavaScript!</p><h3><strong>The General Concept</strong></h3><p>The general concept of a rules engine, is that you have a set of “facts”, and then actions or outcomes that result from a set of rules. The classic example for a rules engine, is something like:</p><blockquote><strong>Rule:</strong> If it is raining, take an umbrella.</blockquote><blockquote><strong>Fact:</strong> It is raining.</blockquote><blockquote><strong>Outcome:</strong> Take an umbrella.</blockquote><h3>Initial Example</h3><p>Instead of trying to write the “engine” first, I took a crack at writing how this could be passed into a general purpose evaluator.</p><p>I came up with something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrqzgP4BTN8_10usYHeV7w.png" /></figure><p>The example topic was generally taken from the Wikipedia article on Decision tables: <a href="https://en.wikipedia.org/wiki/Decision_table">https://en.wikipedia.org/wiki/Decision_table</a></p><p>Using ES6 arrow functions, and having one parameter that contains the “facts”, how concise could things get? It’s not as concise as putting the facts in an Excel spreadsheet type table, but the goal was to understand the concepts, and not re-build an elaborate engine. In this form, the rules almost appear if they have been written in a dedicated DSL (Domain Specific Language). So, the only thing left was to add an implementation! So let’s see how the 12 lines of JavaScript stack up.</p><h3>The 11 Lines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caszy75-5L_kSSdCfOv-oA.png" /></figure><p>The above class has two specific facets:</p><ol><li>Collecting the set of rules.</li><li>Providing an iterator that executes the rules based on a set of “facts” or “domain”, and returning when a rule is true.</li></ol><p>There aren’t any fancy features here, but again, the goal is to understand the mechanics behind a rules engine, and not to build something on parity with Drools.</p><p>The interesting tidbit is the execution of a rule by simply assuming its a function that has been passed in with:</p><pre><strong><em>rule(domain)</em></strong></pre><p>This executes the code that has been passed in, and assumes completion if a true result is returned.</p><p>Adding a few more lines after our rules evaluation, will yield the below console output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WOXO7KZ3S748F-YRHV5yA.png" /></figure><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*NM3P3m4i4OU2QlfkGz_f7Q.png" /></figure><h3>The full example</h3><p>Below is the full example that you can copy in paste into your own environment:</p><pre>class RuleEval {<br>  ruleSet = new Map();<br>  addRule(rule, result) {<br>    this.ruleSet.set(rule, result);<br>  }<br>  evalRules(domain) {<br>    for ( const [rule, result ] of this.ruleSet ) {<br>      if ( rule(domain) ) return { rule: rule, result: result };<br>    }<br>  }<br>}</pre><pre>let ruleEval = new RuleEval();<br>ruleEval.addRule(<br>(facts) =&gt;<br>facts.temp &gt; 100 ,<br>&#39;dont play golf!&#39;<br>);</pre><pre>ruleEval.addRule(<br>  (facts) =&gt;<br>  facts.outlook === &#39;sunny&#39; &amp;&amp;<br>  facts.temp &gt; 95,<br>  &#39;dont play golf!&#39;<br>);<br>ruleEval.addRule(<br>  (facts) =&gt;<br>  facts.outlook === &#39;overcast&#39; &amp;&amp;<br>  facts.temp &gt; 50 &amp;&amp; facts.temp &lt; 70 &amp;&amp;<br>  ! facts.windy ,<br>&#39;play golf!&#39; );</pre><pre>let answer = ruleEval.evalRules(<br>{<br> outlook: &#39;overcast&#39;,<br> temp: 65,<br> windy: false<br>}<br>);</pre><pre>if ( answer ) {<br>  console.log ( `Rule: ${answer.rule} result: ${answer.result}` );<br>}</pre><h3>Conclusion</h3><p>Hopefully this example provides a useful start on exploring how the concept of a rules engine works. In its crudest form, it could potentially make a tree of IF statements look more elegant than they really are.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f00d9ea7dae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unclogging Node with Workers]]></title>
            <link>https://drewword.medium.com/unclogging-node-with-workers-2b05d9c479a3?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b05d9c479a3</guid>
            <category><![CDATA[node]]></category>
            <category><![CDATA[worker-node]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 15:54:34 GMT</pubDate>
            <atom:updated>2022-07-11T15:54:34.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ZW8v3ArtGDzB9PJW_h6aQg.png" /></figure><h3>Did you just discover …</h3><p>Did you just discover that NodeJS is single threaded? Maybe you are new to NodeJS development. Maybe you have been using Node within an environment where the threading model was never a concern, for instance within AWS Lambda. For whatever reason, discovering and understanding Node’s threading model can usually elicit a couple of reactions:</p><blockquote>“Oh that’s cool!”</blockquote><p>or</p><blockquote>“Really? So what do I do now?”</blockquote><h3>An Arrow in the Quiver</h3><p>This article will focus on <strong><em>one</em></strong> of the options available within the NodeJS environment. This is not the only option, but could be considered as one of the options that might fit into a larger architecture. This article outlines usage of Node Worker threads. For demonstration purpose, the code presented will utilize the Piscina worker pool library. (<a href="https://github.com/piscinajs/piscina">https://github.com/piscinajs/piscina</a>)</p><h3>Demonstrating the Problem</h3><p>Let’s say you have an awesome NodeJS setup that suits your needs perfectly. One last bit of functionality is required that demands you process an image file in a minimal way. This processing however is CPU intensive, which winds up tying up the primary event loop of Node. Whenever this CPU intensive operation is called, it blocks <strong><em>all</em></strong> other calls. Within Chrome dev tools, this may look something like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DF8v-9fFlt4LxwsvetI2wA.png" /></figure><p>This demonstration API takes a parameter of how long to “sleep” or tie up the CPU. In this case, a 10 second timeout request is initially sent, with a one second sleep request sent immediately after. Since NodeJS can only handle a single thread of work, the second request has to wait until the first is complete.</p><p>Using an alternate version utilizing a worker, the Chrome network request tab looks much different as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtDh-yaZOzEsMYcCs1pFsQ.png" /></figure><p>The second request no longer needed to wait for the first request to complete. This may be the difference between a responsive server, and a server that leaves a client waiting for a completely different request to complete.</p><h3>Worker Pool Example</h3><p>Below are the complete NodeJS files used to produce the above results.</p><p><strong><em>server.js</em></strong></p><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const sleeper = require(&#39;./sleep&#39;);<br>const path = require(&#39;path&#39;);<br>const Piscina = require(&#39;piscina&#39;);</pre><pre>// https://nodejs.org/api/worker_threads.html#worker-threads</pre><pre>const app = express();<br>const port = 3030;<br>app.use(cors());<br>const piscina = new Piscina({<br>  filename: path.resolve(__dirname, &#39;worker.js&#39;)<br>});</pre><pre>app.get(&#39;/message&#39;, (req, res) =&gt; {<br>  var theTimeout = req.query.timeout;<br>  theTimeout = ! theTimeout ? 2000 : theTimeout;<br>  sleeper.sleep(theTimeout);<br>  res.send({result:`client requested timeout was ${theTimeout}`});<br>})</pre><pre>app.get(&#39;/message-worker&#39;, async (req, res) =&gt; {<br>  var theTimeout = req.query.timeout;<br>  theTimeout = ! theTimeout ? 2000 : theTimeout;<br>  const result = await piscina.run({ millis: theTimeout });<br>  res.send ( {result:result });<br>});</pre><pre>app.listen(port, () =&gt; {<br>  console.log(`Demo app listening on port ${port}`)<br>});</pre><p><strong><em>sleep.js</em></strong></p><pre>function sleep(milliseconds) {<br>const date = Date.now();<br>let currentDate = null;<br>do {<br>  currentDate = Date.now();<br>  } while (currentDate - date &lt; milliseconds);<br>}<br>exports.sleep = sleep;</pre><p><strong><em>worker.js</em></strong></p><pre>const sleeper = require(&#39;./sleep&#39;);<br>module.exports = ({ millis }) =&gt; {<br>  sleeper.sleep(millis);<br>  return `waited in worker.... ${millis} millis.`;<br>};</pre><p>There are two main entry points, message, and message-worker. The <strong><em>message</em></strong> path simply calls the sleep function to simulate running a CPU intensive process. The <strong><em>message-worker</em></strong> method delegates to the worker.js which runs in a new thread within Node.</p><h3>Gotchyas</h3><p>Using this technique to free up Node’s main thread can be applied in some situations, but it’s not a cure-all for anytime you run into troubles. Resources are not free, and eventually you will wind up in trouble if this is used for every request in your backend. Some questions you should ask yourself are:</p><ul><li>What should my resource cap be if this functionality is called multiple times?</li><li>Are there options for deployment that mitigate the need to adding complexity to my Node application?</li><li>Is this a bandaid for a larger usage issue?</li></ul><h3>Conclusion</h3><p>Hopefully this article shed some light on a simple mechanism to alleviate a CPU intensive path within a NodeJS application. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b05d9c479a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Poster Art with Jimp]]></title>
            <link>https://drewword.medium.com/typescript-poster-art-with-jimp-19bd0dee2c05?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/19bd0dee2c05</guid>
            <category><![CDATA[posters]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[jimp]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Wed, 05 May 2021 01:10:14 GMT</pubDate>
            <atom:updated>2021-05-05T01:10:14.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUEJlMbGMIP2dT7yL8EDBw.jpeg" /></figure><p>Many years ago I wanted an easy and cheap way to print poster sized pictures without paying a premium at the local pharmacy. I thought if I could slice up a single picture into multiple 4x6 sized photos, I could just send the batch in for printing, and piece them together on a larger poster board at home. I also wouldn’t have to worry about wrinkling up the poster, I could just shove all of the pictures in my pocket.</p><p>At the time, 3 megapixel cameras were all the rage, and Java was still new and exciting. I processed a couple of photographs, put them in frames, and enjoyed them for years. Even with the low resolution and blowing them up to a larger size, the effect of assembling a larger picture from several smaller ones made them all a piece of art.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PTlytIDM2tenFpDJFJqPSA.jpeg" /></figure><p>So, now on vacation, I wanted to process some more photographs. I had no idea where that program went, and it’s probably several generations of laptops lost. I thought it has to be easier with all of the new libraries out there, and indeed it was. It will probably take me longer to write this article than to use the JavaScript image processing library Jimp. I followed their TypeScript instructions, and had something together in no time. (<a href="https://www.npmjs.com/package/jimp">https://www.npmjs.com/package/jimp</a>). I thought I would share my sample program, in case anyone wants to have some TypeScript fun, or is looking for an example on using Jimp with TypeScript.</p><h3>Getting Started</h3><p>In order to run the example, you will need Node.js and TypeScript installed. Then navigate over to github to download the source here: <a href="https://github.com/drewword/jimp-poster">https://github.com/drewword/jimp-poster</a></p><p>Next, transpile the TypeScript with tsc, and execute the program with an example below:</p><pre>node poster.js ./boat.jpg 6</pre><p>The first parameter is the image your want split into multiple pieces, the next is the number of images to produce in the horizontal axis. The default is to produce 4x6 photos. In the above example, 6 photos would be produced making the overall width 36 inches.</p><p>The final row of images may be cutoff if the overall image is not the exact dimensions of 4x6. Please feel free to make plenty of modifications to the original source, if there is a better way to produce the overall image, please branch the original source.</p><h3>The Code</h3><p>The main section that performs all of the work is a simple nested loop. The interesting parts of Jimp usage are the creation of a new temporary image, and the blitting of a section of the original image to the temporary image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*lr9EQLI50GcmEgmjZy4tmw.png" /></figure><p>The final steps are to make the image section larger to ensure it’s friendly for drugstore printing, and to write the image out to disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*D2wromu7YDcEuR78u_nz8Q.png" /></figure><p>You should see output similar to below after you run an image through:</p><pre>Image to process: ./boat.jpg<br>Horizontal count of images: 6<br>processing image ...<br>Number of total images: 30</pre><p>Next simply upload everything to your drugstore of choice, pick them up and assemble the stack of photos to your medium of choice. I may take a future version to the web as a client side only poster-maker.</p><p>I hope you enjoy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19bd0dee2c05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Gateway Express.js Greedy Paths to a full stack with Vue.js]]></title>
            <link>https://drewword.medium.com/api-gateway-express-js-greedy-paths-to-a-full-stack-with-vue-js-c11adfc1ecd3?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/c11adfc1ecd3</guid>
            <category><![CDATA[aws-documentdb]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 00:48:30 GMT</pubDate>
            <atom:updated>2020-11-14T00:48:30.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*fUm8zEwAKO5yMj5TbK2AoA.png" /></figure><p>What do you do when you want to take your Express.js app from your desktop to AWS? Is there an easy way to simply deploy your code “as-is” to Lambda? Yes there is!</p><p>Using the <strong>aws-serverless-express</strong> node module, along with the Abstract Factory design pattern, you can easily switch from a prototype mode to a real-life app completely self-contained and served from Lambda.</p><h3>Should I be Serving HTML From Lambda?</h3><p>Serving HTML, along with the rest of your APIs from a single Lambda isn’t the best path to a production app; however, if you are trying to quickly put together a demo, without a lot of organizational overhead, having some deployment tricks up your sleeve can make you look like the hero.</p><h3>What are we building?</h3><p>The overall demo application we are going to build is a full end to end application using <strong>Vue.js</strong>, <strong>Express.js</strong>, <strong>Lambda</strong>, and <strong>AWS DocumentDB</strong> with the <strong>MongoDB</strong> APIs. All of this will be written in Typescript and deployed with the AWS CDK.</p><p>The end result will be a simple guest book application that has two functions — adding a guestbook entry, and retrieving all guestbook entries. You can see a screenshot of the application depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*WW-k5IVQgGMkScx8RD106w.png" /></figure><h3>Getting the Source</h3><p>Before going too far, make sure to download the source from Github at the link below.</p><p><a href="https://github.com/drewword/vue-express-lambda-mongo">https://github.com/drewword/vue-express-lambda-mongo</a></p><h3>Prerequisites for Running the Demo</h3><p>In order to run the demo, you will need the following:</p><ul><li>Working node installation.</li><li>Typescript installed.</li><li>An AWS account.</li><li>The AWS CDK installed.</li></ul><h3>Getting Up and Running Locally</h3><p>To get up and running locally, after downloading the source, run <strong>npm install</strong> in the root directory, then change directories to the <strong>guestbook-server</strong> directory and run npm install there as well.</p><p>You can then run npm build from the same guestbook-server directory to convert the Typescript to JavaScript. After the source is converted, type the below command to run locally.</p><pre>&gt; LOCAL_MODE=1 node server.js</pre><p>Local mode is the flag that triggers listening to a local port in order to test. After starting the local Express application, navigate to the below URL:</p><p><strong>http://localhost:8080/demo-site/</strong></p><h3>Express App Walkthrough</h3><p>Below is a subset of the Express.js application that will be served from Lambda. (some lines are omitted here for clarity). Here we are using the “Embedded JavaScript Template” engine to perform simple variable replacement, passing the base URL for API calls. This is a step that is not completely necessary here, although could lead as a stepping stone if you wanted to migrate static content to S3. This is essentially the endpoint to use when the Vue.js application is posting API requests.</p><pre>const app = express();<br>const PORT = 8000;<br>const guestBookDAO:GuestbookDAO = new DAOFactory().getDAO();<br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);</pre><pre><strong>app.get</strong>(&#39;/demo-site/&#39;, async(req, res) =&gt; {<br>    let baseLambdaURL = process.env.BASE_URL || &quot;&quot;;<br>    res.render(&#39;index&#39;, { baseURL: baseLambdaURL });<br>});</pre><pre><strong>app.post</strong>(&#39;/demo-site/add-entry&#39;, async (req, res) =&gt; {<br>    guestBookDAO.addGuest(req.body.firstName, req.body.lastName);<br>    res.send(&quot;{status:&#39;OK&#39;&quot;);<br>});</pre><p>The other initial item to note is the GuestbookDAO. This is a Typescript interface that utilizes the Abstract Factory Pattern to either serve a DocumentDB backed DAO, or a local mock version of a in-memory database. A quick look inside the DAOFactory reveals the switch between local and live.</p><pre>export class <strong>DAOFactory</strong> {<br>  <strong>getDAO</strong>():GuestbookDAO {<br>    if ( <strong>process.env.LOCAL_MODE</strong> ) {<br>      console.log (&quot;Using Test DAO.&quot;);<br>      return new <strong>TestDAO</strong>();<br>    }<br>    console.log (&quot;Using MongoDB DAO.&quot;);<br>    return new <strong>MongoDAO</strong>();<br>  }<br>}</pre><p>If the LOCAL_MODE environment variable is set, the factory will return an instance of the TestDAO, otherwise it will return the MongoDAO. When deployed to AWS, the LOCAL_MODE flag will not be defined.</p><p>The final switch is used within the main <strong>server.ts</strong> Express application to determine if the local server should be started, or if the <strong>serverless-express</strong> proxy should be used.</p><pre>if ( process.env.<strong>LOCAL_MODE</strong> ) {<br>  <strong>app</strong>.<strong>listen</strong>(PORT, () =&gt; {<br>  console.log(`⚡️[server]: Server is running at<br>    https://localhost:${PORT}`);<br>  });<br>}<br>else {<br>  const server = <strong>serverlessExpress</strong>.<strong>createServer</strong>(app);<br>  exports.handler = (event:any = {}, context:any) =&gt; {<br>  <strong>serverlessExpress</strong>.<strong>proxy</strong>(server, event, context);<br>}</pre><p><strong>Express.js</strong> doesn’t know what to do with a Lambda request, this is where the <strong>serverless express proxy</strong> comes into play. This translates AWS Lambda requests to something Express.js can understand, along with the corresponding output. The serverless express project is located here on GitHub: <a href="https://github.com/awslabs/aws-serverless-express">https://github.com/awslabs/aws-serverless-express</a>.</p><h3>Vue.js Code Walkthrough</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*iYFz2UGrsRLHHJwsHSA9Qg.png" /></figure><p>So at this point, hopefully you have a handle of the general Express application that can either be deployed locally, or deployed to AWS Lambda using the serverless express proxy. Now it’s time to explore what application is being served. This is our Vue.js guestbook. The code for the Vue.js application can be found in <strong>guestbook-server/public/index.ejs</strong>.</p><p>This article won’t be a deep-dive into Vue.js, as that can be an entire subject to itself. I will go over the general highlights of the application however. One thing to note, and this is my personal opinion, is that Vue.js is so much easier to craft a simple application over Angular or React. I’m unsure of the scalability overall of using Vue.js in a larger application; but using Vue.js in smaller prototype applications is a perfect fit with Express.js.</p><p>Below is a subset of the Vue.js application which renders the guestbook form. Some code has been omitted for clarity.</p><pre>&lt;h1&gt;Welcome to the Guestbook&lt;/h1&gt;</pre><pre>First Name: <br>&lt;<strong>input</strong> <strong>v-model</strong>=&quot;firstName&quot; class=&quot;form-control&quot;&gt;</pre><pre>Last Name: <br>&lt;<strong>input</strong> <strong>v-model</strong>=&quot;lastName&quot; class=&quot;form-control&quot;&gt;</pre><pre>&lt;<strong>button</strong> <strong>v-on:click=&quot;submitEntry&quot;</strong> <br>  class=&quot;btn btn-primary&quot;&gt;Add Name to Guestbook&lt;/button&gt;</pre><pre>&lt;<strong>button</strong> <strong>v-on:click=&quot;getEntries&quot;</strong> <br>  class=&quot;btn btn-info&quot;&gt;Get Entries&lt;/button&gt;</pre><pre>&lt;ul&gt;<br>  &lt;li <strong>v-for=&quot;user in users&quot;</strong>&gt;<br>    <strong>{{user.firstName}} {{user.lastName}}</strong><br>  &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>The two inputs for first name and last name, are backed by the Vue.js application data. The two other form controls are a button that triggers the submit entry functionality, and a button to get all entries from MongoDB (DocumentDB).</p><p>Below is a main highlight from the Vue.js application definition in the same file, defining the method for submitting entries. I have used the axios library here to handle posting to the server.</p><pre>var <strong>app</strong> = new <strong>Vue</strong>({<br> el: &#39;#app&#39;,<br> <strong>data</strong>: {<br>   firstName: &#39;&#39;,<br>   lastName: &#39;&#39;,<br>   users:[]<br>},<br><strong>methods</strong>: {<br> <strong>submitEntry</strong>: function() {<br>  <strong>axios.post</strong> (&quot;<strong>&lt;%= baseURL %&gt;/demo-site/add-entry</strong>&quot;, {<br>      <strong>firstName</strong>: this.firstName,<br>      <strong>lastName</strong>: this.lastName<br>    }).then((response) =&gt; {<br>      <strong>console.log</strong>(&quot;Added guestbook entry.&quot;);<br>    }, (error) =&gt; {<br>      <strong>console.log</strong>(error);<br>  });</pre><h3>Building the Infrastructure with the AWS CDK</h3><p>The AWS CDK code establishes two separate stacks. The initial stack creates the Lambda, API Gateway entry, and the DocumentDB cluster. The second stack modifies the Lambda parameters with the DocumentDB connection string. Here I ran into a few cases where the CDK did not want to deploy due to circular references. I found migrating the addition of the MongoDB connection string to the second stack cleared everything up. The primary code for the CDK deployment can be found in the file <strong>full-vue-proto-stack.ts</strong>.</p><h3>API Greedy Path Variables</h3><p>When defining the API Gateway endpoint, using the method <strong>addProxy</strong> will proxy all calls to the paths of the Lambda in order to route to the Express.js application.</p><pre>var <strong>apiEndpoint</strong> = new <strong>apigateway.RestApi</strong>(this, &quot;demohtml-lambda&quot;, {<br>  restApiName: &quot;RESTExpress&quot;,<br>  description: &quot;Simple hello world lambda.&quot;<br>});<br><strong>apiEndpoint</strong>.root.<strong>addProxy</strong>({<br>  defaultIntegration:<br>  new apigateway.LambdaIntegration(lambdaFunction)<br>});</pre><p>This puts an entry in API Gateway that looks like below:</p><p><strong>/demo-site/{proxy+}</strong></p><p>For details on using this within API Gateway, see the AWS release notes here: <a href="https://aws.amazon.com/blogs/aws/api-gateway-update-new-features-simplify-api-development/">https://aws.amazon.com/blogs/aws/api-gateway-update-new-features-simplify-api-development/</a>. Using greedy paths in addition to using the serverless express library is the secret sauce to a fast and easy deployment.</p><h3>Building and Deploying to AWS</h3><p>From the root directory of the project, run the following.</p><pre>&gt; <strong>npm run build</strong><br>&gt; <strong>cdk deploy --all</strong></pre><p>After deploying with the CDK, the CDK will output display an item similar to below.</p><p><strong>FullVueProtoStack.demohtmllambdaEndpointXXXX</strong>=[SOME URL]</p><p>Use that URL with the addition of <strong>/demo-site/</strong> to display the results from Lambda.</p><h3>Final Bits with MongoDB</h3><p>This article would be entirely too long to go in-depth on utilizing MongoDB within a Node environment; however, hopefully the simple usage can get you started. MongoDB compatibility for AWS DocumentDB can be a great way to use an AWS managed service for your MongoDB needs. Note that if you are using advanced features of MongoDB, please check for API compatibility.</p><p>Locate the file <strong>MongoDAO.ts</strong> within the guestbook-server directory for how to connect, insert items into the database, and retrieve a collection of entries.</p><h3>Final Thoughts</h3><p>This article is probably longer than I would have liked, and going in-depth on any one topic would make the article length unbearable. However, my goal was to make each part of the code as succinct as possible to illustrate the full end-to-end process.</p><p>Don’t forget to check out the code on GitHub here: <a href="https://github.com/drewword/vue-express-lambda-mongo">https://github.com/drewword/vue-express-lambda-mongo</a>.</p><p>In addition, don’t forget to run <strong>cdk destroy</strong> as well to avoid getting an unexpected AWS bill. The DocumentDB policy is set to destroy, so anything created during the demo will be eliminated in favor of keeping a small bill. In production, you would want to change this policy to keep the database around.</p><p>Happy AWS coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c11adfc1ecd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure voting with AWS WAF, API Gateway, and CDK]]></title>
            <link>https://drewword.medium.com/secure-voting-with-aws-waf-api-gateway-and-cdk-e830439ee75e?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/e830439ee75e</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-api-gateway]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-waf]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Mon, 24 Aug 2020 15:10:58 GMT</pubDate>
            <atom:updated>2020-08-24T15:10:58.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTRu3W_9f-715Nk8ObGY1A.png" /></figure><p>Internet voting may never become a reality; however, securing your APIs should always be on the forefront of standard development practices. One of the tools offered by AWS to secure your application is the AWS WAF. The AWS WAF can be configured through the AWS console in order to create web access control lists and add individual firewall rules. Using the console for security engineers is a good start; however, provisioning of cloud resources through ClickOps is not considered a best practice in software development. This is where the AWS CDK comes in.</p><h3>Codifying ClickOps WAF configuration</h3><p>The AWS CDK is one of the tools offered from AWS in order to create Infrastructure as Code (IaC). The CDK differentiates itself from other tools such as Terraform by using standard programming languages instead of a domain specific language (DSL). Since the CDK is one of the new up and coming methods for creating IaC, that is what will be used for this article.</p><p>In this article I will outline my experience using the CDK, present source code to a simple example that blocks API access by country code, and recommend ways to streamline development when configuring the WAF with the CDK.</p><h3>The Source Code</h3><p>The source code for this article can be located here in GitHub:</p><p><a href="https://github.com/drewword/aws-cdk-waf-country-block">https://github.com/drewword/aws-cdk-waf-country-block</a></p><h3>State of The CDK</h3><p>The current version of the CDK that I used for the demo is 1.59.0. The CDK is receiving updates all of the time, so things may have changed or improved by the time you read this article. When using the CDK, there are various layers of library support classes. These range from the AWS solutions constructs (<a href="https://aws.amazon.com/solutions/constructs/">https://aws.amazon.com/solutions/constructs/</a>) all the way down to providing escape hatches for getting around things that aren’t available yet. (<a href="https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html">https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html</a>)</p><p>Currently the state of support for the AWS WAF is towards the lower end, where simple CloudFormation wrapper classes are provided. Not ideal.</p><p>When looking at other IaC options, I noticed that Terraform isn’t much better at this stage either.</p><h3>Versions of CloudFormation WAF</h3><p>It appears that there are several different versions of CloudFormation code to use when coding the WAF as well, which doesn’t make things any easier. From what I could determine, WAFv2 was the best option to utilize, and the shadow CDK classes for v2: (<a href="https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html">https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html</a>)</p><h3>Ready to Use Rules</h3><p>Fortunately the AWS WAF does provide pre-configured rules that could easily be used in conjunction with CDK configuration, so this might be an option to follow up on for some organizations. (<a href="https://aws.amazon.com/about-aws/whats-new/2017/11/ready-to-use-managed-rules-now-available-on-aws-waf/">https://aws.amazon.com/about-aws/whats-new/2017/11/ready-to-use-managed-rules-now-available-on-aws-waf/</a>) I wanted to configure my own rules, so that is what this article will focus on.</p><h3>Rolling Wrappers</h3><p>The best option I can recommend at this point if you are going head first into using the CDK with the AWS WAF would be to create some wrapper classes around some of the common configuration you may want to deploy. There will obviously be a balancing act between creating your own CDK library vs. simply using what’s available; however, when only the CloudFormation “Cfn” classes are available, that is probably the best way to insulate yourself from the implementation details.</p><h3>Examining the Code</h3><p>OK, enough sounding like a politician, let’s get busy blocking our API from foreign actors in our fictitious voting API.</p><p>To start with, we will create a very simple Lambda, and pass that Lambda to our Country Code Blocker class. Here is the demo CDK stack that combines the two. On line 11, a country code array is passed in to the CountryCodeBlocker. We will start with blocking the US. For a United States presidential election, we at least need to block ourselves. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*I2YZLw6zS8Ij9nAExZcIYQ.png" /></figure><p>The HelloWorldLambda simply creates a hello world API, or any other API that you would want to add some WAF protection.</p><h3>Blocking Countries</h3><p>In order to attach our WAF to our API, there are essentially two steps.</p><ol><li>Create a WebACL with an array of rules.</li><li>Create the association with the resources.</li></ol><p>For step 1, you will see on line 19 the creation of the web access control. (Within <strong><em>CountryCodeBlocker.ts</em></strong>) This is using the CDK wafv2 API (which mirrors the CloudFormation WAF v2 API). As you can see, this is not necessarily the most readable. It’s really passing in general JSON configuration to an API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*b941Etlv-7YqgZtJgmMH8Q.png" /></figure><p>Keeping the code short was essential here, as lower level classes of the CDK is not the brightest point of the toolkit. This is where I recommend wrapping your desired functionality in your own class, and giving your developers an easier time at implementing this for their multitude of APIs.</p><h3>Creating the Rule Association</h3><p>Luckily the call to make the association from either your load balancer, or API Gateway endpoint is relatively straightforward as show below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*ZmRmGh_reeHsGm8wkNTVig.png" /></figure><p>The API Gateway ARN must be constructed per the AWS CLI documentation. (<a href="https://docs.aws.amazon.com/cli/latest/reference/wafv2/associate-web-acl.html">https://docs.aws.amazon.com/cli/latest/reference/wafv2/associate-web-acl.html</a>), as follows:</p><p>The ARN must be in one of the following formats:</p><blockquote>For an Application Load Balancer: <a href="https://docs.aws.amazon.com/cli/latest/reference/wafv2/associate-web-acl.html#id1">``</a>arn:aws:elasticloadbalancing:<em>region</em> :<em>account-id</em> :loadbalancer/app/<em>load-balancer-name</em> /<em>load-balancer-id</em> ``</blockquote><blockquote>For an Amazon API Gateway stage: <a href="https://docs.aws.amazon.com/cli/latest/reference/wafv2/associate-web-acl.html#id3">``</a>arn:aws:apigateway:<em>region</em> ::/restapis/<em>api-id</em> /stages/<em>stage-name</em> ``</blockquote><p>Here is the implementation for <strong><em>getResourceARNForEndpoint</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcNj1kSV0wgeryhwwl_E5w.png" /></figure><p>The final bits of interest is the creation of the wafv2 CfnWebACL RuleProperty. This is show below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*1Y5PFEJH9WHCBRR4yGmA8g.png" /></figure><p>This has very rough checks for ensuring the rule conforms to the “RuleProperty” class; however, this does not ensure your configuration will work properly. Some JSON blocks are required for some rules, and others will blow up with odd exceptions if configured incorrectly. If in doubt, I recommend configuration the the AWS console first to see what is required for your particular rule.</p><h3>Running the Demo</h3><p>OK, let’s run the demo. After downloading the code, all you need to do is run</p><pre>cdk deploy</pre><p>After running deploy, you will see a URL output for your new API. If you are in the United States, when hitting the API, you will see the following result from API Gateway:</p><pre><strong>{&quot;message&quot;:&quot;Forbidden&quot;}</strong></pre><p>Well, that was boring! How do we get to our API? Well, just use your favorite VPN, and change your country! If you don’t have a VPN provider, you can download the Opera browser free of charge, which has a VPN built in free!</p><p>After turning on your VPN (and making sure your requests are coming from outside the US), you should see:</p><pre><strong>{&quot;hello&quot;:&quot;world&quot;}</strong></pre><h3>Console Comparison</h3><p>So what do the rules look like in the AWS console? Let’s take a look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*mhzBF9ZxG22yn2NzwNbqSA.png" /></figure><p>Here is the result when something matches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*a4kbe52cJ3ZVxVe2K6glzA.png" /></figure><p>Luckily there is a rule builder within the console, which allows you to see roughly how the CDK code should be configured. While the CDK only offers Cfn wrapper classes for the WAF, it can be a helpful step to visually configure rules, look at the JSON rule editor, and then create the infrastructure code from there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*zu965pFBmOqJuOaRIRbvGg.png" /></figure><h3>Conclusion</h3><p>Before wrapping up, don’t forget to destroy your stack, so you don’t incur any extra charges in your account:</p><pre>cdk destroy</pre><p>Hopefully this simple example gives insight into how you can use the AWS WAF, CDK, and API Gateway together within your organization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e830439ee75e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Region Lambda with Route53]]></title>
            <link>https://drewword.medium.com/multi-region-lambda-with-route53-8d8f8d63357b?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d8f8d63357b</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[multi-region]]></category>
            <category><![CDATA[lambda]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Wed, 17 Jun 2020 23:05:11 GMT</pubDate>
            <atom:updated>2020-06-17T23:05:11.438Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Your Feet Wet with the CDK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7Xkg4g0UL_S0VSaVTiX9g.png" /></figure><p>Whenever I reacquaint myself with the possibility of using Lambda in a multi-region failover scenario, I consistently run across the AWS blog post here: <a href="https://aws.amazon.com/blogs/compute/building-a-multi-region-serverless-application-with-amazon-api-gateway-and-aws-lambda/">https://aws.amazon.com/blogs/compute/building-a-multi-region-serverless-application-with-amazon-api-gateway-and-aws-lambda/</a></p><p>The CloudFormation code is all there; however, the AWS CDK is supposed to make things easier. I wanted to see how much easier using the CDK would be to re-create this scenario. In this article, I will go through code highlights, experiences with the CDK, and some tips I learned along the way.</p><p>All of the code for this article is located in GitHub here:</p><p><a href="https://github.com/drewword/multi-region-lambda-cdk">drewword/multi-region-lambda-cdk</a></p><h3>Requirements for Running The Code</h3><p>In order to run the CDK sample code in your own account, you will need the following:</p><ul><li>An AWS account.</li><li>Your own domain.</li><li>Certificates created for the domain within multiple regions.</li></ul><p>The original AWS blog post gives details on how to request certificates in multiple regions for the same domain. (AWS certificates are specific to a region)</p><h3>Code Walkthrough</h3><p>After cloning the repository above, the first point of interest is the file <strong>LambdaRegionDemo.ts</strong>. Here there are two interesting elements. The first is loading various CDK context variables. Those will be variables passed in from the command line to specify elements specific to your environment. There are also two variables that will determine what region “fails”, and what region is healthy. (status1 and status2 vars). The Route53 health check looks for the string OK. The lambda functions accept a variable of what to return to determine health.</p><p>The second interesting item to note is the multiple stacks used to create a Lambda in two different regions. See a depiction of the bootstrap typescript below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*zO4Bb-zu5kssQSDqX0QiBw.png" /></figure><p>All of the variables are read from the AWS CDK context object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*svHIvqNl9LbSK-maiAfKyA.png" /></figure><p><strong>DemoLambdaStack.ts</strong></p><p>The DemoLambdaStack takes care of instantiating a lambda function, a Route53 health check, and the Hosted Zone record set. (Note, this demo requires that you have your own domain setup within an AWS account.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*Org1Ow_sg_E2TpBAcIF8Ng.png" /></figure><p>This is all vanilla typescript organization for the point of organizing all of the constructs that will be built by CloudFormation. In the next section, I will dive deeper into where the CDK started to show some cracks.</p><h3>CDK missing pieces</h3><p>I used version 1.45 of the CDK, and could not find a health check class for use in Route53. Hopefully by the time you read this, it will be added to the CDK; however, I used the “next level down”, which is the equivalent <strong>Cfn</strong> class. In this case it was <strong>CfnHealthCheck</strong>. In order to get some of the values, I used the original AWS article as a reference with the sample CloudFormation. This was my first hint that I would need to use the CloudFormation “<strong>Fn</strong>” classes, such as <strong>Fn.ref</strong> and <strong>Fn.join</strong>. The general flow for this process was:</p><ul><li>Examine the CloudFormation sample output.</li><li>Find the corresponding CloudFormation function classes within the CDK.</li><li>Run CDK synth to compare your output to sample CloudFormation output.</li></ul><p>Here is a comparison of the CDK synth output for the health check, and the corresponding CDK code.</p><pre>MyHealthCheck:<br>  Type: AWS::Route53::HealthCheck<br>  Properties:<br>    HealthCheckConfig:<br>      FailureThreshold: 1<br>      FullyQualifiedDomainName:<br>        Fn::Join:<br>          - &quot;&quot;<br>          - - Ref: helloWorldLambdaRestApi6825FB98<br>            - .execute-api.us-east-1.<br>            - Ref: AWS::URLSuffix<br>      ResourcePath:<br>        Fn::Join:<br>          - &quot;&quot;<br>          - - /<br>            - Ref: helloWorldLam...od67DD79AF<br>            - /hello<br>      SearchString: OK<br>      Type: HTTPS_STR_MATCH<br>    HealthCheckTags:<br>      - Key: Name<br>        Value: us-east-1-healthcheck</pre><p>Below is the corresponding CDK code:</p><pre>let checkURL = <strong>Fn.join</strong>(&quot;&quot;, [restApi.restApiId,<br>        &quot;.execute-api.&quot;,<br>        region,<br>        &quot;.&quot;,<br>        <strong>Fn.ref</strong>(&quot;AWS::URLSuffix&quot;)]);</pre><pre>let healthCheckIdentifier = region + &quot;-healthcheck&quot;;</pre><pre>this.healthCheck = new route53.CfnHealthCheck(stack,<br>        &quot;MyHealthCheck&quot;, {<br>        healthCheckTags: [{<br>          key: &quot;Name&quot;,<br>          value: healthCheckIdentifier<br>        }],<br>        healthCheckConfig: {<br>        type: &quot;HTTPS_STR_MATCH&quot;,<br>        failureThreshold: 1,<br>        fullyQualifiedDomainName: checkURL,<br>        searchString: &quot;OK&quot;,<br>        resourcePath: <strong>Fn.join</strong>(&quot;&quot;, [&quot;/&quot;,<br>        restApi.deploymentStage.stageName,<br>        &quot;/hello&quot;])<br>}</pre><p>Both the CloudFormation YAML, in addition to the typescript code seem reasonably similar. This is where the CDK can have downsides. When a higher level class doesn’t exist, using the various “escape hatches” can be cryptic and cumbersome. The advantage with using the CDK however, is that you can hide complexity behind a class that can be re-used without knowing the lower level details.</p><p>AWS outlines some more of these <strong>escape hatches</strong> in this article: <a href="https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html">https://docs.aws.amazon.com/cdk/latest/guide/cfn_layer.html</a></p><p>As long as there is an API exposed for the functionality you are looking for, you have a path to coding it within the CDK. It won’t always be simple however. The AWS CDK wins over Terraform in this respect that the CDK uses a real programming language, so you’re not stuck in a DSL of YAML.</p><h3>Getting Hints — or Most of the Way</h3><p>After the lambda is created, along with a Route53 health check, the final piece is a Route53 Record Set to tie everything together. The CDK has a class within Route53 <strong>ARecord.</strong> Unfortunately the ARecord class does not have a parameter to accept a health check. Again, I resorted to using the “next level down” class, which was the <strong>CfnRecordSet.</strong> I was a little unclear exactly what to use for some of the parameters. In order to get my 80% there, I used CDK synth command while using the <strong>ARecord</strong> higher level CDK class.</p><p>This gave me the benefit of having a CloudFormation reference to use when converting to use the raw <strong>CfnRecordSet</strong>. Obviously this is not ideal; however, getting CloudFormation hints from a reference implementation can jump the hurdle where AWS CDK documentation runs thin. Utilizing the CloudFormation documentation from AWS was also immensely useful.</p><h3>Remembering the CDK is a CloudFormation generator</h3><p>One important point to remember when using the CDK, is that the CDK is a CloudFormation generator at heart. I learned this lesson when attempting to pick apart a URL that was being generated. It can appear this URL is generated within the typescript CDK code; however, that is incorrect. Ultimately final URLs for endpoints are generated from the process of AWS deploying the CloudFormation stack.</p><p>One minor exception is with the SSM parameter store classes. This class is also available at synthesize time, which will read variables before the stack is deployed. This is available to the CDK Runtime Context similar to the variables used on the command line.</p><p><a href="https://docs.aws.amazon.com/cdk/latest/guide/get_ssm_value.html">https://docs.aws.amazon.com/cdk/latest/guide/get_ssm_value.html</a></p><h3>Running The Demo Code</h3><p>In order to run the demo code, run the following:</p><ul><li>npm install</li><li>npm run build</li></ul><pre>cdk deploy -c hostedZoneName=YOURDOTCOMADDRESS.com <br>-c hostedZoneId=ZYWQL6IKKZIWZ <br>-c certarn1=ARN-FOR-YOUR-HOSTED-ZONE-REGION1<br>-c certarn2=ARN-FOR-YOUR-HOSTED-ZONE-REGION2<br>-c status1=OK -c status2=FAIL FailoverTest-Region1 FailoverTest-Region2 </pre><p>After successful deployment, navigate to the following site in a web browser:</p><p><a href="https://demo.yourdomain.com/hello"><strong><em>https://demo.YOURDOMAIN.com/hello</em></strong></a></p><p>Now re-deploy with the same command above, and switch status1 and status2. After a minute or so, you will notice the return from the lambda states it is running in a different region.</p><h3>Conclusion</h3><p>So how do I view the CDK now that I have implemented something slightly beyond “Hello World”? The main points I found are:</p><ul><li>If deciding to the learn the CDK, make a conscious decision to learn CloudFormation as well. Knowing CloudFormation will help tremendously when the CDK comes up short.</li><li>Remembering that the CDK is a veneer on top of CloudFormation generation. You can’t do runtime processing with CloudFormation outputs. (There are some deeper exceptions with custom resources — but that is beyond the scope of this article.)</li><li>Don’t discount the CDK if there are some rough edges. If you are creating lots of AWS resources, hide some of the complexity behind another class, so developers within your organization can simply be abstracted from the complexity.</li></ul><h3>Reference</h3><p>Please reference all code located within Github here:</p><p><a href="https://github.com/drewword/multi-region-lambda-cdk">drewword/multi-region-lambda-cdk</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d8f8d63357b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing Lambda with Cognito, API Gateway, Amplify, and the CDK]]></title>
            <link>https://drewword.medium.com/securing-lambda-with-cognito-api-gateway-amplify-and-the-cdk-b6d29bb4137f?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d29bb4137f</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-cognito]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 15:18:41 GMT</pubDate>
            <atom:updated>2020-06-02T15:18:41.228Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*-KJs4arl6DtSyA7N1Ez0mA.png" /></figure><h3>Getting Started</h3><p>Getting started with AWS can often be daunting. Tying everything together in order to get off the ground isn’t always a simple task. Luckily the AWS CDK has entered the picture to make all of our lives easier. Using VSCode with typescript code completion makes scripting infrastructure easier than ever.</p><h3>Use Case</h3><p>I was recently asked by someone how they would go about creating a website with sign-in functionality. Initially I thought of trying to stitch together something by storing user data within DynamoDB; however, I faintly remembered from my AWS certification adventure that AWS Cognito was something to re-investigate. For the AWS exam Cognito was a quick set of facts to remember — now I was being asked to apply my certification in a real-world scenario. Looking down the side menu of Cognito in the AWS console was a lot to take in to say the least.</p><h3>Goals</h3><p>With the basic use case, I had the following technical goals in mind:</p><ul><li>Create a User Pool by using the AWS CDK.</li><li>Create a test user within the User Pool by using the CDK.</li><li>Create a custom attribute for storing user specific data, such as are they a “gold member” status, or silver level member?</li><li>Create a lambda function that can be secured with Cognito.</li><li>Parse the Cognito JWT token in order to read the identity of the user.</li><li>Demonstrate calling the API utilizing AWS Amplify.</li></ul><h3>Getting Started</h3><p>In order to get started, you will need the following tools:</p><ul><li>Node with npm.</li><li>Typescript installed.</li><li>The AWS CDK installed</li><li>AWS Account with keys for programmatic access.</li></ul><p>Setting up all of the foundation requirements is beyond the scope of this article; however, the following link from AWS covers this in greater detail: <a href="https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html">https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html</a>.</p><h3>Source Listing</h3><p>All of the code for this article can be found in the following GitHub repository: <a href="https://github.com/drewword/cognito-cdk-amplify">https://github.com/drewword/cognito-cdk-amplify</a></p><h3>Setting Up A User Pool</h3><p>Creating the User Pool is very straightforward through the following call:</p><pre>const userPool = new <strong>UserPool</strong>(this, &#39;myUserPool&#39;, {<br>      userPoolName: &quot;demo-userpool&quot;,<br>      selfSignUpEnabled: true,<br>      customAttributes: {<br>        <strong>member_status</strong>: new StringAttribute()<br>      },<br>      signInAliases: {<br>          email: true,<br>          phone: true,<br>          username: true<br>      }<br>    });</pre><p>This excerpt can be found within the following file in the Git repository: <a href="https://github.com/drewword/cognito-cdk-amplify/blob/master/lib/cognito-sample1-stack.ts">https://github.com/drewword/cognito-cdk-amplify/blob/master/lib/cognito-sample1-stack.ts</a></p><p>This is where I created a custom attribute called member_status, which would fulfill the requirement to add custom data for each individual user.</p><h3>Adding a User Pool Client</h3><p>A user pool client defines how you interact from the outside world with Cognito. This is where I defined a “web-only” type flow using an Oauth Implicit Code flow, as noted below:</p><pre>const userPoolClient = userPool.addClient(&#39;app-client&#39;, <br>     {<br>      oAuth: {<br>        flows : {<br>          implicitCodeGrant: true<br>        },<br>        scopes: [OAuthScope.OPENID],<br>        callbackUrls: [&#39;https://www.google.com&#39;]<br>      }<br>    }<br> );</pre><p>The callback here would typically be your website; I am simply using google as a placeholder.</p><h3>Creating a Test User</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYIHzc4xB9nYUVSAKLyYjQ.png" /></figure><p>Cognito offers methods to create users through a variety of methods. I wanted to have a test user created with the CDK stack itself. This can be achieved by using an AwsCustomResource. By using an AwsCustomResource, any set of AWS commands can be called when the CDK stack is created.</p><p>Within the <strong>onCreate</strong> of the <strong>AwsCustomResource</strong>, the Cognito AdminCreateUser call is used, adding in the user with a “gold_member_status”. (see below depiction)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*ZN0G4IhF9fefKMKzD9AOWg.png" /></figure><p>For the full listing of this custom resource, please refer to the GitHub link here: <a href="https://github.com/drewword/cognito-cdk-amplify/blob/master/lib/cognito-sample1-stack.ts">https://github.com/drewword/cognito-cdk-amplify/blob/master/lib/cognito-sample1-stack.ts</a></p><h3>Creating the Lambda Function</h3><p>Deploying a Lambda function with the CDK is rather straightforward. In the example, the code for the Lambda is extracted from the folder <strong>hello-lambda</strong>.</p><pre>const helloWorldFunction = new Function(this,<br> &#39;helloWorldFunction&#39;, {<br>          code: new AssetCode(&#39;hello-lambda&#39;),<br>          handler: &#39;helloworld.handler&#39;,<br>          runtime: Runtime.NODEJS_12_X<br>    });</pre><h3>Setting up the Authorizer</h3><p>Below is an outline of creation of the authorizer, and attaching the authorizer to the GET method for ApiGateway.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*DCmhlwt8zSr-3_yqLG4hPw.png" /></figure><h3>Accessing the Cognito Token within Lambda</h3><p>When the lambda is called, we really want to answer the basic question of “Who is calling us?”. We know that ApiGateway has authenticated the caller; however, we want to know details about the user. This could be for various levels of roles, their email address, etc.</p><p>In order to access this information, simply look within the headers.</p><pre>export const handler = <br>    async (event: any = {}): Promise&lt;any&gt; =&gt; {<br>        console.log(&quot;Starting hello handler.&quot;);<br>        const jwtHeaders = event.headers[&#39;Authorization&#39;];</pre><p>This is located in the <strong>hello-lambda</strong> folder within the <strong>helloworld.ts</strong> file. Decoding the JWT can be done with the jsonwebtoken library. Note, here I simply decode the token. In a production system, you would want to use the verify call of the library.</p><pre>const decoded = jwt.decode(jwtHeaders);<br>const memberStatus = decoded[&quot;custom:member_status&quot;];</pre><h3>The Amplify Test Client</h3><p>In order to test the user creation, you can access the AWS hosted UI for authentication, or simply use the AWS Amplify client. For ease of use, within the git repository, look within the <strong>amplify-test-client</strong> folder.</p><p>The amplify test client performs the following:</p><ul><li>Calls the authenticate API.</li><li>Responds to the initial challenge with an updated password.</li><li>Calls the Lambda API after authentication.</li></ul><p>In order to call the amplify test client, use the CDK deploy output variables with the following command:</p><pre>node ./amplify-client-test/index.js [USERPOOLID] [CLIENTID] [TESTURL]</pre><h3>Expected Test Output</h3><p>After running <strong>cdk deploy</strong>, and then running the amplify test client, you should receive results similar to below. Note that the Cognito custom attribute of member_status is returned from the Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*AiU7eBtGULWk9Z9BBteH9w.png" /></figure><h3>Conclusion</h3><p>There was a lot to cover in this article to receive an end-to-end call from Amplify to ApiGateway, and returning with Cognito attributes. Please check out the source code on GitHub for full detail: <a href="https://github.com/drewword/cognito-cdk-amplify">https://github.com/drewword/cognito-cdk-amplify</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d29bb4137f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDK — Cloud Candy Quick Start with Lambda Hello World]]></title>
            <link>https://drewword.medium.com/aws-cdk-cloud-candy-quick-start-with-lambda-hello-world-3e4e8edc6d7e?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e4e8edc6d7e</guid>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Tue, 12 May 2020 14:56:29 GMT</pubDate>
            <atom:updated>2020-05-12T14:56:29.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CDK — Cloud Candy Quick Start with Lambda Hello World</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECbIlWNsQxTP8XHaPkqtpQ.png" /></figure><h3>Background</h3><p>If you are reading this, I don’t have to tell you about the popularity of AWS. AWS is everywhere. Cloud computing has infiltrated even the most mundane of back-office corporate environments. Some of the key questions are typically where to get started however. Training is typically done by utilizing the AWS Console (GUI), or is a mixture of CloudFormation scripts that you are simply told to “run”. AWS re:Invent has great instructional content; however, many sessions say run this CloudFormation, which is not a great way to get started.</p><p>Other cloud experts may be brought into your corporation that recommend other tools such as Terraform. Terraform can be its own little world as well, and if attempting to understand AWS for the first time, may not be the best place to start. Terraform in addition to CloudFormation, are domain specific markup that doesn’t necessarily “speak” to someone with a programming background.</p><p>Hopefully in this article I will outline another alternative to diving in and understanding AWS by utilizing the AWS CDK. The CDK is a cloud development kit that allows you to use popular programming languages to create AWS constructs. In this article, I will be using typescript; however, the general concepts can be applied to any language the CDK supports.</p><p>The output of the CDK is CloudFormation, the “native” way AWS utilizes Infrastructure as Code.</p><h3>Isn’t the Console Easier?</h3><p>To sign up for an AWS account, you have inevitably navigated into the AWS console. You may have even gone through many tutorials that utilize the console, or perhaps you are a seasoned expert still using the console. When I first started, I had a very specific task in mind related to a personal website. I found an online tutorial how to set things up, and when I was finished I felt I had jumped through a great learning hurdle. Unfortunately visiting back years later to the same process, I had no idea what I had done. There wasn’t really a concrete history of what I had used — no audit trail to be found.</p><p>I felt oddly disconnected from the process as well. There were infrastructure tools available at the time; however, when I looked at how to utilize them, it felt like I would be learning multiple things, and really AWS.</p><h3>Getting Started</h3><p>As mentioned before, this article will assume typescript usage when using the CDK. Typescript and the CDK will be installed through npm.</p><h3>Step 1 — Ensure you have NPM installed.</h3><p>Install NPM along with NodeJS. These are typically installed together. Visit the <a href="https://nodejs.org/en/">nodeJS site here</a>.</p><h3>Step 2 — Already Have NPM / Node? Time to Update</h3><pre>sudo npm install -g npm</pre><p>Note, I’m running on a Mac, and I needed <strong>sudo</strong>. This may be optional for you.</p><h3>Step 3 — Install TypeScript</h3><pre>sudo npm install -g typescript</pre><p>to update use:</p><pre>sudo npm update -g typescript</pre><h3>Step 4 — Install the CDK</h3><pre>sudo npm install -g cdk</pre><p>Similar to above, if you already have it installed, you can run the npm update command.</p><h3>Creating a new CDK project</h3><p>Let’s start creating a new project. First create a new empty directory, and run the cdk init command:</p><pre>mkdir intro1<br>cd intro1<br>cdk init --language typescript</pre><p>Note, I had some issues after updating my CDK, and I needed to clean the npm cache. This worked for me; however, is noted here as a last resort:</p><pre>npm cache clean --force</pre><p>After a successful run, you should see a set of commands such as:</p><pre>npm run build<br>npm run watch<br>npm run test<br>cdk deploy<br>cdk diff<br>cdk synth</pre><h3>CDK Default Enhancements</h3><p>The CDK has some odd choices for the template files. Hopefully there is a way in the future to easily add your own templates. For now, I am going to make the following changes:</p><ul><li>Change the source code to reside in a single directory (not lib and bin).</li><li>Change the output directory of the typescript compiler to not litter the current directories.</li><li>Add a clean phase to the build to accommodate the above changes.</li></ul><p>Notice the screenshot after initial setup, with source in both <strong>bin</strong> and <strong>lib</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*EQNdJV5KlufwGkGtc9jrvA.png" /></figure><h3>Source location tweaks</h3><p>Start by creating a new folder called <strong>src</strong> within your <strong>test1</strong> directory.</p><p>Now move the files from <strong>bin</strong> and <strong>lib</strong> into the <strong>src</strong> folder. You can delete the lib folder at this point. If using VSCode, the typescript files will be updated for you — otherwise, examine the imports below, as you may need to modify the typescript files.</p><p>The intro1.js file should have an import similar to below:</p><pre>import { Intro1Stack } from &#39;./intro1-stack&#39;;</pre><p>Within <strong>package.json</strong>, add the following to dev dependencies:</p><pre>&quot;devDependencies&quot;: {<br>   &quot;rimraf&quot;: &quot;^3.0.1&quot;,</pre><p>Rimraf will help clean out the build directory in an OS independent manner.</p><p>Within <strong>package.json</strong>, change the bin attribute as follows:</p><pre>&quot;bin&quot;: {<br>   &quot;intro1&quot;: &quot;bin/src/intro1.js&quot;<br>},</pre><p>Next, within the same package.json, change the options that will be run:</p><pre>&quot;scripts&quot;: {<br>   &quot;rimraf&quot;: &quot;./node_modules/rimraf/bin.js&quot;,<br>   &quot;clean&quot;: &quot;rimraf bin/&quot;,<br>   &quot;build&quot;: &quot;npm run clean &amp;&amp; tsc -p ./&quot;,</pre><p>Almost there, within tsconfig.json, add the following:</p><pre>&quot;compilerOptions&quot;: {<br>   &quot;outDir&quot;: &quot;bin&quot;,</pre><p>The important thing to note is the <strong>outDir</strong>. With that, JS and TS files won’t get cluttered together.</p><p>One final file to tweak, which is the cdk.json. Ensure the npx command is pointing to the correct location:</p><pre>{<br>  &quot;app&quot;: &quot;npx ts-node src/intro1.ts&quot;,</pre><p>Notice the <strong>src</strong> directory above instead of <strong>bin</strong>.</p><h3>Whew, Finally Running</h3><p>OK, let’s run everything to make sure we are in business. Run the following commands:</p><pre>npm run build<br>cdk synth</pre><p>Build will transpile everything into the bin directory, and cdk synth will display what CloudFormation will be executed.</p><h3>Bootstrapping your Account</h3><p>Getting a brand new AWS account, with a user provisioned, and access keys is beyond the scope of this article. If you aren’t sure what those are, there are a lot of resources on how to create a new AWS user with programmatic access. Once you have that set, come back here. Running <strong>aws configure</strong> will get you started on the path of what you need.</p><p>Once you are set with aws configure, bootstrap the CDK into your account with:</p><pre>cdk bootstrap</pre><h3>Lambda Hello World</h3><p>At this stage the CDK is all set to go — but we have nothing inside of it. Let’s keep things as simple as possible, and add a lambda function that returns hello world.</p><p>Let’s add lambda and api-gateway:</p><pre>npm install @aws-cdk/aws-apigateway<br>npm install @aws-sdk/lambda</pre><p>Adding the Lambda Source</p><p>Add a resources directory, with the following JavaScript code (<strong>lambdatest.js</strong>):</p><pre>const AWS = require(&#39;aws-sdk&#39;);<br>exports.main = async function(event, context) {<br>  try {<br>    var method = event.httpMethod;<br>    if (method === &quot;GET&quot;) {<br>      if (event.path === &quot;/&quot;) {<br>        return {<br>          statusCode: 200,<br>          headers: {},<br>          body: &quot;Hello World!&quot;<br>        };<br>      }<br>    }<br>  }<br>  catch(error) {<br>    var body = error.stack || JSON.stringify(error, null, 2);<br>    return {<br>      statusCode: 400,<br>      headers: {},<br>      body: JSON.stringify(body)<br>    }<br>  }<br>}</pre><h3>The CDK Infrastructure</h3><p>Now we have created our lambda code under the resources directory, let’s tell the CDK to deploy it with the API Gateway.</p><p>Add the following typescript file under the src directory. (<strong>src/LambdaTest.ts</strong>)</p><pre>import core = require(&quot;@aws-cdk/core&quot;);<br>import apigateway = require(&quot;@aws-cdk/aws-apigateway&quot;);<br>import lambda = require(&quot;@aws-cdk/aws-lambda&quot;);</pre><pre>export class LambdaTest extends core.Construct {<br>  constructor(scope: core.Construct, id: string) {<br>    super(scope, id);<br>    const handler = new lambda.Function(this, <br>      &quot;LambdaTestHandler&quot;, {<br>        runtime: lambda.Runtime.NODEJS_10_X,<br>        code: lambda.Code.asset(&quot;resources&quot;),<br>        handler: &quot;lambdatest.main&quot;<br>    });<br>    const api = new apigateway.RestApi(this, &quot;test-api&quot;, {<br>      restApiName: &quot;Lambda Test Service&quot;<br>    });<br>    const apiIntegration = <br>      new apigateway.LambdaIntegration(handler, {<br>      requestTemplates: { &quot;application/json&quot;: <br>       &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; }<br>      });<br>     api.root.addMethod(&quot;GET&quot;, apiIntegration); <br>   }<br>}</pre><h3>Adding The CDK Function to the Stack</h3><p>Inside your Intro1Stack class, you will notice a line about “add your code here”, which is created by the cdk init.</p><p>Add the following code to the Intro1Stack.ts:</p><pre>// The code that defines your stack goes herenew myservice.LambdaTest(this, &#39;LambdaTest&#39;);</pre><h3>Deploy and Enjoy!</h3><p>Run the following commands to deploy to your AWS account:</p><pre>npm run build<br>cdk synth<br>cdk deploy</pre><p>If everything went according to plan, you will have an output of a URL. Paste this in your browser and you will see the famous “Hello World”!</p><h3>Cleaning Up</h3><p>Make sure your run the following command to clean up the CloudFormation stack output by your CDK project:</p><pre>cdk destroy</pre><h3>What We Have Done — Summary</h3><p>Hopefully in this article I have shown that you don’t need to touch the AWS console to have an enjoyable coding experience and deploy AWS resources while working in a popular language such as typescript. There are always enhancements to be made such as crafting the lambda itself in typescript; however, that will need to come in another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e4e8edc6d7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Express Mustache Quick Start]]></title>
            <link>https://drewword.medium.com/express-mustache-quick-start-36c3421af91?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/36c3421af91</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mustache]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Thu, 09 May 2019 23:41:34 GMT</pubDate>
            <atom:updated>2019-05-09T23:41:34.091Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting up and running with mustache to handle a simple form submission.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*hflmaWpwYvzd8PMB8jLUBQ.png" /></figure><p>Whenever I get started with a new Express JS project, it seems that I am always searching for that one line of special sauce to make everything work. Express is a wonderful framework for fast web development; however, sometimes missing that one single line will have you staring at the browser while it spins expecting a response.</p><p>The goal of this article is to create a minimal example of Express JS that:</p><ul><li>Demonstrates how to use mustache with Express.</li><li>Demonstrates how to create a simple html form and submit / re-display data.</li><li>How to use require and import to organize some of your Node JS files.</li><li>Give an explanation along the way of all of the various components.</li></ul><h3>The Finished Product</h3><p>Here is a screenshot of the finished product that we are building today. The sample application will display a form that allows a user to enter their name, process the form post, and redirect to another page that displays the name entered. Not very complicated; however, that is the point of this post — simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ter-W0Lq89gw-prwd9H2xA.png" /></figure><p>With the final page result show below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFccLsH_NtJlf3X_uOWMbA.png" /></figure><h3>Getting Started</h3><p>In order to get started, make sure you have the latest node and npm binaries. I am currently using version 10.15.1 of node. Next navigate to a new directory and run the following commands:</p><pre>npm init<br>npm install express --save<br>npm install mustache-express --save</pre><p>The first command of ‘npm init’ will ask some questions about your project, you can simply hit enter to accept all of the defaults.</p><h3>What is Mustache?</h3><p>Mustache is a template engine that can be used with express in order to achieve similar functionality to JSP (Java Server Pages). The functionality provided within the templates is pretty straightforward — which is actually what you really want. Mixing too much logic within your presentation template makes your code a mess and isn’t the best separation of concerns.</p><h3>The Entry Point</h3><p>The main entry point for the application depicted below. Create a new file, and give it a name of <strong>server.js</strong>.</p><pre>let <strong>express</strong> = <strong>require</strong>(&#39;express&#39;);<br>let <strong>mustacheExpress</strong> = <strong>require</strong>(&#39;mustache-express&#39;);<br>let <strong>bodyParser</strong> = <strong>require</strong>(&#39;body-parser&#39;);</pre><pre>let <strong>enterNameRoute</strong> = require(&#39;./enterName&#39;);<br>let <strong>displayNameRoute</strong> = require(&#39;./displayName&#39;);</pre><pre>let <strong>app</strong> = <strong>express</strong>();</pre><pre><strong>app</strong>.set(&#39;views&#39;, `${__dirname}/views`);<br><strong>app</strong>.set(&#39;view engine&#39;, &#39;mustache&#39;);<br><strong>app</strong>.engine(&#39;mustache&#39;, <strong>mustacheExpress()</strong>);<br><strong>app</strong>.use (bodyParser.urlencoded( {extended : true} ) );</pre><pre><strong>app</strong>.use (&#39;/&#39;, enterNameRoute);<br><strong>app</strong>.use (&#39;/&#39;, displayNameRoute);</pre><pre><strong>app</strong>.listen(3000,function() {<br>    console.log(&quot;Server started&quot;);<br>});</pre><p>The final command to run the script is highlighted below.</p><pre>node server.js</pre><p>Everything won’t run as expected yet however, since we still need to enter some required functionality.</p><h3>Entry Point Explanation</h3><p>The first two lines import the usage of express and mustache for our application. The next body-parser import is used to handle the form submission data.</p><p>The following two lines import our own code for Express routes, the enter name route, and the display name route.</p><pre><strong>app</strong>.use (&#39;/&#39;, enterNameRoute);<br><strong>app</strong>.use (&#39;/&#39;, displayNameRoute);</pre><p>The last line is the express startup that will listen on the port you specify. Navigating to localhost:3000 within a browser will allow you to test out your app.</p><h3>Route Definition</h3><p>In order to avoid having everything located in one large file, the code that handles the various functionality in your Express application can be separated by route. Below are the two routes defined for our small application, enterNameRoute, and displayNameRoute.</p><p>Create a new file, call it <strong>enterName.js</strong>, and paste in the below contents.</p><pre>let <strong>router</strong> = require(&#39;express&#39;).Router();<br>let <strong>storage</strong> = require(&#39;./simpleStorage&#39;);</pre><pre><strong>router</strong>.<strong>get</strong>(&#39;/&#39;, function(request,response) {<br>  response.render (&#39;enterName&#39;, {pageTitle: &quot;Enter Your Name&quot;});<br>});</pre><pre><strong>router</strong>.<strong>post</strong>(&#39;/submitName&#39;, function (request, response) {<br>  storage.setValue(request.body.userName);<br>  response.redirect(&#39;/displayName&#39;);<br>});</pre><pre><strong>module.exports = router</strong>;</pre><p>Do the same for <strong>displayName.js</strong>.</p><pre>let <strong>router</strong> = require(&#39;express&#39;).Router();<br>let <strong>storage</strong> = require(&#39;./simpleStorage&#39;);</pre><pre><strong>router</strong>.get(&#39;/displayName&#39;, function(request,response) {<br>  let userName = storage.getValue();<br>  response.render (&#39;displayName&#39;,<br>     {<br>       pageTitle: &quot;Your Name Display&quot;,<br>       userName: userName<br>     });<br>  });</pre><pre><strong>module.exports</strong> = <strong>router</strong>;</pre><p>Both of these files should be located in the same directory as your initial index.js. You can put these into a subdirectory as your application grows, which would then change the require statement accounting for the new directory.</p><h3>Route Explanation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yapMbDwjpnQmF6BRMVNvzg.png" /></figure><p>The express router establishes a handler for a particular endpoint definition. For instance, in the enterName.js route definition, there are two HTTP methods defined, a GET and a POST. The GET request instructs express to render the template <strong>enterName.mustache </strong>(NOTE: the .mustache extension is not required). The second argument defines any variables that should be available to the mustache template.</p><p>The last line in both files defines what will be exported, in order for this module to be included in the main <strong>server.js</strong> file.</p><h3><strong>App Use and Router Glue</strong></h3><p>If you notice, in server.js the enterName route is included as noted below.</p><pre><strong>app</strong>.use (&#39;/&#39;, enterNameRoute);</pre><p>And in the enterName.js file, the router has a similar method when defining the GET request, with a path as well.</p><pre><strong>router</strong>.<strong>get</strong>(&#39;/&#39;, etc...</pre><p>These paths work in conjunction with each other, and one is not replacing the other. If for instance, within the app, it was done with `<strong>app.use (‘/foo`, </strong>and the router.get was defined as `<strong>router.get(‘/bar’`, </strong>then in order to reach that particular route, you would need to navigate to <strong>localhost:3000/foo/bar</strong>.</p><h3>Mustache Templates</h3><p>The remaining wiring for the basic scaffolding for our application is the two mustache templates. These are both outlined below. Both of these files should be created in a new directory called <strong>views</strong>.</p><p>File: <strong>enterName.mustache</strong></p><pre>&lt;html&gt;<br> &lt;head&gt;<br>  &lt;link rel=&quot;stylesheet&quot;<br> href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;<br> crossorigin=&quot;anonymous&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;container&quot; style=&quot;padding:20px&quot;&gt;<br>     &lt;div class=&quot;card card-body bg-light&quot;&gt;<br>     &lt;h1&gt;{{pageTitle}}&lt;/h1&gt;<br>     &lt;<strong>form</strong> <strong>action</strong>=&quot;<strong>/submitName</strong>&quot; method=&quot;<strong>post</strong>&quot;&gt;<br>       Enter your name: &lt;br/&gt;<br>      &lt;input type=&quot;text&quot; class=&quot;form-control&quot; <br>        name=&quot;<strong>userName</strong>&quot; style=&quot;max-width:300px&quot;&gt;<br>      &lt;br/&gt;<br>      &lt;input type=&quot;submit&quot; value=&quot;OK&quot; class=&quot;btn btn-primary&quot;&gt;<br>     &lt;/form&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;</pre><p>File: <strong>displayName.mustache</strong></p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;link rel=&quot;stylesheet&quot;<br>href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css&quot;<br>   crossorigin=&quot;anonymous&quot;&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div class=&quot;container&quot; style=&quot;padding:20px&quot;&gt;<br>      &lt;div class=&quot;card card-body bg-light&quot;&gt;<br>        &lt;h1&gt;<strong>{{pageTitle}}</strong>&lt;/h1&gt;<br>        &lt;h3&gt;Hello <strong>{{userName}}</strong>&lt;/h3&gt;<br>      &lt;/div&gt;<br>     &lt;/div&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Templates Explanation</h3><p>The templates are relatively straightforward HTML. The main point of interest is the variable substitution which is noted with two curly braces as such {{ }}.</p><p>Within the enterName template, the form post action is defined to match the route defined within <strong>enterName.js</strong>. This is where the POST handler will come into play.</p><h3>Storing State — The Final Bits</h3><p>The final file for our example is used in order to keep state around. This is a very rudimentary method for the purpose of a demo. There are more production like possibilities by utilizing one of the session libraries from NPM. This will not account for multiple users in our simple app, and is only meant to serve up state from one route to the next.</p><p>Create a new file in the same directory named <strong>simpleStorage.js</strong>.</p><pre>var globalValue = &quot;&quot;;</pre><pre>function <strong>getValue</strong>() {<br>  return globalValue;<br>}</pre><pre>function <strong>setValue</strong>(value) {<br>  globalValue = value;<br>}</pre><pre>module.exports.<strong>getValue</strong> = <strong>getValue</strong>;<br>module.exports.<strong>setValue</strong> = <strong>setValue</strong>;</pre><h3>A Quick Note on Require / Import</h3><p>Within the simpleStorage module is a simple example of exporting methods from one JS file to another within Node. Once you have defined your exports, you can utilize the Node keyword <strong>require</strong>, and use the functionality elsewhere. The require statement takes a path to your file, and can traverse up or down the filesystem.</p><h3>Wrapping Up</h3><p>I hope this short post can serve as a good starting point for getting your mustache and express project up and running.</p><p>This post only scratched the surface of these technologies, I would encourage you to do a deeper dive within everything that was shown.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36c3421af91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding the Perfect Promise — A JavaScript Journey]]></title>
            <link>https://drewword.medium.com/finding-the-perfect-promise-a-javascript-journey-be0f3c50bcc0?source=rss-effad8ca3b27------2</link>
            <guid isPermaLink="false">https://medium.com/p/be0f3c50bcc0</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Dre May]]></dc:creator>
            <pubDate>Fri, 03 May 2019 18:02:50 GMT</pubDate>
            <atom:updated>2019-05-10T18:56:49.117Z</atom:updated>
            <content:encoded><![CDATA[<h3>Finding the Perfect Promise — A JavaScript Journey</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cHLJrtsPTX5wUpX1DYHWQ.png" /></figure><p>As I started to write this article, it began as a technical blurb on the merits of using the JavaScript feature of async / await. This concise blurb naturally evolved in my head to a masterpiece of technical know how on all of the possibilities of creating callback mechanisms within JavaScript. That grandeur quickly faded however, as I conceded that these articles must already exist. And with a few searches, I confirmed that yes, literally dozens, if not hundreds of good articles exist on the merits of async await vs. raw promises. Throw in a healthy dose of RxJS observables and a custom written JavaScript event bus, and there is a great recipe for technology overdose.</p><p>As I shifted gears to something more down to earth, I realized that the true value was showing my journey from one implementation to the next, the reasons for continued refactoring, and what I learned along the way. Oh, and yes, I will show callbacks, promises, and async / await.</p><h3>Getting There</h3><p>My task was relatively straight forward — write a minimal demo script for a new API being developed. The purpose was to create something that could demonstrate concepts to another team with minimal code. Instead of taking the time to write a full-fledged Java implementation, the wise choice for me was to create a short JavaScript sample with Node.js as the runtime.</p><p>This script was not meant for production, nor meant to be particularly elegant, performant, or clean — simply as a demo. Powerpoint on steroids. But as I quickly realized, no code can ever escape the lens of self scrutiny.</p><h3>Rockets Away</h3><p>The code for my organization is proprietary, so in order to shed light on my journey, I needed to take a contrived path to illustrate my refactoring adventure. Todd Motto has a wonderful list of APIs that are publicly available, and I happened to choose the SpaceX API as an interesting way to re-create my experience. Todd Motto’s API list can be found here:</p><p><a href="https://github.com/toddmotto/public-apis">https://github.com/toddmotto/public-apis</a></p><p>And the SpaceX API I chose for demonstration purposes is located here:</p><p><a href="https://github.com/r-spacex/SpaceX-API">https://github.com/r-spacex/SpaceX-API</a></p><h3>Getting Started</h3><p>If you would like to follow along, some of the pre-requisites are:</p><ul><li>Install the latest version of npm and Node.js. (I am currently running Node.js version 10.15.1)</li><li>Within a new directory start off with npm init.</li><li>Install two packages: axios and lodash.</li></ul><pre>npm init<br>npm install axios --save<br>npm install lodash --save</pre><h3>The Mission</h3><p>The goal of my demo script is to first call an API from SpaceX to retrieve launches for a previous year, and then find one with mission data. Once that is found, simply print out some information about the mission. This will involve calling two separate APIs from the SpaceX catalog. And this is where the fly enters the ointment of clean code.</p><blockquote>Anytime you need to chain multiple asynchronous calls, the invitation goes out to your messiest friends for a party.</blockquote><h3>Draft One</h3><p>This is where my first mistake entered the picture. The idea that any code should not be given its fair share of pre-thought before typing is a trap waiting to happen. The temptation to blast away at the keyboard — especially within a scripting environment, is very high. In fact, it is almost encouraged! If a new language doesn’t offer a REPL (Read-eval-print-loop), then it simply isn’t cool.</p><p>So here is a version of my first round of code.</p><p><strong>Initial Bits</strong></p><p>Let’s get started by setting up the two libraries used in my demo:</p><ul><li>axios (for making HTTP requests)</li><li>lodash (for some utilities to make the code a little cleaner).</li></ul><pre>const axios = require(&#39;axios&#39;);<br>const _ = require(&#39;lodash&#39;);</pre><p><strong>The First API</strong></p><p>The first API call to retrieve space launches within a particular year was created below.</p><pre>function <strong>getSpaceDataForYear</strong>(year, <strong>processResultsFunc</strong>) {<br>   axios.get(&#39;https://api.spacexdata.com/v3/launches/past&#39;, {<br>     params: { launch_year: year} })<br>    .then( (results) =&gt; <strong>processResultsFunc</strong>(results) )<br>    .catch( (err) =&gt; console.log (err) );<br>}</pre><p>And the calling block starts here.</p><pre><strong>getSpaceDataForYear</strong>(&quot;2018&quot;, <strong>processLaunchDataForYearResult</strong>);</pre><p>At this point, everything seems fine as I frantically type to get my demo done, but as you will see, signs of wear and tear are already appearing. The need to send in a callback function was necessary, as axios calls return a JavaScript promise object. Remember, the temptress of immediate <strong>WET</strong> (We Enjoy Typing) was fully at play when I embarked on creating this demo.</p><p>So we must continue! Enter the next chain of calls, with the definition of <strong>processLaunchDataForYearResult</strong>.</p><pre>function <strong>processLaunchDataForYearResult</strong>(launchResult) {<br>  let flightWithMission = findFlightWithAMission(launchResult);<br>  outputMissionDataSummary(flightWithMission);<br>  getMissionDetails(flightWithMission, <strong>processMissionDetailsResult</strong>);<br>}</pre><p>We are now a second layer deep on what should be a straightforward demo, and it will get worse. As you can see, the next API call is contained within getMissionDetails, and that method will also need a callback function (<strong>processMissionDetailsResult</strong>).</p><p>The function getMissionDetails is outlined below, which is very similar to the function that contained the first API call. Essentially call our callback function in the promise completion of the axios call.</p><pre>function <strong>getMissionDetails</strong>(flight, <strong>processResultsFunc</strong>){<br> axios.get(<br>   `https://api.spacexdata.com/v3/missions/${flight.missionId}`)<br>  .then( (results) =&gt; <strong>processResultsFunc</strong>(results) )<br>  .catch( (err) =&gt; console.log (err) );<br>}</pre><p>The rest of the code is located below, which is provided in case you want to re-create the entire working draft one sample.</p><pre>function <strong>findFlightWithAMission</strong>(yearMissionData) {<br>  var flightWithMission = null;<br>  for (let value of yearMissionData.data ) {<br>    let flightNumber = value.flight_number;<br>    let missionId = _.get(value, &#39;mission_id[0]&#39;);<br>    let rocketName = _.get(value, &#39;rocket.rocket_name&#39;);<br>    if ( flightNumber &amp;&amp; missionId &amp;&amp; rocketName ) {<br>      return  {<br>        flightNumber: flightNumber,<br>        missionId: missionId,<br>        rocketName: rocketName<br>      };<br>    }<br>  }<br>}</pre><pre>function <strong>outputMissionDataSummary</strong>(flight) {<br>  console.log(`Flight number: ${flight.flightNumber}`);<br>  console.log(`Mission ID: ${flight.missionId}`);<br>  console.log(`Rocket name: ${flight.rocketName}`);<br>}</pre><pre>function <strong>processMissionDetailsResult</strong>(missionResult) {<br>  outputMissionDetail(missionResult);<br>}</pre><pre>function <strong>outputMissionDetail</strong>(missionResult) {<br>  console.log(`Mission Name: ${missionResult.data.mission_name}`);<br>  console.log(`Mission ID: ${missionResult.data.description}`);<br>}</pre><h3>Round One Evaluation</h3><p>Round one looked something like this guy pictured here. A hodgepodge chain of parts put together, and not necessarily pretty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*3BjvouAz8DVV1uXRJlXDzQ.jpeg" /></figure><p>If someone wanted to see the overall flow of the set of APIs, the reader would need to jump from a top level function, to another function, and then to another. If the purpose of the demo was to show the flow of API calls in a concise fashion, the demo failed. After looking at the callback chain, I knew it was time for a refactor.</p><blockquote>And it appears that <strong>WET</strong> (We Enjoy Typing) is a self-fulfilling prophecy, as it requires more refactoring and typing!</blockquote><h3>Stage Two</h3><p>Stage two involved a refactor that would allow the consumer of the demo code to observe the potential sequence of API calls without muddling through a myriad of JavaScript functions. The top level refactor is listed below.</p><pre><strong>getSpaceDataForYear</strong> (&quot;2018&quot;)<br>.then( <strong>findFlightWithAMission</strong> )<br>.then( <strong>outputMissionDataSummary</strong> )<br>.then( <strong>getMissionDetails</strong> )<br>.then( <strong>outputMissionDetail</strong> )<br>.catch ( (error) =&gt; { console.log(error); });</pre><p>What allowed this concise chain? A heavy dose of Promises everywhere! I changed every method to return a Promise object. In hindsight, maybe this went overboard? Don’t fret however, there is another refactor after this. At least the callbacks were gone.</p><p>Here is the code for getMissionDetails, it was reduced to a single line:</p><pre>function <strong>getMissionDetails</strong>(flight) {<br> return axios.get(`https://api.spacexdata.com/v3/missions/${flight.missionI<br>}`);<br>}</pre><p>However, other methods added a Promise wrapper:</p><pre>function <strong>findFlightWithAMission</strong>(yearMissionData) {<br>  return <strong>new Promise</strong>( (resolve, reject) =&gt; {<br>    var flightWithMission = null;<br>    for (let value of yearMissionData.data ) {</pre><p>Here is the rest of the code if you would like to follow along, in order to see all of the changes required to achieve the above conciseness.</p><pre>function <strong>outputMissionDetail</strong>(missionResult) {<br>  return <strong>new Promise</strong>( (resolve, reject) =&gt; {<br>    console.log(`Mission Name: ${missionResult.data.mission_name}`);<br>    console.log(`Mission ID: ${missionResult.data.description}`);<br>    resolve(missionResult);<br>  });<br>}</pre><pre>function <strong>outputMissionDataSummary</strong>(flight) {<br>  return <strong>new Promise</strong>( (resolve, reject) =&gt; {<br>    console.log(`Flight number: ${flight.flightNumber}`);<br>    console.log(`Mission ID: ${flight.missionId}`);<br>    console.log(`Rocket name: ${flight.rocketName}`);<br>    resolve(flight);<br>  });<br>}</pre><pre>function <strong>findFlightWithAMission</strong>(yearMissionData) {<br>  return <strong>new Promise</strong>( (resolve, reject) =&gt; {<br>    var flightWithMission = null;<br>    for (let value of yearMissionData.data ) {<br>    let flightNumber = value.flight_number;<br>    let missionId = _.get(value, &#39;mission_id[0]&#39;);<br>    let rocketName = _.get(value, &#39;rocket.rocket_name&#39;);<br>    if ( flightNumber &amp;&amp; missionId &amp;&amp; rocketName ) {<br>      flightWithMission =  {<br>       flightNumber: flightNumber,<br>       missionId: missionId,<br>       rocketName: rocketName<br>     };<br>     break;<br>    }<br>  }<br>  resolve(flightWithMission);<br>  });<br>}</pre><pre>function <strong>getSpaceDataForYear</strong>(year) {<br>  return axios.get(&#39;https://api.spacexdata.com/v3/launches/past&#39;, {<br>  params: {<br>   launch_year: year<br>   }<br> });<br>}</pre><pre>function <strong>getMissionDetails</strong>(flight) {<br>  return<br> axios.get(<br>  `https://api.spacexdata.com/v3/missions/${flight.missionId  }`<br>  );<br>}</pre><h3>Stage Two Evaluation</h3><p>I have two major issues with the second round of WET (have you noticed yet that frantic code typing is not healthy coding?):</p><ul><li>The main API demo code block is concise; however, it isn’t necessarily clear how data is being passed from one step to the next. Perhaps for some it may be fine; however, it still didn’t look quite right to me.</li><li>In order to achieve the conciseness I modified every method to return a Promise. This seemed like a mistake as well.</li></ul><h3>Stage Three</h3><p>I was on a roll at this point in my re-acquaintance with the variants of JavaScript promises, so I thought I should continue. After all, I had already doubled the expected time I thought I would spend on this task, I may as well make it triple the time.</p><p>This time, I would pull out the final stop, and utilize the JavaScript functionality of async / await.</p><p>Here is the main code block after the refactor:</p><pre>(async () =&gt; {<br>  let flightData = <strong>await</strong> <strong>getSpaceDataForYear</strong>(&quot;2018&quot;);<br>  let flightWithMission = <strong>findFlightWithAMission</strong>(flightData);<br>  <strong>outputMissionDataSummary</strong>(flightWithMission);<br>  let missionDetails = <strong>await</strong> <strong>getMissionDetails</strong>(flightWithMission);<br>  <strong>outputMissionDetail</strong>(missionDetails);<br>})();</pre><p>The await keyword essentially erases the callback, erases the promise, and states:</p><blockquote>“wait for this to complete, and give me the return data.”</blockquote><p>Technically, the promise is not really erased; however, the goal is to give that appearance to your code.</p><p>The necessary syntax on the function itself is to add the async keyword to the beginning, as illustrated below.</p><pre><strong>async</strong> function <strong>getSpaceDataForYear</strong>(year) {<br>  return axios.get(&#39;https://api.spacexdata.com/v3/launches/past&#39;, {<br>   params: {<br>    launch_year: year<br>   }<br> });<br>}</pre><p>There is one last little important thing to note, which of course adds one last little wart to the main code flow, which is that await is only valid within an async function.</p><p>In order to work around this, I wrapped the main flow inside an IIFE (Immediately Invoked Function Expression) with the async keyword. This was a small price I believe, as now asynchronous methods are clearly noted, and the code is more readable.</p><h3>Summary</h3><p>I hope you have enjoyed the walkthrough, the sample usage of the SpaceX API, and the various examples of how your code may look with different callback / promise mechanisms.</p><p>Some of my key takeaways from this exercise are:</p><ul><li>Always plan ahead. Unless you have the goal of constant refactoring for the point of refactoring itself (WET principle), then measuring twice, cutting once can save some time.</li><li>It never hurts to research. Before embarking on a coding exercise, it never hurts to read up on the options for implementation. Even if it is for a non-production scenario, knowledge is power.</li></ul><h3>Final Code</h3><p>Here is the final source code for my mock exercise. This may be my motivation to write that automated bot to check for the next space flight and trip to Florida.</p><pre>const axios = require(&#39;axios&#39;);<br>const _ = require(&#39;lodash&#39;);</pre><pre>(async () =&gt; {<br>  let flightData = <strong>await</strong> <strong>getSpaceDataForYear</strong>(&quot;2018&quot;);<br>  let flightWithMission = <strong>findFlightWithAMission</strong>(flightData);<br>  <strong>outputMissionDataSummary</strong>(flightWithMission);<br>  let missionDetails = <strong>await</strong> <strong>getMissionDetails</strong>(flightWithMission);<br>  <strong>outputMissionDetail</strong>(missionDetails);<br>})();</pre><pre>function <strong>outputMissionDetail</strong>(missionResult) {<br>  console.log(`Mission Name: ${missionResult.data.mission_name}`);<br>  console.log(`Mission ID: ${missionResult.data.description}`);<br>}</pre><pre>function <strong>outputMissionDataSummary</strong>(flight) {<br>  console.log(`Flight number: ${flight.flightNumber}`);<br>  console.log(`Mission ID: ${flight.missionId}`);<br>  console.log(`Rocket name: ${flight.rocketName}`);<br>}</pre><pre>function <strong>findFlightWithAMission</strong>(yearMissionData) {<br>  var flightWithMission = null;<br>  for (let value of yearMissionData.data ) {<br>   let flightNumber = value.flight_number;<br>   let missionId = _.get(value, &#39;mission_id[0]&#39;);<br>   let rocketName = _.get(value, &#39;rocket.rocket_name&#39;);<br>   if ( flightNumber &amp;&amp; missionId &amp;&amp; rocketName ) {<br>    return  {<br>     flightNumber: flightNumber,<br>     missionId: missionId,<br>     rocketName: rocketName<br>   };<br>  }<br> }<br>}</pre><pre><strong>async</strong> function <strong>getSpaceDataForYear</strong>(year) {<br>  return axios.get(&#39;https://api.spacexdata.com/v3/launches/past&#39;, {<br>  params: {<br>  launch_year: year<br> }<br> });<br>}</pre><pre><strong>async</strong> function <strong>getMissionDetails</strong>(flight) {<br> return<br> axios.get(`https://api.spacexdata.com/v3/missions/${flight.missionI<br> }`);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be0f3c50bcc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>