<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daz on Medium]]></title>
        <description><![CDATA[Stories by Daz on Medium]]></description>
        <link>https://medium.com/@dazcyril?source=rss-ad8b0a0a140e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*49okl20Pm_jXA6hU1mdzmA.jpeg</url>
            <title>Stories by Daz on Medium</title>
            <link>https://medium.com/@dazcyril?source=rss-ad8b0a0a140e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:34:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dazcyril/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Angular State Management using NgRx but with a Lot Less Boilerplate Code]]></title>
            <link>https://medium.com/@dazcyril/angular-state-management-using-ngrx-but-with-a-lot-less-boilerplate-code-a118317ff420?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a118317ff420</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ngrx]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Thu, 20 Dec 2018 17:42:08 GMT</pubDate>
            <atom:updated>2019-01-03T15:34:23.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3uhJFHdjxdX4RIVtAT7Rg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/QuiM1c65QM4?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Paul Zoetemeijer</a> on <a href="https://unsplash.com/search/photos/printing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>NgRx is great, but the amount of boilerplate can be overwhelming. In this post I show two packages that can help drastically reduce the amount of boilerplate you have to write. Plus, there are other benefits for better type checking, and more efficient immutability.</p><p>NgRx actions, in their most basic form, can just be a simple POJO (plain old JavaScript object) that conforms to the following interface:</p><pre>interface <a href="https://ngrx.io/api/store/Action">Action</a> {<br>  <a href="https://ngrx.io/api/store/Action#type">type</a>: string;<br>}</pre><p>We can benefit from strong typing by using an enum of types, defining Action classes, and a type union to combine the action class types. But, this introduces a lot of extra boilerplate code.</p><p>For the reducer, we have to ensure the state is immutable. We introduce a lot of extra boilerplate code again, to deal with immutability. Either by using the spread ... operator or the popular Immutable.js library.</p><p>There are two open-source projects that can help drastically reduce the amount of boilerplate we need, while still benefiting from strong typing and immutability.</p><ol><li><a href="https://github.com/pelotom/unionize">Unionize</a>: described as “Boilerplate-free functional sum types in TypeScript”. It simplifies the creation of type-safe actions, and has helpers for creating reducers and working with actions.</li><li><a href="https://github.com/mweststrate/immer">Immer</a>: Applies some magic using JavaScript proxies to generate the next immutable state using a draft copy of the current state. This library is surging in popularity because it solves the immutability problem in a unique way that feels like native JavaScript. It simplifies the reducer logic because immutable code can be written using standard mutating JavaScript that everyone is familiar with. For more information on Immer check the <a href="https://hackernoon.com/introducing-immer-immutability-the-easy-way-9d73d8f71cb3">introductory blog post</a> or <a href="https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer">video</a>.</li></ol><p>Both of these packages can be installed from npm:</p><pre>npm install --save immer unionize</pre><p>First let’s see how to apply Immer and Unionize to a very basic example. I’ll use the example of a <a href="https://ngrx.io/guide/store">counter from the NgRx documentation</a>. I’ve updated the code to use Immer and Unionize, you can find it in <a href="https://github.com/darrenmothersele/ngrx-example-immer-unionize">this GitHub repo</a> or launch it on <a href="https://stackblitz.com/github/darrenmothersele/ngrx-example-immer-unionize/tree/master">Stackblitz</a> to see it working.</p><p>This is what the actions look like in the NgRx example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6f08b9f2edecdbf4ebb1c93365a2195/href">https://medium.com/media/b6f08b9f2edecdbf4ebb1c93365a2195/href</a></iframe><p>Now they look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1b0424b5a4f2bb6d93acf4705d985cf/href">https://medium.com/media/e1b0424b5a4f2bb6d93acf4705d985cf/href</a></iframe><p>Unionize does all the hard work, defining everything we need to have strongly typed actions. Because Unionize is a more general TypeScript library, we need to customise it a bit to work with NgRx. The option { tag: &#39;type&#39;} passed in the example above customises the actions to use type as the key. This is what NgRx expects as the key that defines they type of action.</p><p>This first example of Unionize is very basic. It gets more interesting with more complex actions that include payloads.</p><p>In the original NgRx example, the reducer used to look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e41b49dffda25fb2fc6568ce59b9102/href">https://medium.com/media/4e41b49dffda25fb2fc6568ce59b9102/href</a></iframe><p>Now it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d31a0eb7915e5dd554aeccb6651964cd/href">https://medium.com/media/d31a0eb7915e5dd554aeccb6651964cd/href</a></iframe><p>The Actions.match function is created automatically by Unionize and can be used to easily create a reducer. You just provide a map of functions where the keys of the map relate to the appropriate action tags (type). To work with NgRx you also always need to provide the default case, as all actions get passed to all reducers, and you might have multiple reducers in different feature modules. In this case the default option is a noop () =&gt; {} .</p><p>I have combined the match functionality of Unionize with the immutable features of Immer. Usually the functions in the match map would have to return a new state and not mutate the previous state. But, thanks to Immer we can operate on a draft copy of the new state. This can be mutated using standard JavaScript techniques. Immer will take care of generating the new immutable version of the state for us.</p><p>You can see there’s a lot less boilerplate, but it’s not really clear in this basic example that there are many other benefits. Immer is lightweight, performant, and simple. It gives us the performance advantages of structural sharing that are even more evident when using the ChangeDetection.OnPush strategy. And, unlike Immutable.js, it interoperates seemlessly with standard JavaScript.</p><p>Not yet convinced? How about the obligatory Todo app example.</p><p>You can view this in <a href="https://github.com/darrenmothersele/ngrx-todo-immer-unionize">this GitHub repo</a>, or launch it directly on <a href="https://stackblitz.com/github/darrenmothersele/ngrx-todo-immer-unionize/">StackBlitz</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/174c34044cf245eeb948cace2273baf8/href">https://medium.com/media/174c34044cf245eeb948cace2273baf8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4662c43fc7ba1719a8c44754cde230dd/href">https://medium.com/media/4662c43fc7ba1719a8c44754cde230dd/href</a></iframe><p><strong>NB</strong>: In order to use AOT (i.e. production builds) the exported reducer function must be declared as a function, not a const. Use something like this:</p><pre><strong>export function </strong><em>reducer</em>(state = initialState, action) {<br>  <strong>return </strong>produce(<em>producer</em>)(state, action);<br>}</pre><p>or, if you prefer…</p><pre><strong>export const </strong>reducerProducer = produce(<em>producer</em>, initialState);<br><br><strong>export function </strong><em>reducer</em>(state, action) {<br>  <strong>return </strong>reducerProducer(state, action);<br>}</pre><p>For more info check the <a href="https://github.com/mweststrate/immer">Immer</a> and <a href="https://github.com/pelotom/unionize/">Unionize</a> repos. Drop me a line if this was useful, or if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a118317ff420" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unzip Files in the Browser with Angular 7]]></title>
            <link>https://medium.com/@dazcyril/unzip-files-in-the-browser-with-angular-7-fcdc3040f3c1?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcdc3040f3c1</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 19:41:13 GMT</pubDate>
            <atom:updated>2018-12-19T19:41:13.786Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="http://gildas-lormeau.github.com/zip.js/">zip.js</a> is an open-source library (BSD license) for zipping and unzipping files in JavaScript. It uses a Web Worker to do the actual Zip file processing. Here I explain how I got this working in Angular…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_d2YzErPHo3OGsA28YYIA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/nVqNmnAWz3A?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Tomas Sobek</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You don’t need all of the files from zip.js to make this work. You only need these 4 files listed below. Copy them into your Angular project. Put them in your src/assets folder as you need them copied into your build output.</p><ul><li><a href="https://github.com/gildas-lormeau/zip.js/blob/master/WebContent/deflate.js">deflate.js</a></li><li><a href="https://github.com/gildas-lormeau/zip.js/blob/master/WebContent/inflate.js">inflate.js</a></li><li><a href="https://github.com/gildas-lormeau/zip.js/blob/master/WebContent/z-worker.js">z-worker.js</a></li><li><a href="https://github.com/gildas-lormeau/zip.js/blob/master/WebContent/zip.js">zip.js</a></li></ul><p>The files need to be copied across into the build, because they are loaded directly by the browser to register as a web worker. Linking the scripts directly from the built assets folder is the easiest method I found to do this.</p><p>I actually used a separate lib/zip folder, rather than putting them in with my app assets. I then edited my angular.json file so that the scripts are copied across into the build.</p><pre>{<br>  <strong>&quot;glob&quot;</strong>: <strong>&quot;**/*&quot;</strong>,<br>  <strong>&quot;input&quot;</strong>: <strong>&quot;./lib/zip&quot;</strong>,<br>  <strong>&quot;output&quot;</strong>: <strong>&quot;./scripts/&quot;<br></strong>}</pre><p>The main zip.js file is then added to your main index.html by adding this before the closing &lt;/body&gt; tag:</p><pre>&lt;<strong>script type=&quot;text/javascript&quot; src=&quot;scripts/zip.js&quot;</strong>&gt;&lt;/<strong>script</strong>&gt;</pre><p>I then created a few interfaces, to make it nicer to work with in TypeScript:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f39057f20c94747111debed4ecd3c1f8/href">https://medium.com/media/f39057f20c94747111debed4ecd3c1f8/href</a></iframe><p>I then wrapped the zip.js in a service so I could inject it into my Angular components where needed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc492168d9809eaa51c5406836191faa/href">https://medium.com/media/cc492168d9809eaa51c5406836191faa/href</a></iframe><p>To use this example, inject into another Angular component or service. Then, call getFiles() passing in the file as an argument. For example, pass in a File object as retrieved from the change event on a file input:</p><pre>&lt;<strong>input type=&quot;file&quot; (change)=&quot;</strong>fileChanged(<strong><em>$event</em></strong>)<strong>&quot;</strong>&gt;</pre><pre>fileChanged(event) {<br>  <strong>const </strong>file = event.<strong>target</strong>.<strong>files</strong>[0];<br>  ...<br>}</pre><p>The observable returned by getFiles() resolves to an array of ZipEntry items as defined in the above interface. You can then pass an item from the array to the getData() method on ZipService to unzip and retrieve the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcdc3040f3c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Per-User File Upload Quotas with Angular and Firebase Custom Auth Tokens]]></title>
            <link>https://medium.com/@dazcyril/per-user-file-upload-quotas-with-angular-and-firebase-custom-auth-tokens-a2d32c28e4ef?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d32c28e4ef</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Wed, 19 Dec 2018 19:01:01 GMT</pubDate>
            <atom:updated>2018-12-19T22:30:38.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*id0-tVmoI2tiHw0BwttIrw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/fyaTq-fIlro?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">chuttersnap</a> on <a href="https://unsplash.com/search/photos/storage?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Working serverless with Angular and Firebase is great, but sometimes there’s a requirement that seems hard to achieve. Firebase Storage allows you to set complex security rules to manage access per user, and you can restrict upload size on a per-file basis. But, what if you need to restrict user uploads based on a per-user quota? This can be achieved by using Firebase Cloud Functions and Custom Auth Tokens.</p><p>First we define Firebase Storage security rules that allow users to upload to their own private area within the storage. Users can only <strong>read</strong> files that are prefixed by their user ID. They can only <strong>write</strong> to paths where their user ID matches AND the file path (resource.name) matches the path in the token AND the file size (resource.size) is smaller than the remaining quota specified in the auth token.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6f731b3f27c60a4d96bace664992b9/href">https://medium.com/media/2d6f731b3f27c60a4d96bace664992b9/href</a></iframe><p>The upload process is then achieved in 3 steps:</p><ol><li>Call a Firebase Cloud Function to generate a new auth token that includes the user’s remaining quota allowance.</li><li>Re-authenticate with Firebase using the custom token.</li><li>Upload the file to Firebase Storage.</li></ol><p>First, on the Angular side, we wrap the storage upload observable to make it easier to compose. Notice that the upload path is created by combining the user ID and a file ID (generated elsewhere). This path is also generated as part of the token and part of the security rules check that these match.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/870a5e40b0f02eb327dba2d908ce606b/href">https://medium.com/media/870a5e40b0f02eb327dba2d908ce606b/href</a></iframe><p>The three steps to upload can then be composed using RxJS Observables. Notice that the same ID used for the file path is also passed as an argument to the getQuotaToken callable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/636e8c98ebc5a6a6cb025bf3cb345f7f/href">https://medium.com/media/636e8c98ebc5a6a6cb025bf3cb345f7f/href</a></iframe><p>For the Cloud Function, we first create a utility function that will take a user ID as parameter, list all the files for this user, and calculate the total sum of the file sizes. This function getUsage will be used by our Cloud Function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af5880ea8d2f250b057f91117dfdfc21/href">https://medium.com/media/af5880ea8d2f250b057f91117dfdfc21/href</a></iframe><p>We can now define a Cloud Function that will generate and return the Custom Authentication Token. The Angular front-end code calls this Cloud Function and passes the generated token to Firebase. This token is then used by the Firebase Storage security rules when the file upload is attempted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d44027ffbacde7419dbcf925988dab2/href">https://medium.com/media/2d44027ffbacde7419dbcf925988dab2/href</a></iframe><p>We have provided for a default quota, and allow a quota to be specified for each user. The constant DEFAULT_QUOTA should be set to a value in bytes. For example 5MB would be (5 * 1024 * 1024). You could allow users to purchase more storage space, in which case you would set the user’s quota value after a successful payment (using setCustomUserClaims). The example above is using a quota that has been set on the user with the DEFAULT_QUOTA value as a fallback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d32c28e4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management in Angular]]></title>
            <link>https://medium.com/@dazcyril/state-management-in-angular-9ebae914ca9a?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ebae914ca9a</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ngrx]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 10:31:08 GMT</pubDate>
            <atom:updated>2018-04-15T10:31:08.772Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxErHtluCSUA2YLvri-IsA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ZahNAl_Ic3o?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Austin Neill</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>There’s a new state management option for Angular, called NGXS. Having just completed a large Angular project, with complex state management requirements, I was interested to find out more about it.</p><p>A demo app has been provided to show how <a href="https://github.com/ngrx/platform">NGRX</a> and <a href="https://github.com/ngxs/store">NGXS</a> compare. The way the NGRX code is presented in the demo app does not reflect how I had been working with NGRX, so I wanted to address this. I use the unionize library along side NGRX for “Boilerplate-free functional sum types in TypeScript”. I have <a href="https://github.com/darrenmothersele/ngrx-vs-ngxs">extended the “ngxs vs ngrx” demo app</a> to include a third example that shows the ngrx with unionize option. I’ve forked the repo on GitHub <a href="https://github.com/darrenmothersele/ngrx-vs-ngxs">here</a>.</p><p>I haven’t used NGXS yet, but it does seem to address some of the concerns with NGRX. The main one being that because NGRX is inspired by Redux from the React eco-system, it doesn’t feel very Angular. On first inspection, NGXS does look more like idomatic Angular.</p><p>One thing I learned from recent projects, is that most of the time you don’t need to make the jump to a full-on Redux style state management library. You can achieve something simple in Angular, and still get separation of concerns, and modularity using the BehaviourSubject in an injectable service approach. There is a big jump from the simple Angular component style, to a full redux style architecture. Perhaps NGXS could offer an easier transition, because it will be more familiar to Angular developers?</p><p>I have found the centralised dispatch of NGRX actions, along with meta-reducers, to be very useful when refactoring, or implementing features that would otherwise require many changes across the whole codebase, or touching many components. Analytics, logging and debugging are just a few examples. It looks like NGXS will have similar benefits, as it has the concept of “plugins”.</p><p>In conclusion, I’m going to take a much deeper look at NGXS, as I think it looks promising. From my recent experiences with Angular, on fairly large projects, I gained a good understanding of NGRX and RxJs. This includes where it makes sense to use redux, and where other more idomatic Angular options would be the simpler. It looks like a lot of thought has gone into NGXS, and how to re-imagine the Flux/Redux pattern to better fit with the Angular framework. I’ll be watching how this develops…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ebae914ca9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimise Redux boilerplate with “unionize” when using NgRx with Angular 5]]></title>
            <link>https://medium.com/@dazcyril/minimise-redux-boilerplate-with-unionize-when-using-ngrx-with-angular-5-e75dba6dd2c0?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e75dba6dd2c0</guid>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 09:13:46 GMT</pubDate>
            <atom:updated>2018-03-09T09:13:46.797Z</atom:updated>
            <content:encoded><![CDATA[<p>Yet another <a href="https://github.com/darrenmothersele/ngrx-unionize-counter">counter example</a>.</p><p>NgRx is an implementation of Redux, in Angular, using RxJS. It’s genius. It combines the power of Redux and RxJS, and helps to create scalable architecture when dealing with large applications.</p><p>But, the downside is that it needs a lot of boilerplate code.</p><p>That is where <a href="https://github.com/pelotom/unionize">unionize</a> really helps.</p><p>I’ve been using unionize for the past few months, on a large and complex codebase. This app had some unique requirements, and managing state in NgRx really helped. Using unionize helped to keep the NgRx code consistent, and manageable.</p><p>I’ve created a small barebones to demonstrate how unionize can be used with NgRx here: <a href="https://github.com/darrenmothersele/ngrx-unionize-counter">https://github.com/darrenmothersele/ngrx-unionize-counter</a></p><p>Let’s walkthrough the code.</p><p><a href="https://github.com/darrenmothersele/ngrx-unionize-counter/blob/master/src/app/state/counter/actions.ts">https://github.com/darrenmothersele/ngrx-unionize-counter/blob/master/src/app/state/counter/actions.ts</a></p><p>The main unionize helper creates a union type out of your list of actions:</p><pre>export const CounterActions = unionize({<br>  increaseValue: ofType&lt;number&gt;(),<br>  decreaseValue: ofType&lt;number&gt;()<br>}, &#39;type&#39;, &#39;payload&#39;);</pre><p>Save the type for ease of use in the reducer function:</p><pre>export type CounterActionsType = typeof CounterActions._Union;</pre><p><a href="https://github.com/darrenmothersele/ngrx-unionize-counter/blob/master/src/app/state/counter/reducer.ts">https://github.com/darrenmothersele/ngrx-unionize-counter/blob/master/src/app/state/counter/reducer.ts</a></p><p>Use the match() helper when creating the reducer function:</p><pre>export function counterReducer(state: CounterState = initialValue, action: CounterActionsType): CounterState {</pre><pre>return CounterActions.match({     </pre><pre>  // your action implementations go here#<br>  // each one returns a new state</pre><pre>}, () =&gt; state)(action);}</pre><p>Check out the full code in the <a href="https://github.com/darrenmothersele/ngrx-unionize-counter">example repo</a> for more details, and the <a href="https://github.com/pelotom/unionize">unionize readme</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e75dba6dd2c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drupal Is Not the Answer]]></title>
            <link>https://medium.com/@dazcyril/drupal-is-not-the-answer-f97854b9c7ba?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f97854b9c7ba</guid>
            <category><![CDATA[drupal]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Wed, 22 Nov 2017 12:26:44 GMT</pubDate>
            <atom:updated>2017-11-22T12:26:44.692Z</atom:updated>
            <content:encoded><![CDATA[<p>I wrote most of this article about 6 months ago as a cathartic exercise. It was not originally intended for publication. After 10 years of using Drupal as my main technology, I started to branch out into other technologies. I noticed I was enjoying working with other technologies more than Drupal. Where I had enjoyed Drupal, it was now a regular source of frustration.</p><h4>Drupal Was the Answer</h4><p>Up until recently, Drupal was the answer. It didn’t really matter what the question was. For me, the answer was almost always Drupal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqdtXHQFqqaOAuHVmrYMeg.png" /><figcaption>Source: <a href="https://trends.google.co.uk/trends/explore?date=all&amp;q=drupal">Google Trends (Search term = Drupal)</a></figcaption></figure><p>I feel lucky to have ridden the Drupal wave. Through life’s ups and downs Drupal provided a stable platform for me to grow my freelance web development and consulting business. I’ve had the pleasure of working on some amazing projects. From small boutique operations, through to huge flagship Drupal sites for major corporations. From simple websites, through to full-blown apps built on top of Drupal.</p><p>At times projects could be difficult, sometimes downright weird, but Drupal was always fun to work with and could bend to fit almost any problem. Most of all, I met a community of great people who shared similar values, made great colleagues, and made some good friends.</p><p>Over the past year, Drupal has taken smaller (and more focused) role in the solutions I’ve been building. I’ve embraced some new technology to created a much more varied stack.</p><h4>What Is the Question?</h4><p>Drupal is not the answer, because in 2017 and beyond, the questions have changed. Drupal might be the answer if you want a flexible, secure, open-source CMS. It’s great if you need to manage structured content, and want a system that can be customised to meet specific content requirements with minimal effort.</p><p>But, how does Drupal answer the wider question of what technology to use to meet today’s (and tomorrow’s) expectations? The expectations for user experience are changing all the time. New technology is enabling new ways of accessing and interacting with content. Progressive Web Apps are becoming more mainstream. The adoption of microservice, and decoupled architectures has proven to be successful. Declarative programming styles are becoming more popular and proving to be more expressive (and less error-prone) than imperative styles.</p><h4>The Last Ever Rebuild</h4><p>A big disruption to web development in the last 10 years was the rapid uptake of the mobile web. This launched many projects as agencies sold responsive rebuilds. The need to redesign websites so they could adapt to an infinite array of devices led many organisations to do a full platform rebuild. The requirement to support mobile was often bundled in with replacing a “pre web 2.0-era” legacy system, adopting an open-source CMS, or some other hair-brained “digital transformation” scheme.</p><p>Dries, in his regular “State of Drupal” address to the community, used to preach <a href="http://buytaert.net/one-drupal-to-rule-them-all">One Drupal to Rule them all</a>. He saw fragmented use of technology across organisations and dreamed of organisations standardising on Drupal.</p><p>The community got behind this and built lots of apps on top of Drupal. It was extended it in every possible direction. Social networks, Intranets, Project management apps, E-commerce, CRMs, ABCs, XYZs were all built on Drupal.</p><p>For many years, agile pioneers ThoughtWorks warned against this “CMS as a platform” approach:</p><blockquote>We are seeing too many organizations run into trouble as they attempt to use their CMS as a platform for delivering large and complex digital applications. This is often driven by the vendor-fueled hope of bypassing unresponsive IT organizations and enabling the business to drag and drop changes directly to production.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tkdX1TnFUtJ0TMhQxP1ng.png" /><figcaption>Source: <a href="https://www.thoughtworks.com/radar/platforms/cms-as-a-platform">ThoughtWorks Technology Radar</a></figcaption></figure><p>That “vendor-fueled hope” of drag and dropping changes fuelled massive success for Drupal-shops and agencies as project sizes increased and more scope was introduced into CMS and website projects. It created opportunities for us Drupal developers to work on more interesting projects that extended beyond just creating simple websites.</p><p>We saw a lot of fanfare around large successful projects building monoliths on top of Drupal. Behind the success stories, it was often tired developers being labelled as “rock-stars” and “ninjas”, desperately patching systems resembling big balls of mud in attempt to meet ridiculous expectations, leaving a trail of unmaintainable, insecure, unstable projects that ran over time and over budget.</p><p>Meanwhile, the rest of the internet was learning that the monolith was not the way to go. Many organisations, feeling the pain of the rebuild, were splitting systems into much simpler components. So they would never again have to face the pain of a full system rebuild. Splitting complex systems into components that can have their own life-cycle and speeds of change. The backend can remain stable and develop much slower, while the frontend, decoupled from the rest of the system, can evolve much faster to adopt new user experiences and deliver much faster on changing business requirements and customer expectations.</p><p>The last ever rebuild is a move to a more decoupled architecture. And, Drupal might not be the answer for everything, but it is certainly a strong contender for the content-management part of a decoupled backend.</p><h4>Drupal Is the Answer?</h4><p>Does this mean I’m not doing Drupal anymore? No, where Drupal is the right tool, I’ll definitely be using it. Over the past 18 months I’ve used Drupal on the backend, with Elasticsearch in the middle, and Angular 2+ on the frontend. It has lead to successful projects, delivered on time (or early), that were fun to work on, and pleased clients.</p><p>One thing I’ve learned, by spending time with other languages and frameworks, is to realise when something is “easy” because I’ve got over the learning curve. But, it can be easy, without being simple.</p><p>So, I continue to aim for simplicity. And, use the right tool for the job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f97854b9c7ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Angular Controls with SVG]]></title>
            <link>https://medium.com/@dazcyril/custom-angular-controls-with-svg-efeeb75922b?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/efeeb75922b</guid>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[web-audio-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Fri, 17 Nov 2017 12:41:22 GMT</pubDate>
            <atom:updated>2017-11-17T14:51:49.494Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago I was playing around with the Web Audio API and Angular v4. The results of this experimentation was a “modular synth” like GUI for creating horrible “Web Audio” noise using Tone.js. You can find the code in <a href="https://github.com/tone-lab/tone-lab">this GitHub repo</a> or see the real thing <a href="https://tone-lab.github.io/">here</a>. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-FpqdJ7gUUSsj1-nKzOvQ.png" /><figcaption><a href="https://github.com/tone-lab/tone-lab">Tone Lab </a>— Modular Synth GUI with Web Audio</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrIXsaG9w34E%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrIXsaG9w34E&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrIXsaG9w34E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4beba1bf787dcff70463255ce4f06789/href">https://medium.com/media/4beba1bf787dcff70463255ce4f06789/href</a></iframe><p>I wanted a minimal UI — and didn’t want to mess around trying to style up HTML elements with CSS. So, I decided I would use really simple SVG controls.</p><p>To do this I generated the SVG using Angular (v4 at the time) within my components for the controls.</p><p>Let’s look at value slider control. You can see several examples of this component in the screenshot above. It’s the vertical slider, with an optional label (text rotated 90<strong>°</strong>) a vertical line, and a small circle indicating the current value.</p><p>First the template. This is a standard Angular template file, but with SVG inside it…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b508eda805388b78bd9eab89e16bf525/href">https://medium.com/media/b508eda805388b78bd9eab89e16bf525/href</a></iframe><p>The &lt;svg&gt; tag wraps three nodes. A text node, which outputs the {{ label }} provided as input to the component. A &lt;path&gt; for the vertical line, and then a &lt;circle&gt; that represents the current value. Notice how I bind the centre point of the circle to cursorPt.y — a property on the component that is used to store the current position.</p><p>The CSS is simple. I styled the host element to match the viewBox dimensions of the SVG as it made the math a bit easier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bd9f8076dd6c7d46547c6e521815eaf/href">https://medium.com/media/3bd9f8076dd6c7d46547c6e521815eaf/href</a></iframe><p>And now the fun bit, the component Typescript code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b0a35b2a97c2d84824a0fa067aec8e2/href">https://medium.com/media/4b0a35b2a97c2d84824a0fa067aec8e2/href</a></iframe><p>The drag behaviour is created using RxJS Observables. I create an Observable from the mousedown events on the component, plus mousemoveand mouseup events on the whole document.</p><p>These then combine to create the drag Observable like this:</p><pre>const drag = down.mergeMap((md: MouseEvent) =&gt; {                                   return move.startWith(md).takeUntil(up.take(1));                               });</pre><p>So down events are mapped to move events, which are taken until an up event. Essentially the down event starts a stream of move events which is terminated by the occurrence of an up event.</p><p>There’s a bit of extra complexity, as seen in the init and drag event handler to do with scaling values. I use the matrix transform available on the SVGPoint objects to translate the coordinates. Then scale the value from the y coordinate using the min and max values of the range.</p><p>This then gives you a slider control you can use in other components like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36cbd2fc0b48150449329dd2122b1b35/href">https://medium.com/media/36cbd2fc0b48150449329dd2122b1b35/href</a></iframe><p>The slider is a basic example, but I also created an Analyser as an Angular Component using SVG to display waveforms and frequencies. This was useful for debugging what was going on in the Web Audio API graphs. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77sx3avIU_Gx7rnsswYP3Q.png" /><figcaption>Example of Analyser Component</figcaption></figure><p>The waveform output is created by binding an SVG path node to a property on the Angular Component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e34228a9a15640c40f2e9e7b61947195/href">https://medium.com/media/e34228a9a15640c40f2e9e7b61947195/href</a></iframe><p>Then, in the Component I use a getter for each of the properties to generate the SVG path definitions for each waveform:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5004e8d0f54fd2c826ae079e133fae60/href">https://medium.com/media/5004e8d0f54fd2c826ae079e133fae60/href</a></iframe><h4>Wrap up</h4><p>This started as a quick experiment to play around with the Web Audio API. Using SVG was fun. It seems like creating custom SVG output from Angular Components could be a powerful way of creating bespoke UI controls. I think this is powerful and flexible beyond what you can do with just HTML elements on their own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efeeb75922b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolving Data in Angular 2, 4, and 5; refactoring components; and moving to ngrx/store]]></title>
            <link>https://medium.com/@dazcyril/resolving-data-in-angular-2-4-and-5-refactoring-components-and-moving-to-ngrx-store-15e15d8be3dd?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/15e15d8be3dd</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[angular-4]]></category>
            <category><![CDATA[ngrx]]></category>
            <category><![CDATA[angular-5]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Thu, 09 Nov 2017 12:03:52 GMT</pubDate>
            <atom:updated>2018-02-27T07:57:12.887Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>UPDATE 26th Feb 2018: </em></strong><em>I have added a new v6 where I switch to using </em><em>unionize to help reduce the amount of boilerplate needed when working with NgRx.</em></p><p>I’ve worked on a few Angular projects over the past 18 months. There’s a lot to learn from working on real-life apps, a large code base, with lots of components. But, I also like creating simple sketches. Small example apps that let you focus on one specific detail. Here I document a sketch I’ve created that looks at various ways of loading data in Angular.</p><p>This particular sketch is a partial review of my journey with Angular. I started with loading data directly in components — easy to understand but not scalable. Then I really got into the Angular Router and started using the data resolvers. Then, eventually, I get into ngrx — the RxJS powered Redux implementation targeted at Angular.</p><p>Here’s the sketch. The <a href="https://github.com/darrenmothersele/angular5-resolve-data">code</a> (tagged with various milestones) is available on <a href="https://github.com/darrenmothersele/angular5-resolve-data">GitHub</a>. I make use of data from the <a href="https://jsonplaceholder.typicode.com/">JSONPlaceholder</a> service, and it looks a bit like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0GL9W4RmlQk2wG-q3UomNg.png" /><figcaption><a href="https://github.com/darrenmothersele/angular5-resolve-data">Simple app to demonstrate data resolving in Angular</a></figcaption></figure><p>I will include snippets of code along the way. If you want to see the whole thing you can git checkout the various version tags to see the code as it develops, <a href="https://github.com/darrenmothersele/angular5-resolve-data">browse the version tags</a> on GitHub, or refer to the tags on the <a href="https://github.com/darrenmothersele/angular5-resolve-data/releases">repository releases page</a>.</p><p>Here’s a model interface to represent the data that’s coming back the JSONPlaceholder API for users:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4200e5f432df93843017db5430b7e9fe/href">https://medium.com/media/4200e5f432df93843017db5430b7e9fe/href</a></iframe><p>And I created a simple service that I can inject to access the API. I have added a utility function that will convert a User to a Partial&lt;User&gt; so I can simulate getting a summary feed of users. The JSONPlaceholder API returns the same full data for the list of users and when you request an individual user. The scenario I want to simulate is getting a feed of summary information and then making further requests to get detail information on each record. The trimUser function just picks the id, name, and username fields.</p><p>You will also notice that I add a delay to the Observable to simulate a slow network. I want to make it visibly obvious where data is loading. This is a trick I use a lot when developing as it’s easy to forget the difference it makes when running over a network compared to running locally on my super-computer.</p><p>There are two methods in this service, one returns the list of users, the other returns detailed data for a specified user:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b821f159d0174e91ab8e98b1ebb5ed2/href">https://medium.com/media/0b821f159d0174e91ab8e98b1ebb5ed2/href</a></iframe><h4>Initial Version (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v0">v0</a>)</h4><p>In this first version I inject the data service directly into the component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad8fd53fc317c13cca5d5b5d871fd465/href">https://medium.com/media/ad8fd53fc317c13cca5d5b5d871fd465/href</a></iframe><p>Notice how I need to keep track of if the user list has been loaded yet, so that I can conditionally display the user list, and give some feedback to the user.</p><p>For the contact detail page I need to inject the service, and the route, so that I can subscribe to the ID parameter from the route and fetch the appropriate user record:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/933ad50d67e6b9dc274cfcd3c295e9cb/href">https://medium.com/media/933ad50d67e6b9dc274cfcd3c295e9cb/href</a></iframe><h4>User List Resolver (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v1.1">v1.1</a>)</h4><p>The first improvement is to move the responsibility of fetching the data out of the component, and into a separate object. This object will be used by the Angular Router to load the data before navigating to the page, so when the component is ready, the data has already been fetched.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a95701c44be036e806716221b3c2e1c2/href">https://medium.com/media/a95701c44be036e806716221b3c2e1c2/href</a></iframe><p>The resolver is added to the list of routes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea66cfae4164780858bcba34216a0ee/href">https://medium.com/media/0ea66cfae4164780858bcba34216a0ee/href</a></iframe><h4>User Detail Resolver (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v1.2">v1.2</a>)</h4><p>The user detail resolver gets the ID param from the route parameters and passes this into the service call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a375ec8dedd78adcf0dc463ad6744b4/href">https://medium.com/media/2a375ec8dedd78adcf0dc463ad6744b4/href</a></iframe><p>It is added to the route config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6e5fd7db844679e4c07a5c1bc1ed4f0/href">https://medium.com/media/f6e5fd7db844679e4c07a5c1bc1ed4f0/href</a></iframe><p>And then, in the component, the route data is subscribed to in order to get the user for display:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62acace7205c84e42a45d1b51878e3e1/href">https://medium.com/media/62acace7205c84e42a45d1b51878e3e1/href</a></iframe><h4>Container Components (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v2">v2</a>)</h4><p>In the first version (v0) the components were doing several things, breaking the “single responsibility principle”. Each component was responsible for fetching data, and displaying it.</p><p>Now we split out the actually resolving of data but the components still have to know how to get the data they require from the context, and display it. This context is injected in to the component (as the route). A popular pattern is to separate out components into “container” components and “presentational” components.</p><p>Presentational components take basic data as inputs and know how to render them. They don’t do any logic, they just accept inputs. Container components wrap the presentational components, providing them with the needed data. The container components know how to get the appropriate data from the context they are provided.</p><p>Here is the detail component simplified down to just a presentational component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bae67e4d5d8c6eeaa125eb6fbb0da05d/href">https://medium.com/media/bae67e4d5d8c6eeaa125eb6fbb0da05d/href</a></iframe><p>It just has @Input‘s — there’s no logic. I like to leave a comment to remind me that this is a presentational component — so I don’t come along and complicate it later.</p><p>The work in this presentational component is done in the template. It just provides markup and styling of the input content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee50bb1970e52a8bd0299ec3ababf7b8/href">https://medium.com/media/ee50bb1970e52a8bd0299ec3ababf7b8/href</a></iframe><p>I created a separate container component to wrap this. It just knows how to get the required data from the route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/701cfc6b55b01e7a398a2d134666a610/href">https://medium.com/media/701cfc6b55b01e7a398a2d134666a610/href</a></iframe><h4>Recap</h4><p>As things stand, I’m quite happy with the architecture of this simple app. Responsibilities are separated along sensible lines, and nothing really has too much responsibility. The data is fetched by the service, which is called from the router resolvers, which is read by the container components, and displayed by the presentational components. Sounds reasonable.</p><p>This is all well and good in a simple example app. But, from my experience working on a large Angular app, I know this kind of architecture is hard to stick to once you start adding in more features, things get a bit more fuzzy, and the boundaries are not clear.</p><p>Real world apps need more advanced async handling, data fetching, use of local storage, caching, etc. This is when I got excited about Redux, and in particular the RxJS-based implementation NgRx for Angular. While the boilerplate can make it seem unnecessary on a small sketch like this, I’m sold on the benefits one one-way data flow after working on larger projects.</p><p>I made two steps in implementing NgRx in this example. First I added a purely Store and Effects based approach, then I looked at the ngrx Entity package.</p><h4>NgRx Store (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v3">v3</a>)</h4><p>The main addition in this version is the global state managed by NgRx store. This is not meant to be a general “how to use redux” style example, I’m specifically thinking about strategies for resolving data.</p><p>In this first example, the store state has two parts. One for the users list and one for the user detail. It’s defined with the following interface, and the two separate reducers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3031091961685e7dba9c8dd35c5d2b2/href">https://medium.com/media/a3031091961685e7dba9c8dd35c5d2b2/href</a></iframe><p>Then, local to the user list reducer, I have the state specific to this part. NgRx has a concept known as “fractal state management”. You can separate out code into feature modules. This works with Angular’s lazy loading. I’ve found it easier to have a single global set of definitions, unless I know the state is only ever used in a particular context. Here is the user list state interface and a default initial state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66286e9fa9f162f45372da760157f359/href">https://medium.com/media/66286e9fa9f162f45372da760157f359/href</a></iframe><p>A common pattern in NgRx is to dispatch a LOAD action to initiate fetching of data. The data is fetched asynchronously and then either a LOAD_SUCCESS or LOAD_FAILURE action is dispatched. This isolates side effects and keeps the rest of the state management <a href="https://en.wikipedia.org/wiki/Pure_function">pure</a>.</p><p>Here’s the reducer, that just updates the state in response to the actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f839c35279cbb15a0f6a8e0f360704ba/href">https://medium.com/media/f839c35279cbb15a0f6a8e0f360704ba/href</a></iframe><p>The data fetching happens in an NgRx Effect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c294026ab6f55fd33febb52a1bcdbb90/href">https://medium.com/media/c294026ab6f55fd33febb52a1bcdbb90/href</a></iframe><p>The NgRx store and effects are added to the main App NgModule:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/490878eae8fa00a94960508e1942d836/href">https://medium.com/media/490878eae8fa00a94960508e1942d836/href</a></iframe><p>To link this up with the Angular components, the presentational components don’t need to change. They only accept inputs, and the container components will provide the same as before. The container components need updating to select the data they want from the store.</p><p>On the listing page this is straightforward. The component just selects the users and the loading state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/670cb9daa668165b2f043401d77eb7fa/href">https://medium.com/media/670cb9daa668165b2f043401d77eb7fa/href</a></iframe><p>The template for the component unwraps the Observable, iterates through each item, and passes each user object to the user card presentational component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2409ffd9b0b97f1b9b3dae359630bb50/href">https://medium.com/media/2409ffd9b0b97f1b9b3dae359630bb50/href</a></iframe><h4>NgRx Entity (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v4">v4</a>)</h4><p>Rather than having separate parts of state for the user list and the current user details, I want to have a single repository of users. To do this I will make use of the Partial type in Typescript. In particular, I will define the repository of users to be of type Partial&lt;User&gt; so that I can store both the summary feed and the full user detail objects.</p><p>This will improve the performance of the app, by being able to show partial data while loading full details from the server.</p><p>I will make use of the NgRx Entity package to reduce the amount of boilerplate code needed to work with a repository of User entities in the store.</p><p>Previously I had two distinct sets of actions for the user list and user details. I now have a single set of actions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/523727ec93bc583ab7dd5d7d394f36ee/href">https://medium.com/media/523727ec93bc583ab7dd5d7d394f36ee/href</a></iframe><p>I create a userAdapter to manage the repository of users in the state from the provider given by NgRx Entity:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7528d97bba14d5d87af18e784c85410c/href">https://medium.com/media/7528d97bba14d5d87af18e784c85410c/href</a></iframe><p>Then, make use of the utilities provided by the adapter when creating the new reducer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb6ccde0daf6c81a1bc750c3fe638cfd/href">https://medium.com/media/fb6ccde0daf6c81a1bc750c3fe638cfd/href</a></iframe><p>The summary success case adds many results. The detail success case either adds the detail (in the case it doesn’t exist) or updates the existing (possibly partial record).</p><p>The changes required to the container components are fairly trivial. They must dispatch using the new Actions, and select the data using the new selectors created using the entity adapter.</p><h4>Unionize (<a href="https://github.com/darrenmothersele/angular5-resolve-data/tree/v6">v6</a>)</h4><p>It is possible to massively cut down the amount of boilerplate needed when working with NgRx by using the unionize library. I demo this in v6 of the repo. The unionize library contains helpers for creating actions, reducers, filtering the actions$ observable in Effects, and dispatching actions. In this version I refactor the NgRx code into an AppStateModule .</p><h4>Wrap up</h4><p>This example has been focused on different strategies for fetching data in an Angular app. Starting with a simple service that is injected directly into components, through various steps of refactoring to improve the design. Some refactoring to separate into container and presentational components, and then moving to a Redux-inspired architecture using NgRx.</p><p>This use of Effects may be sub-optimal. As mentioned <a href="https://medium.com/@m3po22/stop-using-ngrx-effects-for-that-a6ccfe186399">in this post</a> it can lead to unwieldy code. So the next step will be to implement an improvement based on the recommendations from <a href="https://medium.com/@m3po22/stop-using-ngrx-effects-for-that-a6ccfe186399">this other article</a>.</p><p>Please get in touch with any questions, or feedback. In particular, I’d love to hear about other strategies or improvements that could be made.</p><p>Thanks,</p><p>Darren</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15e15d8be3dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Cryptographic Random State in JavaScript (in the Browser)]]></title>
            <link>https://medium.com/@dazcyril/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c538b3daae50</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Thu, 02 Nov 2017 09:43:02 GMT</pubDate>
            <atom:updated>2017-11-02T09:43:02.493Z</atom:updated>
            <content:encoded><![CDATA[<p>I need to generate some random state for an OAuth2 implicit flow for a JavaScript SPA. This “state” is passed to the identity provider, and then passed back after authentication to guard against XSS. Basically, I just need a string of random characters.</p><p>This state parameter is optional in OAuth2 implicit flow, and it only needs to be pseudo-random, but authentication isn’t something I like to take chances with, so I thought I’d look for the best option. I did a quick web search, as this seemed like the kind of thing that I’d find a perfect, best-practise, solution for on stack overflow, GitHub or similar. But, I had a few issues with the solutions I found:</p><ol><li>They used the crypto library from node, so were server-side solutions not intended for the browser, or,</li><li>They used Math.random which I decided wasn’t suitable and I wanted to use the <a href="https://caniuse.com/#feat=cryptography">Javascript Cryptography API</a>, or,</li><li>They had nested loops and conditionals, which were either inefficient, or not declarative enough for my programming style, or,</li><li>They produced a byte-string that didn’t encode easily in a URL.</li></ol><p>Here was one of the implementations I liked, from an <a href="https://github.com/manfredsteyer/angular-oauth2-oidc/blob/master/angular-oauth2-oidc/src/oauth-service.ts">Angular OAuth2 library</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc1f8aa1733d3c710cafa959fc122c6b/href">https://medium.com/media/dc1f8aa1733d3c710cafa959fc122c6b/href</a></iframe><p>I liked the use of “possible” chars, but it uses Math.random() and I wanted to use getRandomValues() from the Cryptography API. I tried a couple of simple looking approaches to converting the bytes returned from getRandomValues but decided to combine it with the “possible” chars approach, and ended up with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0dd4217767d0cb518837f18a967a44b/href">https://medium.com/media/c0dd4217767d0cb518837f18a967a44b/href</a></iframe><p>The<a href="https://developer.mozilla.org/en-US/docs/Web/API/RandomSource/getRandomValues"> MDN docs for the Cryptography API</a> states that:</p><blockquote>To guarantee enough performance, implementations are not using a truly random number generator, but they are using a pseudo-random number generator <em>seeded </em>with a value with enough entropy. The PRNG used differs from one implementation to the other but is suitable for cryptographic usages. Implementations are also required to use a seed with enough entropy, like a system-level entropy source.</blockquote><p>The 40 character strings that are produced by this code should be random enough, performance is OK, and they encode easily into an URL for submitting to the identify provider as part of an OAuth2 implicit flow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c538b3daae50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Latest 3D fractal works…]]></title>
            <link>https://medium.com/@dazcyril/latest-3d-fractal-works-ab4dbc042269?source=rss-ad8b0a0a140e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab4dbc042269</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[fractals]]></category>
            <dc:creator><![CDATA[Daz]]></dc:creator>
            <pubDate>Sun, 05 Jun 2016 16:33:33 GMT</pubDate>
            <atom:updated>2016-06-05T16:33:33.220Z</atom:updated>
            <content:encoded><![CDATA[<p>A few more of my recent 3d fractal experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaMm5eSBfSjx6vLKTBu9bQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElGHYq_KB7K2M-xlIAM_7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otnQXb1gcSlCK6EeQChXvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*HJXE7Pkgil23xPrdZWvAQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aNOdApXBeLOau2H1OxIM1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWYEi7yPQTBIWASoreu7dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Z2WR5syWv000Ci2H5pMzyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*piUWaX1s17U_5hxhCZ_UDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*R2kPBMPzY9p0lnolJZ3sNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSzNKkOJe5yhRfPjJDgN0Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab4dbc042269" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>