<?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[NextFaze - Medium]]></title>
        <description><![CDATA[Smart developers for smart ideas - Medium]]></description>
        <link>https://medium.com/nextfaze?source=rss----980139edfe2---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>NextFaze - Medium</title>
            <link>https://medium.com/nextfaze?source=rss----980139edfe2---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 08:26:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/nextfaze" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Supercharge ⚡️ your DynamoDB  single-table design pattern with TypeDORM]]></title>
            <link>https://medium.com/nextfaze/supercharge-%EF%B8%8F-your-dynamodb-single-table-design-pattern-with-typedorm-39168d0d2e29?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/39168d0d2e29</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[single-table-design]]></category>
            <dc:creator><![CDATA[Rushi Patel]]></dc:creator>
            <pubDate>Wed, 26 May 2021 10:02:41 GMT</pubDate>
            <atom:updated>2021-05-26T10:02:41.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supercharge ⚡️ your DynamoDB single-table design pattern with TypeDORM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOoFGZ-gVMHvVFt4yokPOA.jpeg" /></figure><p><a href="https://www.youtube.com/watch?v=KYy8X8t4MB8">Single-table design for DynamoDB</a> has gained popularity due to the increased ability to query relational data in No-SQL databases.</p><p>The <a href="https://github.com/typedorm/typedorm">TypeDORM</a> is an Object Relational Mapper library running in Node,js and written in Typescript. <a href="https://github.com/typedorm/typedorm">TypeDORM</a> is a feature-rich DynamoDB ORM to help you write high-quality, loosely coupled, scalable, and maintainable applications with highly relational data in the most productive way.</p><h4>What this article is about</h4><p>In this article, we will be looking at different challenges that may arise while developing with DynamoDB using a single-table-design pattern and how <a href="https://github.com/typedorm/typedorm">TypeDORM</a> can help us avoid them.</p><h4>What this article is NOT about</h4><p>We will not be covering why and who should use DynamoDB single-table design as <a href="https://medium.com/u/3c9962a8238">Alex DeBrie</a> has done an excellent job at explaining it <a href="https://www.alexdebrie.com/posts/dynamodb-single-table/">here</a>.</p><p>Once you understand how single-table design works with DynamoDB, you would want to try it out with a real-life example. There is already a very popular article by <a href="https://medium.com/u/b8d1e8a0e0d8">Forrest Brazeal</a> that can be found <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">here</a>, which you should first look at before continuing with this article.</p><h4>What you should know before moving on</h4><ul><li><a href="https://www.alexdebrie.com/posts/dynamodb-single-table/">What is a single-table-design pattern</a></li><li><a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">How it works with a real-life relational dataset</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRuKGrhME7zewM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FRuKGrhME7zewM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FRuKGrhME7zewM%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3cb345d52915c15cf89acef523df124/href">https://medium.com/media/d3cb345d52915c15cf89acef523df124/href</a></iframe><p>Once you are familiar with the single-table design pattern and have also looked at how it can be used to model highly relational data in DynamoDB, let’s talk about why it isn’t a very viable way to work with data and what can we do to make it better.</p><p>When first introduced to single-table-design, there are some common questions and concerns developers start to ponder:</p><ul><li>I can’t use a single-table design, I need operation time “types safety”.</li><li>All the attributes and their names just don’t make sense anymore, how do I reliably interact with them?</li><li>As I keep adding more indexes, how do I make sure that all the attributes created for modeling don’t end up returning to clients?</li><li>If I choose to keep the original attribute value and its index-referenced attribute separate, how do I make sure they are always in sync?</li><li>How do I keep the key schema up to date with a matching pattern for each entity that I add?</li><li>How do I confidently interact with all entities without having to remember to provide correct condition expressions for common operations (i.e for unique attributes, making sure to always include condition expressions with attribute_not_exists)?</li><li>With a single table design, I can’t use data mapper libraries.</li><li>The resulting code is hard to read as there are too many attributes/symbols representing different meanings.</li><li>My colleges may know how to work with the DynamoDB but this particular way is very unfamiliar.</li><li>I want to use the single-table design but I don’t want to manage each entity schemas in a separate spreadsheet.</li></ul><p>There might be many more questions but most of them are pointing to one concern in particular:</p><blockquote>“Do I really want to trade off development ease, developer experience, code quality over this new way of working with DynamoDB?”</blockquote><p>The answer is: you don’t have to. There is a better option.</p><p>Let me introduce you to <a href="https://github.com/typedorm/typedorm"><strong>TypeDORM</strong></a>: Strongly typed ORM for DynamoDB — Built for the single-table-design pattern. Let’s first have a quick look at what it is and how it can help us to solve all the problems stated earlier.</p><p>Later, we will also have a look at how we can leverage TypeDORM to better structure entities (continuing from the example from <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">this</a> great article).</p><h3>Introduction to <a href="https://github.com/typedorm/typedorm">TypeDORM</a></h3><p>TypeDORM is an ORM built from the ground up using TypeScript to provide an easy entry point when doing complex, highly relational data modeling in DynamoDB. Its syntax might be familiar since the decorator-based syntax is highly influenced by TypeORM — one of the very popular ORM for working with SQL databases.</p><p>Let’s take a quick look at some of the many features that TypeDORM provides:</p><ul><li>Single table design first-class support</li><li>DataMapper development pattern</li><li>Full type safety enabled using advanced typescript generics</li><li>Declarative relational schema</li><li>Multiple connections support</li><li>Operation based managers per connection, includes Entity manager, Transaction manager, Batch manager, and Scan Manager</li><li>Code follows all possible best practices and provides first-class support for some of the very popular patterns used in the single-table-design pattern</li><li>Additional higher-level features like, such as the ability to declare non-key attribute as unique, automatic retries</li><li>Auto-Generated values for attributes</li><li>Auto-update attributes and its referenced indexes on UPDATE operations</li><li>Dynamic &amp; Static default values for attributes</li><li>Complex update, key condition, and condition expression all made easy to work with</li><li>Powerful expression builder to auto-generate expressions from typesafe input</li></ul><h3>Getting Started with TypeDORM</h3><h4>Installing</h4><p>Let’s first install all the modules that we will need.</p><pre>npm install @typedorm/common @typedorm/core --save</pre><p>We will also need to install reflect-metadata shim that TypeDORM relies on and configure it so that metadata’s are correctly detected by TypeDORM</p><pre>npm install reflect-metadata --save</pre><h4>Enable emitting metadata at runtime</h4><p>If you are using TypeDORM with TypeScript, make sure you also have the below options enabled in yourtsconfig.json</p><pre>&quot;emitDecoratorMetadata&quot;: true,<br>&quot;experimentalDecorators&quot;: true,</pre><p>Once this is done we need aws-sdk which TypeDORM uses to communicate with the DynamoDB table.</p><pre>npm install aws-sdk --save</pre><p>We are all set now, next we will need to configure the connection. If you have ever worked with <a href="https://github.com/typeorm/typeorm">TypeORM</a>, this setup will look very familiar.</p><p>In the next section, we will have a look at the relational data set that we will be working with. You can always refer back to <a href="https://medium.com/u/b8d1e8a0e0d8">Forrest Brazeal</a>’s <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">article</a> any time you feel lost.</p><h3>Getting to know our data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W_E9H-r1KZc3VKcenB0Keg.png" /><figcaption>credit: Forrest Brazeal</figcaption></figure><p>Here are some access patterns that Brazeal has listed:</p><ol><li>Get employee by employee ID</li><li>Get direct reports for an employee</li><li>Get discontinued products</li><li>List all orders of a given product</li><li>Get the most recent 25 orders</li><li>Get shippers by company name</li><li>Get customers by contact name</li><li>List all products included in an order</li><li>Get suppliers by country and region</li></ol><h4>Entities that we will be working with</h4><p>These are all the entities we will need to create with a given signature to fulfill our access patterns. Here is a slightly modified version of the Entity chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGk7nz4WKCb1G1ny9oxNqQ.png" /><figcaption>Entity chart</figcaption></figure><p>The process of selecting what goes under PK and SK remains the same as described <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">here</a>.</p><p>If you were following this closely, you will notice few differences between the above entity chart and one presented by Brazeal, Which are:</p><ul><li>Each attribute is only ever referenced in a single index</li><li>Each entity PK now has a prefix of STATIC entity type — this helps us better identify items where they are all put together in the same table as well as allows us to use incrementing ids</li></ul><h4>Our access patterns</h4><p>Here is the list of all access patterns and what attributes we will be querying on. In case you didn’t follow <a href="https://www.trek10.com/blog/dynamodb-single-table-relational-modeling">this</a> article and came up with different access patterns, that’s perfectly okay too.</p><p>Hereafter building on top of Brazeal’s access patterns, this is what it looks like now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fH4-cGmu5eHjOsoBZXB0g.png" /><figcaption>Access patterns</figcaption></figure><p>You will still have to follow all the steps required in a single-table design pattern, with one slight change being that all the entities need to have a SQL-like entity structure (of course, you can still add more attributes to entities later).</p><p>Understanding how to build an entity schema would be a different article on its own — our main focus is how we can reliably work with the above entities using TypeDORM.</p><h3>Developing with <a href="https://github.com/">TypeDORM</a></h3><p>This section will focus on getting connections, entities, tables configured for TypeDORM that can effectively parse data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLr3UeH9tYu3qJtsSUg%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLr3UeH9tYu3qJtsSUg%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLr3UeH9tYu3qJtsSUg%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="336" frameborder="0" scrolling="no"><a href="https://medium.com/media/7283cb737636d96c18333ad23608e4c0/href">https://medium.com/media/7283cb737636d96c18333ad23608e4c0/href</a></iframe><h4>Declare a Table</h4><p>Since we are doing a single-table design we really only need a single DynamoDB table with a single Global Secondary Index (GSI). We declare that by creating a new instance of Table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ac8aa60ed8fb1a3ede4ca3c6de3797c/href">https://medium.com/media/1ac8aa60ed8fb1a3ede4ca3c6de3797c/href</a></iframe><h4>Define entities</h4><p>Now it’s time to covert our entity chart into an actual TypeDORM entity, we do this by annotating our model with @Entity decorator, exported by @typedorm/common . Product and Employee entities are the only ones listed here, but you got the overall idea.</p><p><em>Note: TypeDORM exposes various decorators to be able to declaratively define an entity. For those not listed here, check out the </em><a href="https://github.com/typedorm/typedorm/blob/main/docs/api.md"><em>TypeDORM API specification</em></a><em> for more up-to-date APIs.</em></p><p><em>Product Entity</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c80521b5818b7f2f6981a397cb227a5/href">https://medium.com/media/0c80521b5818b7f2f6981a397cb227a5/href</a></iframe><p><em>Employee Entity</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15e6650b3b6908c8f484bb64bcd8f488/href">https://medium.com/media/15e6650b3b6908c8f484bb64bcd8f488/href</a></iframe><p>You will need to define all entities in a similar way to the above examples.</p><h4>Establishing a connection</h4><p>Once we have all the entities in, the next thing is to initialize a DynamoDB connection. We do this by creating a connection instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c4692b9465c075d49be2780eca0496e/href">https://medium.com/media/0c4692b9465c075d49be2780eca0496e/href</a></iframe><p>If all of your entities are grouped under the same directory, you can also provide a relative path to entities option and TypeDORM will auto load all the entities from a given path.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26FPnsRww5DbqoPuM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26FPnsRww5DbqoPuM%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26FPnsRww5DbqoPuM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="237" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fa5dab1bf1c2a776f3bd00f1eb20ea2/href">https://medium.com/media/5fa5dab1bf1c2a776f3bd00f1eb20ea2/href</a></iframe><p>Now since we have everything in place, we are ready to work with a single-table designed DynamoDB table in a type-safe way.</p><h4>Querying records</h4><p>Once everything is set up, it’s will be super easy to perform all kinds of operations like Create, Delete, Put, Update, all in a type-safe way.</p><p>For example, let’s have a look at what our queries will look like for the first two access patterns:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2241617fd63a2648c9db8c971e4efa8/href">https://medium.com/media/e2241617fd63a2648c9db8c971e4efa8/href</a></iframe><p>P.S. You can provide additional options to filter/log queries.</p><p>For the most up-to-date list of available options and entity have a look at <a href="https://github.com/typedorm/typedorm/blob/main/docs/api.md">API Spec</a>.</p><p>Even though we have only covered querying items with TypeDORM here, there are many more use-cases where TypDORM proves its worth. Experiment with different TypeDORM APIs and tell us what you think in the comments.</p><h3>More about TypeDORM</h3><p>TypeDORM is committed to delivering new features every month until all the major document client APIs are covered, meanwhile if you want to access the feature before the release we also publish a beta version.</p><p>To find out more about what new features are on the road map, check out the <a href="https://github.com/typedorm/typedorm/projects/1">TypeDORM public roadmap</a>.</p><p>If there are any other features you would like to be included, open a new issue <a href="https://github.com/typedorm/typedorm/issues/new">here</a>.</p><p><strong>Thanks for reading! If you liked this article, hit that clap button below👏 . It means a lot to us and it helps others easily find this article. For more updates follow us on </strong><a href="https://medium.com/nextfaze"><strong>Medium</strong></a><strong> or <em>follow me on </em></strong><a href="https://github.com/whimzyLive"><strong><em>Github</em></strong></a><strong><em>.</em></strong></p><p><em>Special thanks to </em><a href="https://medium.com/u/746c9ee6236f"><em>Zak Barbuto</em></a><em> for proofreading this article.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39168d0d2e29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/supercharge-%EF%B8%8F-your-dynamodb-single-table-design-pattern-with-typedorm-39168d0d2e29">Supercharge ⚡️ your DynamoDB  single-table design pattern with TypeDORM</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debug Angular 10 Karma Tests in VSCode]]></title>
            <link>https://medium.com/nextfaze/debug-angular-10-karma-tests-in-vscode-9685b0565e8?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/9685b0565e8</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[karma]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Zak Barbuto]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 00:51:07 GMT</pubDate>
            <atom:updated>2021-10-04T21:55:10.545Z</atom:updated>
            <content:encoded><![CDATA[<h3>Debug Angular 12 Karma Tests in VSCode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lrc2f2njnYMeen_e4TPlXg.png" /></figure><p><strong>Update 2021–10–05: </strong>This still works with Angular 12. I changed the launch config slightly and added a note about testing a single file.</p><p>Angular does not come with a launch.json for VSCode out of the box. What’s worse, if you do some Googling for “debugging karma tests in VSCode” the results you get are likely quite out of date — intended for very old versions of either Angular or VSCode.</p><p>Here’s some minimal changes to a brand new Angular 10 CLI project that will allow you to attach the VSCode debugger to your running Karma tests.</p><h4>1. Update your karma.conf.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c2d2cf36698074217117ecec65ed375/href">https://medium.com/media/5c2d2cf36698074217117ecec65ed375/href</a></iframe><p>Highlighting the only parts that need to be added:</p><pre>browsers: [&quot;ChromeHeadlessNoSandbox&quot;],<br>    customLaunchers: {<br>      ChromeHeadlessNoSandbox: {<br>        base: &quot;ChromeHeadless&quot;,<br>        flags: [<br>          &quot;--no-sandbox&quot;,<br>          &quot;--user-data-dir=/tmp/chrome-test-profile&quot;,<br>          &quot;--disable-web-security&quot;,<br>          &quot;--remote-debugging-address=0.0.0.0&quot;,<br>          &quot;--remote-debugging-port=9222&quot;,<br>        ],<br>        debug: true,<br>      },<br>    },</pre><p>The important parts being we are now using headless chrome (since we are using VSCode for our debugging, we don’t need to open a full Chrome instance any more) and we are configuring a remote debugging port.</p><h4>2. Create a launch.json</h4><p>If you’re happy to run all your tests through ng test then you really only need the first configuration which connects the debugger to our headless Chrome instance. However, you typically don’t want to run your full test suite when you’re debugging tests in just one file. I like the convenience of being able to just hit F5 and run ng test on my currently open test file, which is what the second configuration is for.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe61a9f529ac0e94ec2aacd29b046e45/href">https://medium.com/media/fe61a9f529ac0e94ec2aacd29b046e45/href</a></iframe><p>The important parts here are that:</p><ol><li>Our port matches the remote-debugging-port in your karma.conf.js</li><li>We enable source maps and have the pathMapping set up as above</li><li>We use &quot;type&quot;: &quot;pwa-chrome&quot; instead of just &quot;chrome&quot; in the latest VSCode so we don’t need the <a href="https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome">Debugger for Chrome</a> extension. However, if you have that extension installed, feel free to substitute &quot;pwa-chrome&quot; for &quot;chrome&quot; — the rest of the config can remain the same.</li><li>&quot;restart&quot;: true ensures that the task keeps running even when our tests exit — useful if you are testing files one at a time, for example.</li></ol><h4>Run your tests and attach</h4><p>Run your Angular tests however you like — either via ng test in the terminal and then run the “Attach to Karma” configuration <strong>or</strong> just run the the “Run test file” launch configuration with a spec test file open in the editor (note that the Attach to Karma” task still needs to be running in the background when running “Run test file”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*HQ3VbLeNHOICpJkW8VpuCA.png" /><figcaption>Play “Attach to Karma” with `npm test` running in the background</figcaption></figure><p>You should now be able to set breakpoints and — as your tests re-run when you make changes— VSCode will pause as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rc-fsqLo5qDhmV4fyk52EA.png" /></figure><h4>That’s it!</h4><p>Short, sharp and sweet. Hope this helped you out, and have a great rest of your day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9685b0565e8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/debug-angular-10-karma-tests-in-vscode-9685b0565e8">Debug Angular 10 Karma Tests in VSCode</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Serverless API with Nestjs and AWS CDK]]></title>
            <link>https://medium.com/nextfaze/deploying-serverless-api-with-nestjs-and-aws-cdk-3d41063543e0?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d41063543e0</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[serverless-api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Rushi Patel]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 09:33:44 GMT</pubDate>
            <atom:updated>2020-09-04T09:33:14.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLwEVxd65nyttqubxclHdg.jpeg" /></figure><h3>What this article is about</h3><p>Javascript has evolved a lot in recent years and its ecosystem is bigger today than it was ever before. We are seeing more and more frameworks coming out everyday that help us write more clean, robust and highly manageable code. In this article we will mainly be looking at technologies and tools that can help us build <strong>secure,</strong> <strong>scalable</strong>, <strong>reliable</strong>, <strong>efficient</strong>, and <strong>affordable</strong> API.</p><p>we will mainly be looking two technologies: <strong>AWS CDK </strong>and<strong> NestJS</strong>.</p><p>Let’s cover some basic ground on CDK (Cloud Development Kit) and NestJs, so everyone is on the same page.</p><p>Our goal here is to build a server-less API without losing tools that we already know and like to work with. You should have some working knowledge of building serverless applications on cloud and <a href="https://hackernoon.com/what-is-serverless-architecture-what-are-its-pros-and-cons-cc4b804022e9">why go serverless</a> as this article <strong>does not</strong> explore reasons to create serverless api.</p><h3>What is AWS CDK and why use it</h3><p>AWS CDK a.k.a Cloud Development Kit is a new addition to AWS’s I<strong>nfrastructure as code</strong> initiative, to help developers provision resources on cloud with the languages that they like. You can read more about it <a href="https://docs.aws.amazon.com/cdk/latest/guide/home.html">here</a> as we won’t be going into the details of how it works. Instead we will have look at how to get a demo application up and running. 👨‍💻</p><p><em>AWS CDK also comes with a CLI tool which makes development and deployment experience very smooth.</em></p><h3>What is NestJs</h3><blockquote>A progressive Node.js framework for building efficient, reliable and scalable server-side applications. — <a href="https://nestjs.com/">Nestjs</a></blockquote><p>NestJs is a framework that enables developers to take advantage of Angular style Dependencies Injection (DI) for building highly maintainable APIs. It is built with Typescript and combines elements of Object Oriented Programming, Functional Programming and Functional Reactive Programming.</p><p><em>NestJs has a CLI to help developers quickly get started and also takes care of inferring types for swagger template without having to manually annotate each operation.</em></p><h3>But why run NestJs on lambda?</h3><p>Now you might be wondering why you would want to run a NestJs application on a Lambda, If not, you can skip this section.😉</p><p>If you have previously done some Serverless applications than you might already know how much of a blessing a <a href="https://dashbird.io/blog/business-benefits-of-serverless/">Serverless</a> application is over traditional ones that requires a server (On premises and Cloud) constantly running even though no one is using it. This is especially true when you are a startup or have an unpredictable workload. Building Serverless API can be hard as most of the frameworks and practices that we have developed in past many years simply do not work as is, instead we have small executable functions where we write a business logic and then configure it to run on some event or an operation. This means we need to create resource for each resource, and even each operation, not to mention the various limits set by cloud providers (<a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html">AWS</a>, <a href="https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/template-best-practices#template-limits">Azure</a>) when we try to do this. (i.e AWS cloudformation has a max limit of 200 resources per a template).</p><p>By running NestJs application on lambda we can try to get best of both world, We get reliability, and affordability and security from AWS world and scalability and better overall better development experience from NestJs land.</p><p>I hope I have convinced most of you on why to run NestJs application on lambda. Now let’s first have a look at what we will be building today and then jump straight into coding.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5QTOKia3HPBLvg9ROL%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5QTOKia3HPBLvg9ROL%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5QTOKia3HPBLvg9ROL%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="184" frameborder="0" scrolling="no"><a href="https://medium.com/media/fba090b0dd09749bc5047817339e36e0/href">https://medium.com/media/fba090b0dd09749bc5047817339e36e0/href</a></iframe><h3>What we are going to build</h3><ul><li>API with CRUD operations for <strong><em>todos</em></strong></li><li>User <strong>Authentication</strong> using Cognito</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVKu5GJJbacYByHIJ6ei9Q.png" /></figure><h3>Local Environment Prerequisites</h3><ul><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html">AWS Cli</a> installed and configured with <strong>admin</strong> permissions</li><li><a href="https://www.npmjs.com/package/@nestjs/cli">Nestjs Cli</a> installed</li></ul><h3>Getting Started With Setting up Project</h3><blockquote>Bootstrap a cdk project</blockquote><pre>npx cdk init --language typescript</pre><p>This will install all the necessary tooling required to deploy our app to the cloud, because CDK often actively gets new updates, it is possible that by the time you are reading this article AWS CDK might have a new latest version then the one bootstrapped with above command, to update all the dependencies run and follow onscreen commands.</p><pre>npx npm-check-updates -u</pre><blockquote>Next, bootstrap nestjs project with name <strong>api</strong></blockquote><pre>nest new api --skip-git</pre><p>Now we have everything that we will need to create our first serverless API</p><h3>Configuring required resources for cloud ☁️️</h3><p>Before going further make sure you are in a root directory of the project, since all the dependencies that we will install now will only be required at the deployment time.</p><h4>Adding User Authentication using AWS Cognito User Pools</h4><p>Create a new Cogito construct that extends base CDK Constrct which will contain all of our auth resources.</p><blockquote>Create Cognito Construct</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21b31dd3cbc2c1ca70788ce3e0e16927/href">https://medium.com/media/21b31dd3cbc2c1ca70788ce3e0e16927/href</a></iframe><blockquote>add user pool to store user sessions</blockquote><p>First, we will configure user pool as following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/731cf3c14ec83e48a2e2e40b505e1d79/href">https://medium.com/media/731cf3c14ec83e48a2e2e40b505e1d79/href</a></iframe><blockquote>add user pool client which will allow api users to get auth tokens on login</blockquote><p>Next, we will add user pool client for earlier user pool</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f563c12317e5b09a33037fedf814c1b6/href">https://medium.com/media/f563c12317e5b09a33037fedf814c1b6/href</a></iframe><blockquote>Configure hosted OAuth server</blockquote><p>Finally, we will add a hosted OAuth server to our Cognito construct.</p><p>Instead of using Cognito hosted UI, we can also other auth flows that AWS Cognito supports but that is out of scope for the purpose of this article. So for this demo we will just stick to using cognito hosted ui.</p><p><em>Don’t forget to change </em><em>domainPrefix to be of your choice, as there can only be one app with any given name</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37751906932b40a670f020b709a2ae73/href">https://medium.com/media/37751906932b40a670f020b709a2ae73/href</a></iframe><p>Now we are all set for user signup/login, next let’s have a look at configuring Amazon API Gateway resource and AWS Lambda.</p><h4>Adding API Gateway proxy lambda resource</h4><p>Our Authentication service is configured, now we are going to add API gateway resource with backed by lambda function.</p><blockquote>Configure Lambda function and lambda layer</blockquote><p>First, add a lambda function to handle all incoming api requests. When AWS invokes your lambda function in response to configured events, it expects all of the runtime dependencies to be available next to application code.To satisfy this requirement and to also keep out application logic from its dependencies, we will use lambda layers.</p><p>Layers allows for easy sharing of external dependencies and greatly improves development experience, as all of dependencies live in a seperate directory that which gets packed and deployed separately to actual business logic.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oEduJ323JmMXE4Yxi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oEduJ323JmMXE4Yxi%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3oEduJ323JmMXE4Yxi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b072606d99c4c85c2f15d5efdff4f20/href">https://medium.com/media/5b072606d99c4c85c2f15d5efdff4f20/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bace7f8d9f749b0a688d047f653de36b/href">https://medium.com/media/bace7f8d9f749b0a688d047f653de36b/href</a></iframe><p><em>Also make sure to exclude node_modules dir from code asset.</em></p><blockquote>Configure API Gateway resource</blockquote><p>Next, we will add an api gateway resource to respond to all incoming http connections and an api key with usage plan configured.</p><p>Usage plan and API key allow us to enable API monitoring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54ff726d928de198f3436f822ba00804/href">https://medium.com/media/54ff726d928de198f3436f822ba00804/href</a></iframe><p><em>Configuring api key and usage plan is completely optional and can be skipped, if you do not with to have api monitoring.</em></p><blockquote>Create Dynamo DB table to store our todos</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ede0139aeb4808a6e740eb6dbf166ad/href">https://medium.com/media/9ede0139aeb4808a6e740eb6dbf166ad/href</a></iframe><blockquote>Enable Cognito Authentication</blockquote><p>Finally, we will be adding cogito authorizer to authenticate incoming requests. We want to eliminate all bad traffic with no or bad tokens long before it ever gets to our lambda function.</p><p>AWS CDK is very new and continuously evolving so it might not have the all the services available as a higher level constructs but you can always use low level Cfn Constructs. At the time of writing this article, aws cdk does not have a construct to create a cognito authorizer so to work around that we will be using low level <em>CfnAuthorizer.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22388e4f94dfeced30be7e6166e04479/href">https://medium.com/media/22388e4f94dfeced30be7e6166e04479/href</a></iframe><p>This is all that we need in order to be able to deploy our awesome serverless api. In the next section, we will look into how to make Nestjs respond to different endpoints and some neat things that you can do using Nestjs.</p><p>If you made it this far, congrats! Give your self a small break and come back when you are ready for more.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fg9582DNuQppxC%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fg9582DNuQppxC%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fg9582DNuQppxC%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/0eba96b395f1e17a357fe179074ce870/href">https://medium.com/media/0eba96b395f1e17a357fe179074ce870/href</a></iframe><h3>Going wild with Nestjs</h3><h4>Adding serverless capability to our Nestjs application</h4><blockquote>Updating app listener to respond to lambda invocation</blockquote><p>In our main.ts, change the cli generated function with following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369863a920c214c5c8e70d313c56f11d/href">https://medium.com/media/369863a920c214c5c8e70d313c56f11d/href</a></iframe><p><em>Here, we are simply exporting named function ‘api’, which if you remember was set as an entry point in api handler.</em></p><h4>Add todos controller</h4><p>Controller in Nestjs are responsible for managing incoming requests and responses and it is the only piece of code that directly gets mounted onto a route.</p><p>First we will add <strong>todos controller</strong> using nest cli, to do that navigate to /api directory and execute following command.</p><blockquote>bootstrap initial controller files using cli</blockquote><pre>nest generate controller todos</pre><p>this will create a todos controller and register it in app module.</p><blockquote>Next, we will create Create, Read, Put, Delete endpoints</blockquote><p>This is the brief of what each endpoints needs to do.</p><p><strong>Create: </strong>creates a todo item with given data for user</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ffb5a146f40024b799daa15e7bf0907/href">https://medium.com/media/8ffb5a146f40024b799daa15e7bf0907/href</a></iframe><p><strong>Read: </strong>Get all todos and by id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a0de525fd7186af9f96c9c3991286c/href">https://medium.com/media/d5a0de525fd7186af9f96c9c3991286c/href</a></iframe><p><strong>Update: </strong>Update item with given id</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad4e03dc1bbdbf34747cd92312b3b11a/href">https://medium.com/media/ad4e03dc1bbdbf34747cd92312b3b11a/href</a></iframe><p><strong>Delete: </strong>delete all delete an item by id and</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13730dfbbcfc0a965680960e205e376d/href">https://medium.com/media/13730dfbbcfc0a965680960e205e376d/href</a></iframe><h3>Deploying</h3><p>We will use CDK cli to deploy our application to AWS. Make sure you have AWS credential configured on your machine with required permissions.</p><p>If you have never used CDK cli to deploy application, then there will be one additional step required before actually deploying our stack, we will need to deploy <a href="https://github.com/aws/aws-cdk/blob/master/design/cdk-bootstrap.md">CDK toolkit</a> stack to deploying region, so that CDK cli can attach and find metadata that it creates.</p><blockquote>To Bootstrap CDK toolkit stack, run</blockquote><pre>npm run cdk bootstrap</pre><p>then, to deploy our awesome serverless API simply run</p><pre>npm run cdk deploy</pre><p>CDK cli will use your default aws credentials configured with aws cli. Incase you have more than one profiles set up you can choose specific one by appending profile flag .</p><pre>npm run cdk deploy -- --<em>profile &lt;profileName&gt;</em></pre><p>That is it, if there were no deploy time errors, you should have a Serverless API that is <strong>secure,</strong> <strong>scalable</strong>, <strong>reliable</strong>, <strong>efficient</strong>, and <strong>affordable, </strong>just as we talk about.</p><h3><strong>Testing</strong></h3><p>Head over to <a href="https://signin.aws.amazon.com/signin?redirect_uri=https%3A%2F%2Fap-southeast-2.console.aws.amazon.com%2Fcognito%2Fusers%2F%3Fregion%3Dap-southeast-2%26state%3DhashArgs%2523%252Fpool%252Fap-southeast-2_inVBZaxRO%252Fapp-integration-app-settings%253F_k%253Doh52b8%26isauthcode%3Dtrue&amp;client_id=arn%3Aaws%3Aiam%3A%3A015428540659%3Auser%2Fcognito&amp;forceMobileApp=0&amp;code_challenge=YK3PS-Yac5FFcs1fVs-uBRgdueCIr8y9MAQ7tt7kwW4&amp;code_challenge_method=SHA-256">AWS console</a> and then to a <em>region</em> that our resources were created. Next navigate to AWS Cognito and look for Lauch Hosted UI under App Client settings</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*u7ifSsfVvZRedVhKuuv57w.png" /></figure><p>Click on the Hosted UI and login/register a user. Once logged in you will be navigated to https://www.google.com if following above example (If you remember correctly, this is what we had setup as a callback url in <strong><em>Adding User Authentication using AWS Cognito User Pools</em></strong><em> section</em>), and locate tokens(mainly <strong><em>id_token</em></strong> and <strong><em>access_token</em></strong>) in query params, note them somewhere as we will need this later for invoking the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*hBuXfFZumSpNloIsCBPC9g.png" /></figure><p>Next in a different tab, open up <strong>API Gateway </strong>page,</p><p>then under <strong><em>APIS &gt; Stages &gt; v1 </em></strong>and copy the invoke URL (yes this is our deployed api url) and API key from <strong><em>APIS &gt; API Keys &gt; key.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrkezTn3-otCkh6g5pTBuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*uau6IhndMNovAZkT0WpUHw.png" /></figure><p>That’s everything we need, now open up Postman or any REST api client and invoke our API. Don’t forget to try all GET, POST, PUT and DELETE operations!</p><blockquote>i.e With cURL it will look something like this</blockquote><pre>curl --location --request GET &#39;https://{api-id}.execute-api.{region}.amazonaws.com/v1/users/{userId}/todos&#39; \</pre><pre>--header &#39;x-api-key: &lt;Your API Key&gt;&#39; \</pre><pre>--header &#39;Authorization: Bearer &lt;Your Id Token&gt;&#39;</pre><h3>Where to next…</h3><p>Complete working example is available on <a href="https://github.com/NextFaze/awesome-serverless-api">github</a>.</p><p>In the next article we will look at using NestJs with non-http AWS services, like invoking a lambda to respond to some Cloudwatch event or an S3 upload. In addition to this, we will also have a look at adding live documentation to our Serverless API (no more need to manage documentation manually 🤓) and generating client SDK(Software Development Kit) using Swagger code gen .</p><p>Happy Serverlessing!</p><p><strong>Thanks for reading! If you liked this article, hit that clap button below👏 . It means a lot to me and it helps others more easily find this article. For more updates follow us on </strong><a href="https://medium.com/nextfaze"><strong>Medium</strong></a><strong> or <em>follow me on </em></strong><a href="https://github.com/whimzyLive"><strong><em>Github</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d41063543e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/deploying-serverless-api-with-nestjs-and-aws-cdk-3d41063543e0">Deploying Serverless API with Nestjs and AWS CDK</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proxy Objects for Quick and Dirty Service Mocks in Jest]]></title>
            <link>https://medium.com/nextfaze/proxy-objects-for-quick-and-dirty-service-mocks-in-jest-975c69a83809?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/975c69a83809</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Zak Barbuto]]></dc:creator>
            <pubDate>Fri, 06 Sep 2019 03:31:01 GMT</pubDate>
            <atom:updated>2023-07-05T03:22:09.129Z</atom:updated>
            <content:encoded><![CDATA[<p>Edit 2023–07–05 — Added some non-screenshot code snippets and tidied up the implementation a bit.</p><p>So you’re writing a test for your Angular component, provider, effect, whatever. It has a bunch of dependencies injected into. Now, assume we’re doing shallow testing so we want to quickly stub out these services to just write tests focusing on the implementation of the thing you’re testing. <em>Note:</em> f<em>or now, we’re going to ignore the arguments of </em><a href="https://medium.com/javascript-scene/mocking-is-a-code-smell-944a70c90a6a"><em>whether or not this is actually good practice</em></a><em> here</em>.</p><p>You might start by doing something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*TJXKoiSaL3tvEWKt5Rjvhg.png" /><figcaption>Stubbing out services with plain JavaScript objects</figcaption></figure><p>This works fine but it quickly bloats out your test files with unnecessary stub code. Moreover, you might end up repeating these mocks all over the place.</p><p>A much quicker, easier and more re-usable alternative is to use JavaScript’s <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">proxy object</a>. We can define an arbitrary getter which will return a new jest spy (jest.fn()) and store that for later retrieval (so multiple calls will always call the same stub). It looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*tpgCMzlI_MHAqStbqNbV8w.png" /><figcaption>Service mock factory</figcaption></figure><p>Any method we try to call on an object created from serviceMockFactory() will return a jest.fn() — a different one for each method but always the same one for the same method. This also means we’re free to do all the useful jest mocking goodies like mockImplementation. We can verify the factory with a quick test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*1yIeJtxYDv8PacEdMnpoRQ.png" /><figcaption>Testing our service mock factory</figcaption></figure><p>Now — we can replace all of our quick mocks from the first example with a reference to this service mock factory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bwE20oe6TjVKo16EgxCopg.png" /><figcaption>Using our service mock factory to stub out our services</figcaption></figure><p>We could shorthand this even further to serviceMockForToken = token =&gt; ({ provide: token, useFactory: serviceMockFactory})</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*coYVrG8Hq6kqo5GIZAvm9g.png" /><figcaption>Quickly stubbing out several providers</figcaption></figure><p>We’re left with one small problem though: we’re only stubbing methods. What if we want to access a property on the service? This can be fixed by adding a setter to our proxy that allows us to override any of the keys with our own value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Dg8kWIj6pQzXYVBjsclobg.png" /><figcaption>Setter for overriding values</figcaption></figure><p>Now, we can override a specific property in any given test:</p><p>TestBed.get(MyService).someProperty = of(&#39;Value has been mocked!&#39;)</p><p>And likewise if we wanted to mock the return value of a method we need only to mockImplementation or mockReturnValue on one of the jest functions.</p><p>If you’re not using this for Angular specifically, it’s probably worth renaming it to something more generic. In this case, I’m using createSpyObject (similar to createSpyObj provided by jasmine )</p><pre>export const createSpyObject = () =&gt; new Proxy(<br>  { proxies: {} },<br>  {<br>    get(target, name) {<br>      target.proxies ??= {};<br>      target.proxies[name] ??= jest.fn();<br>      return target.proxies[name];<br>    },<br>    set(target, key, value) {<br>      target.proxies[key] = value;<br>      return true;<br>    },<br>  }<br>);</pre><p>Or, if you want something type-safe:</p><pre>export type SpyObject&lt;T&gt; = {<br>  [key in keyof T]: jest.SpyInstance;<br>};<br><br>export function createSpyObject&lt;T = any&gt;() {<br>  return new Proxy(<br>    { proxies: {} },<br>    {<br>      get(target, name) {<br>        target.proxies ??= {};<br>        target.proxies[name] ??= jest.fn();<br>        return target.proxies[name];<br>      },<br>      set(target, key, value) {<br>        target.proxies[key] = value;<br>        return true;<br>      },<br>    }<br>  ) as SpyObject&lt;T&gt;;<br>}</pre><p>Done — simple mocking for any service. What’s better — we can re-use this util all over our application’s tests. Easy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=975c69a83809" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/proxy-objects-for-quick-and-dirty-service-mocks-in-jest-975c69a83809">Proxy Objects for Quick and Dirty Service Mocks in Jest</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Component Providers and why they might be underused]]></title>
            <link>https://medium.com/nextfaze/angular-component-providers-and-why-they-might-be-underused-592f16adbe26?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/592f16adbe26</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular2]]></category>
            <dc:creator><![CDATA[Zak Barbuto]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 00:01:00 GMT</pubDate>
            <atom:updated>2019-08-01T00:04:56.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Component Providers — an alternative for event bubbling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*zL21b05fyYLcF5Iq" /><figcaption>“Component-level providers: A novel approach to bubbling events” was a bit too cliché for my tastes</figcaption></figure><p><em>This post is sort of a response to an article I read this morning on </em><a href="https://blog.angular-university.io/"><em>Angular University</em></a><em> discussing </em><a href="https://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why"><em>Smart Components vs Presentational Components</em></a><em>. It’s a great article as an intro to “smart” vs “presentation” (or “dumb”) components and a part of a great series I recommend reading.</em></p><p>The article above discusses possible workarounds for “bubbling” events in deeply nested “presentation” components back up to a “smart” component. It proposes two solutions:</p><ol><li>Make a lower-level component “smart”; or</li><li>Wrap the presentation component in a custom “smart” component.</li></ol><p>Both of these are perfectly reasonable workarounds — but I’d like to propose a third: component-level providers.</p><p>This hinges on a particular phrasing used in the above article relating to smart components:</p><blockquote>This (smart) type of component is inherently tied to the application itself, so as we can see it receives in the constructor some dependencies that are application-specific, like the LessonsService.</blockquote><p>Note: <em>dependencies that are application-specific</em>. Not that a presentation component <strong>can’t</strong> have dependencies — just that it can’t have application specific dependencies.</p><h4>The problem quickly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*0qaJGJLaxiCrChj0Sej3qQ.png" /><figcaption>The sort of component hierarchy we’re talking about</figcaption></figure><p><em>Note: The example above is a contrived example of what we’re talking about. For the time being, let’s ignore that this app could probably be done in many different ways and hitting problems like this might be a hint at poor application architecture.</em></p><p>Imagine our app has an API service injected into it. Our “Smart Component” wants to know when that delete button at the bottom of the tree (“Button Component” above) is clicked so we can tell the API to delete an item. What we definitely <strong>don’t </strong>want to do here is wire up @Output() events the whole way up the chain just so we can listen for button clicks at the bottom.</p><h4>Component Level Providers</h4><p>Before we talk about the solution, it’s worth having a TL;DR rundown of the way Angular’s <a href="https://angular.io/guide/hierarchical-dependency-injection#injector-bubbling">injector bubbling</a> works. In short: to find a dependency for something, Angular first looks at that element’s Injector. If it doesn’t find it, it goes to the element’s parent injector. It continues this way “bubbling” up the tree until it hits the “root injector”.</p><p>In very simple applications, you’ll typically only provide things at the root level — the ApplicationModule. However, besides providing at the Module level, you can also provide things at the component level. The series of articles mentioned in the introduction actually talks about this in one of the <a href="https://blog.angular-university.io/angular-2-redux-ngrx-rxjs/">later chapters</a> as a way of providing local service state. If you’ve ever implemented a custom FormControl component using <a href="https://angular.io/api/forms/ControlValueAccessor">ControlValueAccessor</a> you’ve probably done something like this:</p><pre><br>@Component({<br> providers: [{<br>   provide: NG_VALUE_ACCESSOR,<br>   useExisting: MyComponent,<br>   multi: true<br> }]<br>})</pre><p>If you provide a dependency at your component level — any child components who inject that dependency get the one provided by your component.</p><h4>How is this useful for the problem?</h4><p>Let’s think about it — our button component just needs something to pump events into. It doesn’t necessarily need to be an @Output. Well, we can make one of those as an abstract class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*zo19UjMo6SW8tDAuFQlm-A.png" /><figcaption>Our custom button event handler which will be injected</figcaption></figure><p><em>Note, this doesn’t have to be a class. You could use any old </em><em>InjectionToken to provide, for example, an EventEmitter instance to the button. I’m using a class because it hopefully makes it more clear how the DI is working.</em></p><p>Right, so we’ve got a dependency for our button. Note, it’s <strong>not an application specific dependency</strong>. There’s nothing about a ClientList or a DeleteClientAction or event an NgRx Store. It’s a ‘dumb dependency’ if you will. The button component does not care what it does or where it comes from — just that it’s there. In fact, if you make it @Optional it doesn’t even <em>need</em> to be there.</p><p>Next, we inject the handler our button component, and start sending click events to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*90wuDB25kY_7_JWVpLdy-A.png" /><figcaption>Injecting our custom button handler into our button presentation component</figcaption></figure><p>Great. But now if we use this custom button element in our app we get everyone’s favourite Angular error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*kBEZX4sokrKGNfmlwSzm6g.png" /><figcaption>Uh-oh. This looks bad.</figcaption></figure><p>So this is usually the point where you jump to your AppModule and add a service to the providers array there, right? Except here we’re going to head into the AppComponent (or smart component of choice) instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*Hd5icVzE9Pows77BGmrUxg.png" /><figcaption>Providing our button handler at the component level. We could provide an <em>EventEmitter here instead.</em></figcaption></figure><p>So we’re now providing the CustomButtonEventHandler on our AppComponent. And what are we providing? The AppComponent itself via the useExisting property. Our AppComponent is implementing the CustomButtonEventHandler that the button component expects. What this means is that any custom-button elements that are children of AppComponent — and are not descendants of other components that provide a CustomButtonEventHandler — will get a reference to the app component to notify when the button is pressed.</p><p>So that custom button can be 30 ‘presentation’ components down (please don’t do this) and we can still get events from it easily at our “smart” component level. Neat.</p><h4>Drawbacks</h4><p>Depending on how you look at things — you might see this as coupling your components together. The parent component needs to know that somewhere in its component tree there is a button that requires this CustomButtonEventHandler. If it’s not a direct child — it may mean coupling to the implementation of any number of child components.</p><p>There’s a couple of counters to this. First, we’re assuming the parent in this case is a smart component — so having some degree of knowledge about its children and their makeup is probably acceptable. Second, the button handler need not be associated directly with the specific custom button. We could have a generic button handler token for our whole application — used by any number of buttons. Using this pattern, all the parent component is saying is “if a button gets clicked — I want to know about it” rather than “listen for clicks on any specific CustomButtonComponents”.</p><h4>Final Thoughts</h4><p>Providing at the component level is there for a reason — to be useful. Yet, I so rarely see it actually used in applications. I think it affords some interesting tricks to avoid making “man-in-the-middle” presentation components more complex than they have to be (like having Outputs just for the sake of bubbling, or being smart components just for the sake of handling events).</p><p>This isn’t to say it’s a pattern you should use extensively throughout your apps. Just another tool at your disposal the next time you need a solution to the above sort of problem.</p><p>Check the <a href="https://stackblitz.com/edit/angular-kgsczr">StackBlitz</a> for a working example.</p><p>Hopefully you’ve found this information useful. Have a safe and wonderful rest of your day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=592f16adbe26" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/angular-component-providers-and-why-they-might-be-underused-592f16adbe26">Angular Component Providers and why they might be underused</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Template Outlets as a Workaround for Component Placement Restrictions]]></title>
            <link>https://medium.com/nextfaze/angular-template-outlets-as-a-workaround-for-component-placement-restrictions-31ee584b085c?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/31ee584b085c</guid>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ionic4]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[Zak Barbuto]]></dc:creator>
            <pubDate>Thu, 25 Jul 2019 07:44:31 GMT</pubDate>
            <atom:updated>2019-07-25T09:41:40.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAsTx5EWlqbAmAfuwT4b_Q.png" /><figcaption>The best code is like a desert — <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>… Look, it works, okay, give me some credit. Image credit: Keith Hardy on <a href="https://unsplash.com/photos/PP8Escz15d8">Unsplash</a>.</figcaption></figure><blockquote>TL;DR Check the <a href="https://stackblitz.com/edit/angular-zp5xzg">StackBlitz</a> at the bottom.</blockquote><p>Some Angular libraries may have restrictions on component placement. <a href="https://ionicframework.com/docs">Ionic</a> is one of them. Certain Ionic components, such as ion-fab need to be direct descendants of ion-content to work. <a href="https://github.com/ionic-team/ionic/issues/12252">Despite</a> <a href="https://github.com/ionic-team/ionic/issues/9288">several</a> <a href="https://github.com/ionic-team/ionic/issues/9279">issues</a> in the past (dating back to 2016) and <a href="https://github.com/ionic-team/ionic/issues/12252#issuecomment-317062521">claims that it was fixed in the latest version</a> it still appears to be an issue at the time of writing (Ionic version 4.6). It’s clearly some sort of technical limitation in getting the fab to render fixed against the scrolling content.</p><p>Ionic is not the only library with these sorts of restrictions — I’ve experienced similar issues in the past with other Angular component libraries. So, Idecided to come up with a workaround.</p><h4>The Problem</h4><p>I’m sure there are several reasons for these sorts of restrictions in an Angular libraries — that is, requiring a specific DOM hierarchy for that component to work. However, there are also many reasons to want to wrap one of those third-party components in your own component. You might want some consistent features or styling for that component across pages. Maybe you want some consistent analytics on a button — or added functionality. Or maybe you want the same fab group — with the same 4 social media options (an <a href="https://ionicframework.com/docs/api/fab">example from the Ionic documentation</a>) — across a dozen pages in your app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bd54656025b0a8baecbf7051e92db09/href">https://medium.com/media/4bd54656025b0a8baecbf7051e92db09/href</a></iframe><p>It looks something like this when expanded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*NnJs3rtSAq95gA8CzVgsgg.png" /><figcaption>Fab example from the Ionic docs</figcaption></figure><p>You don’t want to copy-paste that block of code across every single page. It makes your page templates brittle and doesn’t follow good <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> coding practices. In general, testable and re-usable components are a <strong>Good Thing™</strong>.</p><p>So what can we do? Are we stuck?</p><p>No. There is a workaround. Depending on your views on TemplateRef usage, you might view it as a bit of a “hack”. In my view, though, sometimes the hack is way better than the alternative.</p><p>First, let’s look at our page component. We use some nice re-usable components to keep everything tidy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d194dc8c8df0518d9ddd4ba102fc81cc/href">https://medium.com/media/d194dc8c8df0518d9ddd4ba102fc81cc/href</a></iframe><p>But, as we’ve established, the FAB won’t work properly. If it’s not the direct descendant of ion-content — which it’s not since it’s a child of my-reusable-fab— it won’t be properly fixed on the page (it will not scroll with the content). What we really want is for Angular to render the contents of my-reusable-fab in place without it actually being a child of my-reusable-fab.</p><h4>A Solution</h4><p>Note <strong>a </strong>solution — not <strong>the</strong> solution. What we can do is use &lt;ng-template&gt;s in conjunction with ngTemplateOutlet directive. If you’re not familiar with Angular <a href="https://angular.io/guide/structural-directives">structural directives</a> and template usage it’s worth reading up on as it provides some of the most powerful functionality in Angular. The updated components are going to look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3be639f06ac1ff31950af546250c5f90/href">https://medium.com/media/3be639f06ac1ff31950af546250c5f90/href</a></iframe><p>Okay — so there’s a few things going on here. In the fab component — we declare a template and assign it to the#templateContent variable. The setter in the component class reads in that variable as a ViewChild and the emits it to our templateOutput EventEmitter . The page component then basically passes those template emissions through to the template outlet. Because ng-template is not actually rendered in the DOM, the result is that the contents of our reusable fab is places as a direct descendant of our ion-content .</p><p>Voilà — we have a reusable fab.</p><p>Ok, so maybe it’s not the most <em>elegant </em>solution — but it’s a pattern that could save you a bit of bother if — four example — your client decides they want to add their Pinterest link to the fab group which is on every page in the app. It might be overkill if your app only has a couple of pages — but in a very large app this it is going to save you a bunch of time and heartache. It also means we only need to write unit tests for the FAB, and wire up any analytics or additional actions, once. Great.</p><p><a href="https://stackblitz.com/edit/angular-zp5xzg">Here’s a stackblitz</a> demonstrating some actual working code if that’s your thing.</p><p>If you’ve got some alternate solutions feel free to drop a comment and I’ll add them to the list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31ee584b085c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/angular-template-outlets-as-a-workaround-for-component-placement-restrictions-31ee584b085c">Angular Template Outlets as a Workaround for Component Placement Restrictions</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing and Debugging on Android with DevFun]]></title>
            <link>https://medium.com/nextfaze/developing-and-debugging-on-android-with-devfun-a5a9396d47ab?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5a9396d47ab</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[annotations]]></category>
            <dc:creator><![CDATA[Alex Waters]]></dc:creator>
            <pubDate>Thu, 20 Dec 2018 01:22:40 GMT</pubDate>
            <atom:updated>2018-12-20T01:22:40.193Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/NextFaze/dev-fun">DevFun</a> is an annotation based library aimed at Android developers to facilitate the separation, isolation, and invocation of developer and debug related code. It does this via annotation processing and Java’s service loader mechanism.</p><p><em>For those of you in the Angular world by sure to check out our sister library </em><a href="https://medium.com/nextfaze/devmod-probing-your-angular-application-for-fun-and-debugging-d7e07c688247"><em>DevMod</em></a><em>.</em></p><figure><img alt="The main DevFun developer interface" src="https://cdn-images-1.medium.com/proxy/1*P3THKKnVrGJWeU2tB9dV-w.png" /><figcaption>The main DevFun developer interface</figcaption></figure><p>Some of the things DevFun can do:</p><ul><li>Invoke functions in your app at any time from anywhere</li><li>Invoke functions with values entered at run-time</li><li>Provide a handy debug interface by only adding a dependency</li><li>AND SO MUCH MORE</li></ul><p>This article gives an overview of some of the traps and pitfalls found with common debugging techniques, and how DevFun helps you avoid them. This is followed by discussing how DevFun leverages code generation and service loaders to isolate itself from your business logic, leaving you with clean and “untainted” code.</p><p>The animation below shows DevFun in action. Other than adding the dependencies, the annotations shown is all that is used to generate the demonstrated behaviour.</p><figure><img alt="All this with just some dependencies and annotations!" src="https://cdn-images-1.medium.com/proxy/1*IxrKhpPvxG5JsRDtWQyn-g.gif" /><figcaption>DevFun is design to have a minimal footprint on your non-debug code, typically requiring nothing more than a function annotation. The floating cog and debug menu are provided by the devfun-menu module</figcaption></figure><h3>Debug Code — Traps and Pitfalls</h3><p>Before my leap into Java/Kotlin and Android, I came from the world of hobbyist C++, C#, and Visual Studio — I lived in a naive world where everything lived in one place, far too many things were public/static, and testing was… What I was “already doing” while I was writing it…? And I think it’s safe to assume that the beginnings of many developers were somewhat similar. Let’s have a look at some of these naive approaches to debugging, and their downsides.</p><h4>Inline Test Code</h4><p>So you’ve added some new feature, but it’s misbehaving — you should be unit testing but you don’t know how to do that yet or you are already pushing some deadline. So instead you just temporarily force the value to something, run, debug, and step through the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e3d1a5c0644c160a87be583bd9e13e0/href">https://medium.com/media/4e3d1a5c0644c160a87be583bd9e13e0/href</a></iframe><p>But of course you forgot to remove your debug code, so the next day you’re going insane trying to figure out why your @mention isn’t working anymore. Or worse yet, you’d accidentally committed it to the humiliation of your collaborators.</p><p>Your shameful late-night mistake:</p><pre><em>Fix parsing of hash tags Alex Waters 2018-10-23 02:59 AM<br>Remove debug code Mike Collaborator 2018-10-23 09:01 AM</em></pre><h4>The DEBUG Flag</h4><p>The life of a developer can be surmised as; write code, run, test, repeat until working. However when your current task sits behind a login screen, we very quickly become sick of entering the test credentials. Thankfully we are a little more seasoned now, and the process of adding debug code is a little more elaborate. We now leverage the power of the debug flag!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2f470e33c4b3bfb6bc0f86f0d3956fc/href">https://medium.com/media/f2f470e33c4b3bfb6bc0f86f0d3956fc/href</a></iframe><p>Except now every time you want to log in as someone else you need to change the code. You also probably can’t commit this when working with others as they’ll potentially have their own test credentials. And oh dear — some smart-ass decided to decompile your app and now has access to your (hopefully not admin) test account.</p><h4>Dependency Injection</h4><p>With more experience comes better methodologies, techniques, and tooling, with the big ones typically being dependency injection and debug source trees. An old favourite was <a href="https://github.com/google/guice">Guice</a>, where adding debug-only overrides was relatively trivial. But these days it’s all compile-time code-gen with <a href="https://github.com/google/dagger">Dagger</a>, which unfortunately does not lend itself to just quickly and easily overriding something — a simplicity lost for compile-time safety and run-time efficiency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d12b7d8828c50a9634de394f0912c68d/href">https://medium.com/media/d12b7d8828c50a9634de394f0912c68d/href</a></iframe><p>This is a little bit better — at least now you haven’t got your test credentials in your release builds, and issues with sharing and committing might not be a problem now since you can just not commit that one changed file (and/or untrack it or whatever).</p><p>However this approach is not without its issues and frustrations:</p><ul><li>You are still polluting your business logic and adding unnecessary complexity to your login flow — simply for development and debugging purposes.</li><li>It requires that you create build-type specific implementations — which can be a real nightmare if you have more than just the standard debug/release variants.</li><li>If you need to change its structure you’ll need to adjust it for all your build types potentially breaking collaborator builds in the process (since you’re changing an untracked file or what have you).</li><li>It requires you to be constantly aware of the login default’s state — adjusting and rebuilding as you switch features, or when you need to test another user, etc.</li></ul><h3>Enter: DevFun</h3><p>DevFun was created to make development and debugging simpler; to remove the need for those “one time” debug code snippets, to provide future developers (frequently yourself) access to your handy debug functions, and to just simply make life easier — all the while keeping your production code clean and explicit.</p><p>And the best part is, it does this with only annotations — so it doesn’t matter if you forgot to remove your debug snippets later as your business logic is never touched!</p><p><em>Of note is that all function annotations are </em><em>SOURCE retained — this means that your compiled code will not contain </em><strong><em>any</em></strong><em> references to them. Throw in some ProGuard and your unreferenced debug functions can be stripped out entirely.</em></p><h4>Fun with Annotation Processing</h4><p>For those unfamiliar with annotation processing — it is a step in the compile process that allows code to be generated during the <a href="http://openjdk.java.net/groups/compiler/doc/compilation-overview/index.html">compile phase</a>.</p><p>DevFun leverages annotation processing by “tagging” functions of interest. A reference is generated at compile time that describes where the function is, how to invoke it, and records any other information as described by the annotation.</p><p>Our previous examples using DevFun:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f6a8506f307c28c02935533d1a0862b/href">https://medium.com/media/9f6a8506f307c28c02935533d1a0862b/href</a></iframe><p>Which DevFun turns into:</p><figure><img alt="Fun with debug functions" src="https://cdn-images-1.medium.com/proxy/1*HLiRy6ze51HDd-MF3jSiZg.gif" /><figcaption>Fun with debug functions</figcaption></figure><p>A couple of things to note:</p><ul><li>The login options are only available on the login screen. DevFun tries its best to be “context aware” — in that fragment and activity related items should only be available when they can be used.</li><li>The handleWord function takes a String as a parameter. When DevFun can’t inject a type (more on that later), it prompts for manual entry for types it understands (which by default includes primitives, strings, and enums).</li><li>DevFun will put annotated items into a “category” based on the class name MyClass &gt; “My Class” with the name based on the function’s name in the same manner. These can be renamed, grouped, or sorted using optional annotation fields or with other optional annotations and are completely arbitrary.</li></ul><h4>Leveraging the Service Loader</h4><p>To further isolate your production sources from your debug code, DevFun leverages Java’s service loader mechanism — the generated code is an implementation of DevFunGenerated. This means your code never needs to know about it or tell DevFun where it is or how to load it.</p><p>For those unaware, a “service” is an implementation of some interface. The fully qualified name of the implementation is a line in a “services file” (plain-text) in the jar/aar META-INF/services/com.my.service.InterfaceName (or use <a href="https://github.com/google/auto/tree/master/service">AutoService</a> to create it for you). These implementations can then be found by the service loader at run-time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b814c732748a6d2bbd0c011289d30d8/href">https://medium.com/media/8b814c732748a6d2bbd0c011289d30d8/href</a></iframe><p>Another benefit to using the service loader is that it becomes trivial to allow libraries to provide generic and frequently used utility functions — an example of this is the devfun-util-glide library, which provides functions to view and clear <a href="https://github.com/bumptech/glide">Glide’s</a> image caches.</p><figure><img alt="Utility functions can be provided by libraries" src="https://cdn-images-1.medium.com/proxy/1*AnMeCIjOSls83HWuRBcQww.png" /><figcaption>Utility functions can be provided by libraries by simply adding a dependency</figcaption></figure><p>The library itself is an object with @DeveloperFunction annotated functions. Arguments to functions are injected automatically at run-time (more on that next).</p><p>The service loader is also used for “modules” DevFunModule. These extend the functionality of DevFun and are loaded and initialised alongside it (which itself is initialised automatically on app start using a ContentProvider). They aren’t required for simple utility libraries like the above, but can be used for example, to spin up a local HTTP server providing a means of invoking functions from the browser (devfun-httpd and devfun-httpd-frontend) — these are quite experimental and mostly proofs of concept. In the future it might be fun to experiment with a kotlin-react app or something (not going to lie — it’s pretty gross what’s there at the moment).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EK1qy9Q_Fsa_G6Lue-z8Rg.png" /><figcaption>Web front-end provided by a DevFun module allows the invocation of functions from your desktop</figcaption></figure><h4>Function Invocation and Dependency Injection</h4><p>Most modern development practices involve some sort of dependency injection. In this article we’re assuming you’re using Dagger 2.x (natively supported by DevFun) — though support for other frameworks wouldn’t be much of an problem.</p><p>One of the many issues surrounding traditional debug &amp; developer code, is that it requires you to modify your production code — if only to reference a NOP implementation — to incorporate these developer-only enhancements. Though potentially trivial changes, it still adds unnecessary noise and is just “not fun” to look back over it in the future. Not to mention future developers that encounter it; “What’s this LoginDefaults — maybe that’s causing bug #123 by giving the wrong values… Oh, it’s just for developers… Well that was a waste of time.”</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99100f674b20c0902bb7f6ddad84cd38/href">https://medium.com/media/99100f674b20c0902bb7f6ddad84cd38/href</a></iframe><p>DevFun itself does not use nor require the use of Dagger. Instead it uses a simple InstanceProvider system (left). At the time this was because (among other reasons) the underlying code generated by Dagger would fail if the consumer used a different version (though these days it’s pretty stable).</p><p>At compile-time DevFun records what it needs to know in order to invoke a function; upon what (the “receiver”), the function to be invoked, and its parameter types. When invoking, it loops through its providers checking the most recently added first. This system makes it trivial to support other DI frameworks — for example, the module devfun-inject-dagger2 adds an instance provider that traverses your Dagger graph.</p><p>The dynamic nature of the instance provider system means that as long as a type is provided by Dagger or whatever, then you can effectively create and annotate any function without giving it much thought.</p><p>If you happen to be using Dagger 1.x, Guice, or some other DI framework, feel free to submit an issue or submit a PR with support.</p><h4>Source-sets, Source-retention, and Modularity</h4><p>Though you could leave your “main” source tree pristine and only have debug code in your debug tree, it’s quite common for objects to have some function that you just wish you could call; something to reset its state, or something to log some data, or something that triggers a bunch of logic that’s just a bit of a PITA to trigger by normal means.</p><p>Unfortunately there’s no way to avoid <em>some</em> debug-ish code in your main sources to reference these elusive functions — but we can minimise the impact. The devfun-annotations module contains only annotations, interface definitions, and some inline utility functions (i.e. minimal method count). Additionally all function annotations are SOURCE retained, so their contents and presence are completely absent from your byte code.</p><p>Furthermore, since DevFun’s functionality is provided via service-loader modules, the rest of it can exist solely in your debug class-path, and does not require you to reference it at all from your any of your sources. Some of the modules provided by DevFun:</p><ul><li>A “menu” module devfun-menu provides a floating debug-cog and hotkeys (` or down-down-up-down on your volume buttons) that shows a menu of functions for invocation.</li><li>A DI module devfun-inject-dagger2 for Dagger 2.x allows DevFun to use your components for instance resolution and injection.</li><li>Modules are available for <a href="https://github.com/square/leakcanary">LeakCanary</a> devfun-util-leakcanary and <a href="https://github.com/bumptech/glide">Glide</a> devfun-util-glide that provide some utility functions (show leak activity, show and clear Glide image caches etc).</li><li>Experimental modules provide a built-in web server devfun-httpd (<a href="https://github.com/NanoHttpd/nanohttpd">NanoHTTPD</a>) and a front-end devfun-httpd-frontend (<a href="https://getbootstrap.com/">bootstrap</a>) allowing for remote invocation of functions from a browser.</li><li>And an experimental module devfun-stetho allows calling functions from Chrome’s JS console via <a href="http://facebook.github.io/stetho/">Stetho</a>.</li></ul><p><em>Disclaimer: the experimental modules are mostly proofs of concept and are not as stable or feature complete as the menu. Also, their code is… Of questionable quality. But they do generally work and are kind of fun if only for the novelty.</em></p><h3>Designed by developers, for developers</h3><p>DevFun was design with developing and developers in mind, it’s intended to “just work” with minimal effort (auto-loading &amp; initialisation and built-in Dagger 2.x DI support etc). The majority of its features and functionality are intended to be customised with most options leveraging Kotlin’s default values. Furthermore, a majority of its API uses interfaces, which in combination with its instance provider system, allows for easily providing your own implementations over the standard ones, and even intercepting core functionality on the fly.</p><p>So if at any point you find something annoying, or you want the means to change or configure something, feel free to create an issue or submit a PR — more than likely it’ll be accepted. DevFun is meant for development, not as some critical component to your app’s functionality. i.e. if it breaks or crashes it really doesn’t matter because it just for us developers! (though obviously efforts are made to avoid that and to provide decent backwards compatibility — but you get the point).</p><p>Thanks for reading!</p><p>Some quick links and extra information:</p><ul><li>For installation and usage see the README over at the <a href="https://github.com/NextFaze/dev-fun">GitHub repository</a></li><li>For a higher-level overview see the “<a href="https://nextfaze.github.io/dev-fun/wiki/">wiki</a>” (should rename that)</li><li>For extensive documentation see the Dokka generated <a href="https://nextfaze.github.io/dev-fun/">GitHub pages</a></li><li>For some awesome app development needs see <a href="https://nextfaze.com/">NextFaze</a> (shameless plug)</li><li>And again for those in the Angular world go check out <a href="https://medium.com/nextfaze/devmod-probing-your-angular-application-for-fun-and-debugging-d7e07c688247">DevMod</a></li></ul><p><em>Originally published at </em><a href="https://nextfaze.com/blog/developing-and-debugging-on-android-with-devfun/"><em>www.nextfaze.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5a9396d47ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/developing-and-debugging-on-android-with-devfun-a5a9396d47ab">Developing and Debugging on Android with DevFun</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remote Redux Debugging in Flutter]]></title>
            <link>https://medium.com/nextfaze/remote-redux-debugging-in-flutter-bf07343c0101?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/bf07343c0101</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[remote-devtools]]></category>
            <dc:creator><![CDATA[Michael Marner]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 13:09:55 GMT</pubDate>
            <atom:updated>2018-10-09T13:13:27.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Connect your Flutter app’s Redux Store to the Redux Devtools from the web!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bz-J49-_eBJWTVg2.jpg" /></figure><p>I really like Flutter, and I like using Redux when building mobile apps. There’s a great Redux implementation for Dart and Flutter, and a time travel capable debug store.</p><p>The Javascript world is spoilt with the fantastic <a href="http://extension.remotedev.io/">Redux DevTools plugin</a>. It allows you to inspect actions and application state in a web browser, time travel, and playback changes to your app’s state. There is an on screen time travel widget for <a href="https://pub.dartlang.org/packages/flutter_redux_dev_tools">Flutter</a>, but that means sacrificing screen space for the UI.</p><p>So why not combine the Redux DevTools from the Javascript world with Redux.dart? Now you can, with the <a href="https://github.com/MichaelMarner/dart-redux-remote-devtools">redux_remote_devtools</a> package!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B15zJjrIZyOpgnzZ.gif" /><figcaption>Debug your Redux Store with Flutter and Remote DevTools</figcaption></figure><p>This article gives a quick overview of how to get setup. The Git repository contains examples to help get you started.</p><h4>Getting Started</h4><p>Add the library to your app’s pubspec.yaml:</p><pre>dependencies:<br>  redux-remote-devtools: ^0.0.4</pre><p>And add the middleware to your app, and provide it a reference to your store so time travel actions from the remote can be dispatched:</p><pre>var remoteDevtools = RemoteDevToolsMiddleware(&#39;YOUR_HOST_IP:8000&#39;);<br>await remoteDevtools.connect();<br>final store = new DevToolsStore&lt;AppState&gt;(searchReducer,<br>  middleware: [<br>    remoteDevtools,<br>  ]);<br>remoteDevtools.store = store;</pre><p>Startup the remotedev server, and then run your Flutter app:</p><pre>npm install -g remotedev-server<br>remotedev --port 8000</pre><p>You can then browse to http://localhost:8000 and start using Remote DevTools to debug your Flutter app!</p><h4>Encoding Actions and State</h4><p>In the Javascript world, Redux follows a convention that your redux state is a plain Javascript Object, and actions are also Javascript objects that have a type property. The JS Redux Devtools expect this. However, Redux.dart tries to take advantage of the strong typing available in Dart. To make Redux.dart work with the JS devtools, we need to convert actions and state instances to JSON before sending.</p><p>Remember that the primary reason for using devtools is to allow the developer to reason about what the app is doing. Therefore, exact conversion is not strictly necessary — it’s more important for what appears in devtools to be meaningful to the developer.</p><p>To make your actions and state JSON encodable, you have two options. Either add a toJson method to all your classes, or using a package like <a href="https://pub.dartlang.org/packages/json_serializable">json_serializable</a> to generate the serialisation code at build time. The GitHub search example demonstrates both approaches.</p><p>If your store is simple then you may be using enums for actions. These encode just fine without any extra effort.</p><h4>Time Travel</h4><p>If you have configured your app to use the DevToolsStore from redux_devtools, then you can time travel through your app state using the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bRQuttqgcvfmor5.gif" /><figcaption>Time Travel through your app</figcaption></figure><p>Remember that there are limitations to time travel, especially if you are using epics or other asynchronous processing with your Redux store.</p><p>Being a new library there are still things to work out. PRs are welcome if you’re up for helping out.</p><p>Now go build something cool with Flutter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf07343c0101" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/remote-redux-debugging-in-flutter-bf07343c0101">Remote Redux Debugging in Flutter</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding Leaks in Xcode]]></title>
            <link>https://medium.com/nextfaze/finding-leaks-in-xcode-b8bc1919b112?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/b8bc1919b112</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Ricardo Santos]]></dc:creator>
            <pubDate>Fri, 10 Aug 2018 02:31:16 GMT</pubDate>
            <atom:updated>2018-08-22T00:40:38.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPryEmrq5HNyXw71vyBaCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@daanmooij">Daan Mooij</a> on <a href="https://unsplash.com/photos/91LGCVN5SAI">Unsplash</a></figcaption></figure><p>Swift and Objective C both use <a href="https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html">Automatic Reference Counting</a> (ARC) to keep track of when an object is required to persist in memory, and when it can safely be released.</p><p>Memory leaks are when an object is created and kept in memory, but is no longer owned by anything and never able to be released. Often this is a cyclic dependency where object A owns object B, and B owns object A. They will both persist in memory as they are required by each other, but nothing else. By ‘owns’, we mean ‘holds a strong reference to’.</p><p>Leaks are commonly seen in the delegate pattern. Delegate references should always be declared as weak, as a weak reference will allow the runtime to free up the memory. Thinking in a parent/child relationship, the parent should have a strong reference to the child, but the child should have a weak reference to it’s parent. In Swift, references are strong by default.</p><p>Another common place for leaks are within closures. Any variables, including self, used within a closure will be strongly captured to ensure they still exist when the closure executes. To avoid a retain cycle here, use a capture list to tell the closure to keep a weak reference.</p><p>Note that this need not apply to all closures, just those that are @escaping, which means they will be stored to be executed later. John Sundell has an excellent post on this called <a href="https://www.swiftbysundell.com/posts/capturing-objects-in-swift-closures">Capturing objects in Swift closures</a>.</p><p>Eg:</p><pre>object.run { res -&gt; Void in<br>  self.result = res <br>}</pre><p>Will leak self.</p><p>Fix this with weak or unowned as appropriate in a capture list:</p><pre>object.run { [weak self] res -&gt; Void in<br>  self?.result = res <br>}</pre><h3>Debugging Using Console Logs</h3><p>This somewhat rudimentary method involves logging. Start by placing a print statement in the init method of the class you are checking. I like to use emoji to make it easy to see in the console.</p><pre>init() { <br>  print(&quot;✅ init my class&quot;) ... <br>}</pre><p>And place another print statement in the deinit method.</p><pre>deinit {<br>  print(&quot;❌ deinit my class&quot;) <br>}</pre><p>Now run the app, and use the feature that allocates the class, then finish it so the class is deallocated (eg present a view controller, then dismiss it). You should see a balanced number of logs, eg one deinit for each init. If you don’t see the deinit log then your object is probably being leaked.</p><p>Instead of logs you could use breakpoints, and for bonus points <a href="https://twitter.com/0xced/status/900692839557992449">play a ‘pop’ sound</a> when deallocation occurs.</p><h3>Debugging Using the Memory Graph Tool</h3><p>This is a runtime tool available in Xcode when you are debugging in the simulator. To start with, edit your scheme and enable Malloc Stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/0*wsBAUd9wHprJKMaW.png" /></figure><p>Next, run your project, and exercise the app to generate leaks. For example, if you suspect a certain view controller is leaking, present/push and dismiss/pop that view controller a bunch of times. Then launch the Memory Graph Tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*gQfhKQU6-9TjcGGO.png" /></figure><p>If you have a leak, it may or may not be highlighted automatically with a purple bang, so treat this as a clue only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*24uYUYyp_Qn9Wxz4.png" /></figure><p>In the screenshot above we can see that TimeEntryViewController has (4) next to it, indicating that there are 4 instances floating in memory. Select one to see the chain of ownership leading to the cycle. If you are really lucky, like we are above, you will even get a useful stacktrace that when clicked will navigate directly to the line of code that captures the object.</p><h3>Debugging Using Instruments</h3><p>Xcode also provides an instrument tool for detecting leaks, which is a handy tool to have on the belt.</p><p>If you want to have a play, run Xcode -&gt; Product -&gt; Profile to start Instruments, then select the Leaks template. Once it loads, press the Record button to start the app in the simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*UBpFm84gTzLxQrqs.png" /></figure><p>As the app is running, use it and observe the Leak Checks row, it will be marked with a red cross when a leak is detected. Click on it to see the Stack Trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ApDPylJ4ddxTs4Rh.png" /></figure><h3>Conclusion</h3><p>As modern devices have significantly more RAM than the first iPhones, apps crashing due to excessive memory consumption is a rarer thing. Nonetheless, it’s always worthy of avoiding leaks, as they can often lead to other issues or bugs at runtime.</p><p>Hopefully this post will help you to plug up a few leaks in your app.</p><p><em>Originally published at </em><a href="https://nextfaze.com/blog/finding-leaks-in-xcode/"><em>www.nextfaze.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8bc1919b112" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/finding-leaks-in-xcode-b8bc1919b112">Finding Leaks in Xcode</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevMod — Probing your Angular application for fun and debugging]]></title>
            <link>https://medium.com/nextfaze/devmod-probing-your-angular-application-for-fun-and-debugging-d7e07c688247?source=rss----980139edfe2---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7e07c688247</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Zak Barbuto]]></dc:creator>
            <pubDate>Mon, 28 May 2018 01:25:10 GMT</pubDate>
            <atom:updated>2018-12-20T23:52:58.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*WkmVJjAEYRIWRGL4ajhU6Q.png" /><figcaption>DevMod’s developer interface</figcaption></figure><p>Today, NextFaze is releasing our new Angular debugging tool <a href="https://github.com/NextFaze/devmod">DevMod</a> to npm. It’s a debugging and developer module that gives a floating button which summons a special developer interface. At the moment, this interface allows you to:</p><ul><li>Call functions on components in the DOM,</li><li>Track the recent emissions of observables and</li><li>Throw an error to check your application’s error handling</li></ul><p>We’ve been using it internally for a while and we loved it so much we just had to open source it for the community.</p><p>DevMod’s core functionality — the @DeveloperFunction decorator — is based on a similar NextFaze debugging tool published for Android apps: <a href="https://github.com/NextFaze/dev-fun">DevFun</a>. If you’re interested there’s also an <a href="https://medium.com/nextfaze/developing-and-debugging-on-android-with-devfun-a5a9396d47ab">in-depth blog post on how that works</a>.</p><p>We use tools like <a href="https://augury.angular.io/">Augury</a> a lot for debugging — which we love — but the idea of being able to call any component method from a special interface really tickled us. The use cases cropped up all the time for things like automatically filling in forms with valid data to test core user flows or magically logging in as a particular user type during development.</p><p>In this post, I wanted to go into detail on how the tool is built and the various debugging tools that Angular gives you out of the box, including ng.probe, that make it possible for debugging tools like DevMod and Augury to analyse your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*51GPdzcrBrhMH-gnjGsKcw.jpeg" /><figcaption>“I heard you had something that needed probing…” — Thanks to <a href="https://pixabay.com/en/mystery-outdoors-spooky-fantasy-3272046/">pixabay</a> for the image.</figcaption></figure><h4>Development Mode vs Production Mode</h4><p>We’ve all seen the little warning that Angular gives you in the console when running in development mode. It tells you to call enableProdMode() before deploying the app in production. So what exactly does calling this function do? Or, more importantly, what happens when it’s not called?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*c8dk4GwYcKKZVlesDA0_ow.png" /><figcaption>Angular’s development mode warning</figcaption></figure><p>Running in development mode actually does a few things under the hood. It is what gives you more verbose stack traces and adds lot of the Angular specific properties to the DOM to aid in debugging. However, what we’re interested in are two globally available variables that are also exposed in development mode: the getAllAngularRootElements function, and the ng object.</p><p>The getAllAngularRootElements function does pretty much what it says on the tin. You call it and it returns an array of all Angular app root elements on the page. Typically this just contains one element — your own app’s root.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwDJJohVKmiMqEwrhEwAag.png" /><figcaption>The output of `getAllAngularRootElements()` in a default Angular CLI app running in development mode.</figcaption></figure><p>The ng object is slightly more interesting. It contains two properties: an object called coreTokens — which contains three injection tokens we can use: ApplicationRef, NgZone and Router — and a probe function. The probe function can be passed any DOM element on the page and it will return a DebugElement instance wrapping the particular node. If you’ve done any Karma testing you’ll be somewhat familiar with DebugElements. They contain the nativeElement instance as well as some other Angular debugging goodies. In the case of a component element, it also contains a reference to the componentInstance.</p><p>You can try poking around your application yourself. Chrome provides a $0 variable containing the currently selected node in the element explorer, so you can select a component element in your app and get to the actual component instance using ng.probe($0) to get the DebugElement and ng.probe($0).componentInstance to get the actual Angular component instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6zOsZBJc6i0XC3PmwgvTg.png" /><figcaption>Getting the DashComponent instance from a DOM element using `ng.probe`</figcaption></figure><p>As an aside, it’s actually a neat trick to jump to the actual file that defines your component by probing the element for the component instance and using Chrome’s inspect function (which, when called on a function, jumps to that function’s definition in the respective JavaScript file) to jump to the constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2G2NrBb-fsAlNoI-mo0TMQ.png" /><figcaption>Jumping to the login.component.ts file by probing our &lt;login-component&gt; element and inspecting the constructor.</figcaption></figure><h4>Building up a picture of the app</h4><p>The combination of these two global functions, along with the core injection tokens, are the foundation of how debugging tools like Augury and DevMod analyse your app. If we have the application, we can get to the injector, and if we have the injector, we can pretty much pull anything we want out of the app, including the app module itself, along with all of the decorator information passed into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-6m3CC-bZgrBey_n41VNqg.png" /><figcaption>Expanded versions of the functions used to get to the app module decorators in DevMod. We now have a list of all component declarations, entry components, providers and external module imports available.</figcaption></figure><p>From here, we’re just a recursive function away from building a complete tree of your app, all its module dependencies and all of their components and providers. This is exactly what Augury provides and the way it does it <a href="https://github.com/rangle/augury/blob/master/src/backend/backend.ts">under the hood</a> is similar to the way outlined above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SSWKwq3bflZcCj5nDpHJpQ.png" /><figcaption>Augury showing all imports, providers and declarations in an application, as well as those defined by imported modules.</figcaption></figure><p>Likewise, we can recursively drill down the DOM from the application root component — calling ng.probe on each HTML element we find and filtering for ones that have a componentInstance - to build up a picture of each of the Angular components we find along the way. Again, Augury already does something similar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*haETSacAfwntMQaejeAw-A.png" /><figcaption>Augury’s view of the Angular component tree — built up from inspecting all elements in the dom.</figcaption></figure><p>You can see why it is definitely a good idea to enable production mode on your app before pushing it live to production. Not only can we do some interesting reverse engineering work but XSS could do some pretty malicious things by replacing providers used by the injector in your app.</p><h4>Enter: DevMod</h4><p>At the moment, we’ve got half the story — the debugging functions provided by Angular. What about @DeveloperFunction and the other decorators provided by DevMod? Well, those are actually pretty straight forward decorators with nothing special about them. All they do is set some metadata on your component class (previously using Reflect) about what functions are available for debugging.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3923d5a7ef6403c55a77061091ce5da/href">https://medium.com/media/b3923d5a7ef6403c55a77061091ce5da/href</a></iframe><p>So now we have a full list of all the Angular components in the DOM, we have a list of all your services, and each service or component might have some DEVELOPER_FUNCTION metadata on it, we can make a simple interface to show all the components that have developer functions on them and list each of the developer functions as a button that calls the method on the component instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f6ba9a6449c570f2d039b40afc92ad7/href">https://medium.com/media/4f6ba9a6449c570f2d039b40afc92ad7/href</a></iframe><p>Of course, we dressed up the styles a bit and added a few nifty built-in functions, but this pretty much forms the core functionality of how DevMod does what it does. Ever since, we’ve never had to fill in a form again — and now you don’t either!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vJ6YbODOFsYoJ-CFNRTQw.gif" /><figcaption>DevMod being awesome</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7e07c688247" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nextfaze/devmod-probing-your-angular-application-for-fun-and-debugging-d7e07c688247">DevMod — Probing your Angular application for fun and debugging</a> was originally published in <a href="https://medium.com/nextfaze">NextFaze</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>