<?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[Jool Software Professionals - Medium]]></title>
        <description><![CDATA[We are explorers in the world of web technology. We ♥ to share our discoveries with the community. We are Jool Software Professionals. https://jool.nl - Medium]]></description>
        <link>https://medium.com/joolsoftware?source=rss----5317e4a37e7e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Jool Software Professionals - Medium</title>
            <link>https://medium.com/joolsoftware?source=rss----5317e4a37e7e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:08:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/joolsoftware" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Increasing RxJS Insight by Writing a TypeScript Transformer]]></title>
            <link>https://medium.com/joolsoftware/increasing-rxjs-insight-by-writing-a-typescript-transformer-eec766f392e?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/eec766f392e</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Roy Touw]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 10:23:00 GMT</pubDate>
            <atom:updated>2020-09-14T12:27:18.015Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZaiPCSCCM-mV542" /></figure><p>Asynchronous code is hard to grasp and using RxJS is no exception. Having multiple parallel processes and plenty of data flowing through your application, it’s often difficult to understand what’s happening when, why and how. The desire to increase the insight in this everchanging state of these programs raised the question of how to extract knowledge from a running program <strong>without manually logging</strong> every line of code.</p><p>TypeScript transformers might be the solution for this and other problems alike. Using TypeScript Transformers one can <strong>extend the behaviour</strong> of certain programs <strong>in an automated manner</strong>. In this article, I will describe <strong>how to write such a TypeScript transformer</strong>.</p><h4>Prerequisites</h4><ul><li>This article will dive into writing a TypeScript transformer but won’t cover implementing a TypeScript transformer in your project, <a href="https://medium.com/joolsoftware/custom-typescript-transformers-with-angular-cli-7f4150797e05">read this article by David Kingma to learn more about injecting a TypeScript transformer into an Angular project.</a></li><li>The abstract syntax tree(AST) being such a central concept in transforming TypeScript programs it would help to understand this article having a basic understanding of either parse trees or AST’s. <a href="https://medium.com/basecs/leveling-up-ones-parsing-game-with-asts-d7a6fc2400ff">A great introduction by Vaidehi Joshi can be read here</a>.</li><li>A basic understanding of RxJS will help to understand the code snippets but is not required.</li></ul><h4>Introduction</h4><p>In this article, I will describe a way to write a TypeScript transformer to <strong>replace RxJS nodes</strong> in a program without altering the original behaviour. The purpose of this transformer is to <strong>collect and send metadata</strong> to a GUI application, enhancing the realtime insight for a given developer. This article will focus on the writing aspects of a TypeScript transformer, and not on RxJS itself. The simplified structure of the transformer is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*tjETAjMxFrjm8ACEBJHf4w.jpeg" /><figcaption>The general structure of the TypeScript transformer.</figcaption></figure><p>The topics covered in this article are:</p><ul><li>AST Traversal</li><li>Node Classification</li><li>Generating Metadata</li><li>Replacing Nodes</li><li>Replacement Functions</li></ul><h4>AST Traversal</h4><p>The input for a TypeScript transformer is a program consisting of multiple source files. Each source file comes in the form of an AST, populated with nodes.</p><p>The first step in the process of transforming a TypeScript file is deciding which parts of the programs require to be mutated, thus which nodes of the AST should be affected.</p><p>The first step in this process is traversing over every node and passing it to a dispatch function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2a6447b483fe18e568deb78801f1783/href">https://medium.com/media/d2a6447b483fe18e568deb78801f1783/href</a></iframe><p>Inside the dispatch function, each node is first classified. Depending on the classification, a node is transformed by the appropriate function or returned unchanged.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/148f55fa499321016cae7cdc3202227b/href">https://medium.com/media/148f55fa499321016cae7cdc3202227b/href</a></iframe><h4>Node Classification</h4><p>To classify a node, and to make sure it is a certain part of an RxJS statement a collection of classifier functions are used. Each classifier will look at both the structure and the contents of a node.</p><p>In the code snippet below, the isObjectOrSubjectConstructor function is shown. This function classifies RxJS object and subject construction statements; e.g.</p><pre><em>new Observable&lt;number&gt;();</em></pre><p>Without looking at the structure of a node, invalid classifications will be made. For example, the following comment should <strong>not</strong> be transformed.</p><pre>//new Observable&lt;number&gt;();</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2521572c69636f7fff31a824cf9c5320/href">https://medium.com/media/2521572c69636f7fff31a824cf9c5320/href</a></iframe><p><a href="https://astexplorer.net/">A great tool for assistance with writing the classifier functions is AST Explorer.</a> This tool helps by creating an AST representation for given TypeScript code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WyuVnKrut2FGSgsup0CavQ.png" /><figcaption>AST Explorer from <a href="https://astexplorer.net/">astexplorer.net</a></figcaption></figure><h4>Unit Testing</h4><p>Another great tool of <strong>assistance</strong> during the development of a TypeScript transformer are unit tests. Using unit tests prevents having to compile a complete project using the transformer <strong>saving a lot of time</strong> in the long run.</p><p>To make the unit testing of functions acting upon TypeScript nodes less of a struggle I’ve created some helper functions. The <em>createNode function </em>creates an AST from a given code snippet in string format and the <em>printNode </em>function converts a node back into a string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b9f63dfe6f50060b4a2993d7ec8b5ec/href">https://medium.com/media/4b9f63dfe6f50060b4a2993d7ec8b5ec/href</a></iframe><p>Using the <em>createNode</em> function enables the ease of unit testing as shown below, greatly aiding development.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f2c251d6d5f929afef54d66709ced0/href">https://medium.com/media/42f2c251d6d5f929afef54d66709ced0/href</a></iframe><h4>Generating Metadata</h4><p>Once a node is classified as part of an RxJS statement the metadata for this part of the expression must be generated. The extraction of metadata from a node is for the biggest part fairly straightforward.</p><p>In my case, I’ve collected the file, line and position of the node, generated a UUID and collected the UUID’s of connected observables, pipe operators and subscribers. This was enough data to visualise a graph of the observable structure in the GUI.</p><p>For things like fetching the identifier belonging to a given observable, it’s key to take a look at the AST Explorer tool yet again. Based on the structure of an AST for a given RxJS statement, a recursive algorithm can be constructed to traverse to the identifier node starting from the observable node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93eadff4de7aadce6dff6429647fb1e6/href">https://medium.com/media/93eadff4de7aadce6dff6429647fb1e6/href</a></iframe><p>It’s important to remember that the transformer performs its magic <strong>during compilation</strong>, while the metadata must be sent to the GUI application during run-time. The reason being the desired result is a <strong>dynamic analysis</strong> of a program, not a static analysis.</p><p>To reach this desire the metadata is stored in the AST. Because a normal object literal can not be stored in the TypeScript AST, a TypeScript object literal must be created for it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/487fe2645f7e2165677812ce021f005a/href">https://medium.com/media/487fe2645f7e2165677812ce021f005a/href</a></iframe><h4>Replacing Nodes</h4><p>Now the nodes are classified and the according metadata is generated, the nodes must be replaced. The goal of this part of the transformer is to replace classified nodes containing parts of the RxJS statements in a fashion where the original behaviour as intended by the programmer is unaltered, but the generated metadata will be collected and sent to the GUI application.</p><p>This will be done by replacing RxJS statements with a wrapped version, for example:</p><pre>new Observable&lt;number&gt;();</pre><p>will be replaced with:</p><pre>wrap(metadata)(new Observable&lt;number&gt;());</pre><p>Upon execution, the <a href="https://javascript.info/currying-partials">curryable</a> wrap function will send the metadata and return the observable construction to the program. In this way, the normal execution of the program will continue as if nothing has been changed by the transformer.</p><p>The following code snippet creates a nested call expression node, resulting in the call of a curried function call as seen in the previous code snippet. The original node, together with the metadata and a specific <em>sendMessage</em> identifier function, is passed along as arguments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f07dd095dd74c2b12cc34d4521f6eb75/href">https://medium.com/media/f07dd095dd74c2b12cc34d4521f6eb75/href</a></iframe><p>As seen in the above example the <em>touch</em> function is called upon the original node. This is required because of the way the AST is traversed during transformation. The original node is replaced with a <em>wrap </em>node, containing the original node as a child node. Without the touch function, this original node will be replaced by a <em>wrap </em>node on every repeating occurrence, <strong>triggering an infinite loop</strong>. By marking a node as touched, the dispatcher will have the knowledge this node is already transformed preventing it from sending it off to be transformed again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*d4mAvZ08dC8tl3Po.png" /><figcaption>Tree data structure top-down traversal.</figcaption></figure><h4>Importing Functions</h4><p>The replaced node is a function call to a function originally not existing in the program. The problem this raises is its <strong>reference</strong> is unknown. To solve this issue the transformer must add the required import statements to the transformed files.</p><p>As you might have seen inside the AST Traversal code snippet earlier, a <em>Set </em>of <em>RxJSParts </em>is created during the traversal of a source file.</p><pre>const imports = new Set&lt;RxJSPart&gt;();</pre><p>Upon each dispatch of a node, the classification is added to this set, utilizing the property of a <em>set </em>only to store unique values. After finishing visiting every node of the AST, this set of classifications is handed over to the <em>importer</em>. The <em>importer </em>creates the appropriate set of import declaration nodes and adds them to the AST recursively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8efd42fd1e026e59f4bd09bf0ba90295/href">https://medium.com/media/8efd42fd1e026e59f4bd09bf0ba90295/href</a></iframe><h4>Replacement Functions</h4><p>The last step in writing a TypeScript transformer is creating the replacement functions. In some cases this as simple as sending the metadata and returning the original code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af74e875f06d2259e055bfeba81f0937/href">https://medium.com/media/af74e875f06d2259e055bfeba81f0937/href</a></iframe><h4>Final Result</h4><p>As can be seen in the final result below, a lot of metadata has been injected in the code. All this metadata plus some metadata generated during run-time is sent to the application containing the GUI for graphical analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sr-hPF4Zs4z1m0aOm8V5Wg.png" /><figcaption>Left: Original Code, Right: Transformed Code.</figcaption></figure><p>The application consuming all this metadata will be covered in a future article. I hope this article presented some insight into the difficulties surrounding the writing of a TypeScript Transformer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eec766f392e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/increasing-rxjs-insight-by-writing-a-typescript-transformer-eec766f392e">Increasing RxJS Insight by Writing a TypeScript Transformer</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a custom FormControl in Angular]]></title>
            <link>https://medium.com/joolsoftware/creating-a-custom-formcontrol-in-angular-da92f2f47733?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/da92f2f47733</guid>
            <category><![CDATA[form-controls]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[controlvalueaccessor]]></category>
            <category><![CDATA[putin]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jasper Fioole]]></dc:creator>
            <pubDate>Thu, 16 Apr 2020 09:08:36 GMT</pubDate>
            <atom:updated>2020-04-16T09:08:36.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HqzstDzsw7lWCg_fYVBYwg.png" /></figure><p>Most apps require some sort of user input through forms. Html provides some form inputs like textfields, textareas, checkboxes, buttons and so on. Some apps require additional input types, for example: a datepicker, a userpicker or something like a counter field with a minus and plus button. We could add additional code to the form it self to make it working, but this isn’t an optional approach, we should prevent redundancy and make a reusable component.</p><p>Angular provides two different approaches to handle user form input: reactive and template-driven. In this post I’ll use reactive forms to handle the user input. I’ll show you how to create a custom input field using Angular components and the ControlValueAccessor interface.</p><p>In this example we will create a simple form to order drinks, this form contains a custom input that can be increased/decreased using a plus/minus button.</p><p>You can find more about Angular forms <a href="https://angular.io/guide/forms-overview">here</a>.</p><h3>Setup an Angular app</h3><p>First lets create an Angular app using CLI (routing is not required, I used SCSS for styling).</p><pre>ng new order-app</pre><p>We’re going to use the ReactiveFormsModule , you can add it to the imports section of the app.module.ts .</p><p>Don’t forget to add the import.</p><pre>import { ReactiveFormsModule } from &#39;@angular/forms&#39;;</pre><h3>Create a simple form</h3><p>Let start by replacing all content of app.component.html with a simple form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c5a8e3131be038653d7e58a216d5dc7/href">https://medium.com/media/6c5a8e3131be038653d7e58a216d5dc7/href</a></iframe><p>This form contains a few inputs to submit an order. At the bottom of our page we can use the json pipe to see what values our form contains.</p><p>We have to update our app.component.ts file as well, in this file we added a factory method createForm which contains a definition of our form fields.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bb3bc55e708aaf8c95d8860799380d3/href">https://medium.com/media/5bb3bc55e708aaf8c95d8860799380d3/href</a></iframe><p>Let’s not forget the SCSS.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/895c0f44b0f8f67312c1b8aa69efca31/href">https://medium.com/media/895c0f44b0f8f67312c1b8aa69efca31/href</a></iframe><p>Using this form works fine, when typing you can see the json changing on the bottom of the page.</p><p>Currently we have tree number fields for taking our order. This is fine, but I would like users to press on a plus/minus button to increase/decrease the value of the input field.</p><h3>Create a custom component</h3><p>Let’s start by creating a folder called components in the src/app/ folder.</p><p>In this folder we can run an Angular CLI command to generate a curstom component.</p><pre>ng generate component counter-input</pre><p>First, let add an input to show a number and two buttons, one for decrease and one for increase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31196ca9deab9ce6bd419708c262d89d/href">https://medium.com/media/31196ca9deab9ce6bd419708c262d89d/href</a></iframe><p>As you can see we created two methods, one for increase and one for decrease. Let’s create the counter-input.component.ts code now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abee2522d2d6925a528c66d0d1d7eaff/href">https://medium.com/media/abee2522d2d6925a528c66d0d1d7eaff/href</a></iframe><p>We defined an a max and min input so users can set a min/max value. The value property houses the current value of our component. Inside the increase/decrease we check if a value is specified, if so and the value is within the acceptable range we can raise/lower the value of our component.</p><p>We have to add some simple SCSS as well to make our component look a bit prettier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2147eac513b240290b60875cfca122b/href">https://medium.com/media/f2147eac513b240290b60875cfca122b/href</a></iframe><h4>Implement the ControlValueAccessor</h4><p>A ControlValueAccessor allows us to use our custom component as a form input. This allows us to add additional attributes to our component like FormControlName .</p><p>The ControlValueAccessor will require us to implement a couple of methods to our counter-input.component.ts class. The interface looks like this.</p><pre>interface <a href="https://angular.io/api/forms/ControlValueAccessor">ControlValueAccessor</a> {   <br>   <a href="https://angular.io/api/forms/ControlValueAccessor#writeValue"><strong>writeValue</strong>(obj: any): void</a>   <br>   <a href="https://angular.io/api/forms/ControlValueAccessor#registerOnChange"><strong>registerOnChange</strong>(fn: any): void</a>   <br>   <a href="https://angular.io/api/forms/ControlValueAccessor#registerOnTouched"><strong>registerOnTouched</strong>(fn: any): void</a>   <br>   <a href="https://angular.io/api/forms/ControlValueAccessor#setDisabledState"><strong>setDisabledState</strong>(isDisabled: boolean)?: void</a> <br>}</pre><blockquote>Angular describes the ControlValueAccessor as: Defines an interface that acts as a bridge between the Angular forms API and a native element in the DOM.</blockquote><p>The Angular Docs are available <a href="https://angular.io/api/forms/ControlValueAccessor">here</a>.</p><p>In addition to the just implemented methods we have to define a few additional methods and attributes. Let’s define a method for onChange and onTouched , I’ll explain the need of those methods/attributes later on.</p><pre>onChange: any = () =&gt; {};<br>onTouched: any = () =&gt; {};<br>disabled = false;</pre><p>Using a FormControl in your application allows you to disable/enable your controls programmatically. FormControls register user interaction, like when a user touched a control or changed its value. Using the ControlValueAccessor interface allows u to tell our component what to do when code of a user interacts with our custom input. Let’s have a look at the newly implemented methods and let them actually do something.</p><p>First lets edit the writeValue method, by default the parameter is named obj and typed any, in our case we want this to be called value and typed number. With this method we will simply change the value of our component.</p><pre>writeValue(value: number): void {<br>   this.value = value;<br>}</pre><p>Now let’s register the onChange and onTouched methods as defined before. These methods can be used to tell ReactiveForms when your component is changed or touched.</p><pre>registerOnChange(fn: any): void {<br>   this.onChange = fn;<br>}</pre><pre>registerOnTouched(fn: any): void {<br>   this.onTouched = fn;<br>}</pre><p>After registering the methods we should assign the disabled attribute.</p><pre>setDisabledState?(isDisabled: boolean): void {<br>   this.disabled = isDisabled;<br>}</pre><p>We would like our component to emit a change event after a button is pressed, we can simply do this by calling a just registered method.</p><pre>increase() {<br>   if (typeof this.max === &#39;undefined&#39; || this.value &lt; this.max) {<br>      this.value++;<br>      this.onChange(this.value);<br>   }<br>}</pre><pre>decrease() {<br>   if (typeof this.min === &#39;undefined&#39; || this.value &gt; this.min) {<br>      this.value--;<br>      this.onChange(this.value);<br>   }<br>}</pre><p>After implementing all the code we need, we have to make sure that the ControlValueAccessor is provided to our component. We can do this by adding the following code to the @Component decorator.</p><pre>providers: [<br>   {<br>      provide: NG_VALUE_ACCESSOR,<br>      useExisting: forwardRef(() =&gt; CounterInputComponent),<br>      multi: true<br>   }<br>]</pre><blockquote>We need to use a forwardRef here, because the CounterInputComponent is not yet defined. It will be defined later on. More information about forwardRef can be found <a href="https://angular.io/api/core/forwardRef">here</a>.</blockquote><p>Our counter-input.component.ts file should look something like this now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f191edeaddc0242f74072572b92b2f7a/href">https://medium.com/media/f191edeaddc0242f74072572b92b2f7a/href</a></iframe><p>The only thing left for our component is updating the html. All we have to do is letting our elements know when the FormControl is disabled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13dd82c84c6366b5a3232a22dc810847/href">https://medium.com/media/13dd82c84c6366b5a3232a22dc810847/href</a></iframe><h3>Updating the form</h3><p>The only thing left to do is updating the form with our custom component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54d699e3e22b78d7194d3370a2e89326/href">https://medium.com/media/54d699e3e22b78d7194d3370a2e89326/href</a></iframe><p>When creating the form we added two inputs, one for min and one for max. You could add these here if you would like to use those.</p><h3>All done!</h3><p>Great, we are all set! The final result of our application will look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*CgQS6a0TC79nl2-GWW9vmA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da92f2f47733" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/creating-a-custom-formcontrol-in-angular-da92f2f47733">Creating a custom FormControl in Angular</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular pre-rendering: Scully.io vs Angular Universal]]></title>
            <link>https://medium.com/joolsoftware/angular-pre-rendering-scully-io-vs-angular-universal-6f026150f341?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/6f026150f341</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[scully]]></category>
            <category><![CDATA[angular-universal]]></category>
            <category><![CDATA[pre-rendering]]></category>
            <category><![CDATA[static-site]]></category>
            <dc:creator><![CDATA[Jasper Fioole]]></dc:creator>
            <pubDate>Wed, 18 Mar 2020 13:43:32 GMT</pubDate>
            <atom:updated>2020-03-19T13:33:45.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqD1snztX5dbRPshFTvjpQ.jpeg" /></figure><p>In some cases you want your angular app to be pre-rendered. Pre-rendering your app can hugely improve the performance of your app. It doesn’t require any client side rendering on the users computer because it is already rendered. If all html of your app is pre-rendered it doesn’t require javascript to show the html. Robots/crawlers don’t use javascript so pre-rendering your app will highly optimize your app for search engines such as Google.</p><p>This can be achieved in a few ways, in this article I’m going to show you how to do this using Angular Universal (SSR) and Scully.io. Afterwards we can compare both techniques and tell them apart.</p><p><strong>Introduction to Angular Universal</strong><br>You might be familiar with Server Side Rendering(SSR) using Angular Universal, but in some cases you’d like your app to pre-render some pages. In this post, I’m going to explain how to use Angular Universal and Angular 9 for pre-rendering.</p><p>You can find the Angular Universal documentation over <a href="https://angular.io/guide/universal">here</a>.</p><p><strong>Introduction to Scully.io</strong><br>Since a few months a committed group of people started working on Scully.io, the open source project is available for everyone to use. The past month I worked closely with the Scully team to provide feedback to improve the library. I’m going to show you how to use Scully.io for your project.</p><p>Scully.io relies on the Angular build process, you can only run Scully after your app was built by angular. Scully will serve the app that was built by Angular and will convert this to a pre-rendered version of the app.</p><p>You can find the Scully.io documentation over <a href="https://github.com/scullyio/scully/blob/master/docs/scully.md">here</a>.</p><h3>Creating an angular app</h3><p>This step is equal for Angular Universal Pre-rendering and Scully.io. If you’d like to add pre-rendering to an existing app you can skip this section. Before starting make sure you are using the right angular version. You can check this using the following command.</p><pre>ng --version</pre><blockquote>Angular Universal Pre-rendering requires Angular 9+<br>Scully.io requires Angular 8+</blockquote><p>In my case I’m using Angular version <strong>9.0.4</strong>. <br>Now lets start by creating a new app using the Angular CLI, you can name your app whatever you like, I’ll stick with static-app .</p><pre>ng new static-app</pre><p>Make sure routing is enabled during the creation of the app.</p><h3>Adding content for testing</h3><p>If you are working on an existing app you can skip this part.</p><p>Before pre-rendering the app we can create some pages to see how it works. Let’s start by adding a simple folder structure.</p><pre>cd src/app/ &amp;&amp; mkdir components &amp;&amp; cd components/</pre><p>Now we can create some components which we can use to test the pre-rendering. In this example I’ll generate two components using CLI.</p><pre>ng generate component page-one --skip-import</pre><p>And the second one.</p><pre>ng g c page-two --skip-import</pre><blockquote>Note: when generating the components we need to add <em>--skip-import</em> to the command. Because we are using these components as pages, we will declare those inside the router. If needed you can add them to a module later on.</blockquote><p>After generating our pages we have to add the components in the routes file. In our project we can update the app-routing.module.ts to make our pages accessible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1f274182ffa41d54f726eecb0aa3a8e/href">https://medium.com/media/d1f274182ffa41d54f726eecb0aa3a8e/href</a></iframe><h4>Update the AppComponent</h4><p>Simply replace the content of app.component.html with the html listed below. This will make it easier to see if everything works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd4f6908f3359361cadf3410f2509acc/href">https://medium.com/media/dd4f6908f3359361cadf3410f2509acc/href</a></iframe><p>Our example app is just for demonstration purposes so we’ll will keep the styling default.</p><h3>Angular Universal (SSR) Pre-rendering</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*A-rmoQCGTSQYHUeOpAst1A.png" /></figure><p>Now we can add Angular Universal to an existing app, this can be the app we’ve created above or another app.</p><p>To start using server side rendering we have to add the Angular Universal schematics. We can do this by executing an CLI command.</p><pre>ng add @nguniversal/express-engine</pre><p>Adding the schematics updates the angular.json as well, we can use this later on to define which pages we want to have pre-rendered.</p><h4>Defining what to pre-render</h4><p>As stated before, Angular Universal added a few things to our angular.json as well. Open the file and look for the prerender section and update the routes array to your liking. If you followed the example in the previous part of this article you can add the one and two routes here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b887001f3bb734cc4e86a180d2c2a4d5/href">https://medium.com/media/b887001f3bb734cc4e86a180d2c2a4d5/href</a></iframe><h4>Dealing with dynamic routes</h4><p>If your app does not include dynamic routes you can skip this part.</p><p>Some apps use routes with parameters, the guess parser is unable to detect the dynamic routes automatically, so how do we solve this. Angular Universal provides two solutions for this, we could append all undetected routes to our CLI command. This is not optimal, but there is an alternative. We could create a routes file and pass it to the pre-rendering process (we’ll look into this later on in this article).</p><blockquote>guess-parser contains a collection of parsers which can statically analyze our Angular application to discover how the routes from the analytics source map to JavaScript bundles.</blockquote><p><strong>Updating our example</strong><br>Let’s add an additional component to our example.</p><pre>ng generate component page-three --skip-import</pre><p>After creating our component we need to update the routes of our app to the following (don’t forget to update the imports).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/343073060846fb977fc9b86029d2179e/href">https://medium.com/media/343073060846fb977fc9b86029d2179e/href</a></iframe><p>In our example it wasn’t necessary to add our previous pages to a module (because we didn’t use anything from another module), in PageThreeComponent we would like to use a few things from other modules so make sure you add it to the declarations section in the app.module.ts .</p><p>We’d like to use the CommonModule so make sure it is imported in the app.module.ts as well.</p><p>First lets update the code of our PageThreeComponent , we’ll start with the page-three.component.ts file. We’ll keep it pretty simple, just to demonstrate that everything is working fine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d987811b25fa85f17ff7652cb10ae83/href">https://medium.com/media/2d987811b25fa85f17ff7652cb10ae83/href</a></iframe><p>Now let’s update our app-three.component.html file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/119cee989397a877e58cdba61d1cbaee/href">https://medium.com/media/119cee989397a877e58cdba61d1cbaee/href</a></iframe><p>At last update the app.component.html with some additional menu items to make it easier to browse trough our app pages.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9c724e36f81908cedbfff27ad316c01/href">https://medium.com/media/d9c724e36f81908cedbfff27ad316c01/href</a></iframe><p><strong>Creating the routes file</strong></p><p>Create a file called routes.txt in the root folder of your project, fill this file with all dynamic routes you want to have pre-rendered. It is not necessary to add static routes because angular already detected those.</p><pre>/three/1<br>/three/2</pre><p>Now we need to update the prerender command in our package.json to use the newly created route file.</p><pre>&quot;prerender&quot;: &quot;ng run static-app:prerender --routesFile routes.txt&quot;</pre><blockquote>TIP: create a (node) script to create and fill the routes.txt file automatically</blockquote><h4>Pre-render the app</h4><p>Use the following npm command to prerender the app.</p><pre>npm run prerender</pre><p>Just like after building an angular app we are able to find the generated files in the dist folder. Now lets see if everything works.</p><p>If you don’t have a http-server installed on your computer you could simply install the http-server npm library for that. Simply run the following command (add -g to install http-server globally).</p><pre>npm i http-server</pre><p>If you installed the http-server inside your project, you can run the following command using npx. If you installed http-server globally just execute it without using npx.</p><pre>npx http-server dist/static-app/browser</pre><blockquote>TIP: view the page source of your app. If everything worked out so far you’ve successfully pre-rendered your app! When a crawler/bot views your app, it won’t use javascript, simply view the page source in your browser to see what is pre-rendered.</blockquote><h3>Creating a Scully app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*SXfXmCg2orphFdHkL9FcCw.png" /></figure><p>Let’s add Scully to an existing app(this can be any angular app using Angular 8+), navigate to the root directory and run the following command.</p><pre>ng add @scullyio/init</pre><p>When using Scully you can choose to use guess-parser to let Scully scan for static routes. This can be achived by adding --scanRoutes to the parser command, this command is shown in the “Pre-render the app” section.</p><h4>Handling dynamic routes</h4><p>If your app does not use any dynamic routes, you can skip this section.</p><p>Scully created a config file in the root folder of our project called scully.&lt;project_name&gt;.config.js , we can use this file to define our dynamic routes.</p><p>When editing this file we can add extraRoutes to the config object to define our routes. In our test project the config file would look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/695b933c222bad7b11174b29c369aeef/href">https://medium.com/media/695b933c222bad7b11174b29c369aeef/href</a></iframe><h4>Pre-render the app</h4><p>To pre-render the app we have to run two command, we’ll start by building our angular app.</p><pre>ng build</pre><p>When our app is built we can run the Scully parser with the following command. We add --scanRoutes to the CLI command to use the guess-parser to automatically detect our static routes, we added our dynamic routes in the previous section.</p><pre>npm run scully -- --scanRoutes</pre><p>The newest version of Scully includes an http-server, after running the command above we can simply open the url listed in the command output. If you’d like to close the server simply type q and hit enter.</p><p>By default Scully adds the pre-rendered site to the static folder inside the dist folder.</p><h3>Scully.io VS Angular Universal</h3><p>Now you know how to pre-render you angular app, well done!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQ81NcsY6YxK7jxnr4v%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQ81NcsY6YxK7jxnr4v%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQ81NcsY6YxK7jxnr4v%2Fgiphy.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/4a87a4b175478fd61872567384509820/href">https://medium.com/media/4a87a4b175478fd61872567384509820/href</a></iframe><p>So lets find out which one to use!</p><h4>Scully.io</h4><p>Setting up a project with Scully is pretty easy, when your app doesn’t use any dynamic routes it is as simple as adding Scully to your project. Adding dynamic routes to your app is pretty simple as well.</p><p>A big advantage of using Scully is the possibility to use json/markdown files as page content. These routes can be detected automatically.</p><p>Scully is still in development (currently Alpha), so it can be buggy. I’ve experienced this a few times during a development project. Some issues might keep you from using Scully in production. Right now when the Scully pre-rendering fails the command will not return an exit code, this means that CI/CD will not detect that the process has failed and deploys a broken app.</p><h4>Angular Universal</h4><p>Angular Universal isn’t new but it got a lot easier. Since Angular 9 we have the possibility to pre-render our pages which is not very difficult.</p><p>A small downside is that we have to define each route that we want to have pre-rendered. This may not be a downside in each project, in some cases you only want to pre-render a few pages, this would make that possible.</p><p>Angular Universal is provided by the official Angular team, because of this and the fact that it was tested by the team and the community as well reduces the chance of bugs.</p><h4>Conclusion</h4><p>The setup for both techniques is pretty simple. Angular Universal requires a bit more setting then Scully.io but this is still manageable.</p><p>You’re probably wondering what technique you should be using for your application. Well, it depends, both techniques works fine. Because Scully is still in a development stage it can be buggy at times. The server that Scully uses to pre-render the website will sometimes crash or get stuck. When the build process fails there is not exit code returned so CI/CD will deploy a broken app on failure. This maybe gets better in future while they keep developing the library.</p><p>If you want to create an app that contains articles (i.e. news/blog), Scully can be an awesome technique to use, cause it can convert markdown files to dynamic pages. If you want to do the same in an Angular Universal app you’ll have to add this conversion yourself.</p><p>If you are planning on using pre-rendering for a production app you are probably safer using Angular Universal. Scully.io looks very promising, so I’ll follow their journey and see what the future brings us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f026150f341" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/angular-pre-rendering-scully-io-vs-angular-universal-6f026150f341">Angular pre-rendering: Scully.io vs Angular Universal</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internationalizing an Angular 8 app using Firebase and POEditor]]></title>
            <link>https://medium.com/joolsoftware/internationalizing-an-angular-8-app-using-firebase-and-poeditor-2b2c559f5629?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/2b2c559f5629</guid>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[internationalization]]></category>
            <dc:creator><![CDATA[Jacob Jonkman]]></dc:creator>
            <pubDate>Fri, 07 Feb 2020 13:02:12 GMT</pubDate>
            <atom:updated>2020-02-07T12:56:03.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*tIq3I93HnoU43hiHqXoj2Q.jpeg" /></figure><p>When developing a web application, at some point someone might conclude that it would be nice to allow users to use your application in multiple languages. By changing an option in some options menu, or maybe by clicking a link, the site should load a different language and show the user its preferred language. On paper, this sounds pretty simple. However, as is most often the case in software development, beneath the surface are a lot of intricacies that can lead to headaches if not appropriately handled. This blogpost is the culmination of my headaches over the past year or so trying to integrate an Angular project with translations from POEditor.</p><h3>The basic premise</h3><p>Consider the case where you have an application that has to be translated. How can you make all of your markup translatable? Fortunately, Angular already has a solution for this, called Angular i18n. An in-depth guide about how this works can be found <a href="https://angular.io/guide/i18n">here</a>, we will assume the reader has some knowledge about how this works.</p><p>After marking all text that has to be translated with i18n directives and running ng xi18n, we end up with an XLF file containing all translatable strings in our project, which looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94a9bfadada68ad7442b3cf6cca13261/href">https://medium.com/media/94a9bfadada68ad7442b3cf6cca13261/href</a></iframe><p>In order to translate this file, the Angular team suggests you make a copy of this file for each language you want to support and send the file to the person who will translate the terms for you. This might work when localization has to be added to a fully finalized application, but when a web app is still subjective to change, sending such files to all translators whenever textual changes happen would be too much of a hassle. We don’t like hassles. Therefore, we decided to look for a tool which could streamline this process for us. After some research, we ended up choosing <a href="http://poeditor.com/">POEditor</a>.</p><p>POEditor is an online tool in which we can define our translatable strings and assign contributors to provide the translations for each language. To begin, we make a new account. For the sake of this tutorial, a free account is satisfactory. With this account, we can store up to 1000 strings, which is plenty for now. However, do note that if you plan to use this tool for a real project, this number is quickly exceeded, which means that you will have to pay for it. After we have registered an account, we can create our translation project. From the projects page, click the “Add new project” button, enter a name and description, and click on “Add”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CgcGw_TYYTVv37CcBTUHjg.png" /></figure><p>The first thing to do for a new project, is to select the languages in which you want your app to be translated. Simply click “Add language” and select one from the dropdown list to do this. After we are done, we can import our messages.xlf file in our project by clicking on the ‘Import Terms’ button. After selecting our messages.xliff file (note that ng xi18n produces a file called messages.xlf, which you have to manually change to messages.xliff for POEditor to accept the file), we have some options for importing. First, you can either choose to import just the terms, in which case the translations of all languages will be left blank, or you can choose to also use your terms as the translations for a specific language. For example, when your web app is written in English, we can import the terms to be the English ‘translations’ of the terms in our project. We also have the option to overwrite all existing translations (which should not be done lightly), and to mark new or obsolete terms with a certain label. After we hit import, we will be notified of how many strings are updated, as well as a list of all terms which have become obsolete after the import. This list can be used to delete these unused translations, but care should always be taken that the old translations are not still useful. I18n also offers support for pluralizations, which work without a problem with POEditor.</p><p>After importing the terms, translators should be notified and granted access to the project to allow them to do their work. Accounts can be given contributor privileges to a specific language, meaning that they can only change translations for that specific language. When the translations are done, we can export the translations of each language separately, in which case the name of the file will signify which language it belongs to. For example, exporting the French translations of our project will result in a file called messages.fr.xliff. These files can then be used to build separate versions of your website for each language you want to support (see later for a command how to do this).</p><h3>Translating dynamic values</h3><p>Up to this point, everything sounds simple enough. However, there are a few problems one might encounter when doing this. First off, we might define strings in the class of a component, which are then used in the template of the component through string interpolation. What happens when we try to translate this? Consider the two files below. An array called colors is defined in the class definition, which are then used in the template file to generate a table structure. There are also two buttons which allow us to change our language. Adding an i18n directive to the &lt;td&gt; element will not result in the color names being extracted by `ng xi18`, since this tool is only able to statically analyze components. If the term cannot be extracted from your project, it will also not be translated. Instead, we can define a custom pipe which can handle the translation for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcfcbff64ed89eceb59938267b7d43c5/href">https://medium.com/media/fcfcbff64ed89eceb59938267b7d43c5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8f899f1a8725fbdaf7f1820d5825bb0/href">https://medium.com/media/c8f899f1a8725fbdaf7f1820d5825bb0/href</a></iframe><p>The <strong>translate</strong> pipe accepts two arguments next to the translatable term: the language to translate to, and the translation table where the translation can be found. This pipe will take the current color, do some pre-processing on the input term and then hands it over to a custom TranslationService which will do the actual translation. We will be using Firebase Realtime Database to store our translations. In-depth tutorials about Firebase and how to set it up can be found elsewhere.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0631e9e273886d94853942d331ac2973/href">https://medium.com/media/0631e9e273886d94853942d331ac2973/href</a></iframe><p>This TranslateService will do the actual work. For example, to translate ‘blue’ to French, this service selects the translations on the path translations/color/blue and then returns the French translation that is specified there, if it exists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c6997404b2c6a6ef5589840b660cbdc/href">https://medium.com/media/7c6997404b2c6a6ef5589840b660cbdc/href</a></iframe><p>We now need a way to extract these translatable strings from our project to import them in POEditor. Unfortunately, as far as I know, there is not really a good way to do this automatically, so we will have to do this manually. However, we can implement functionality in our translation service which detects missing translations and notifies us of this. For example, records can be written to our database signaling when a certain term could not be translated. This also helps to find bugs when for example we made a spelling error when adding our colors to POEditor, causing the translation service to look for the color ‘blue’ while we have only defined the color ‘bleu’.</p><p>In order to keep some structure in this process, we will define a new POEditor project for each category of translations that we have in our project. For example, we might want to translate colors, countries and dog breeds, so we will define three new POEditor projects: <strong>Colors</strong>, <strong>Countries</strong> and <strong>Dog-Breeds</strong>, in which we add the terms that we want to translate manually. After the translators are done, we also need a way to extract these translations from POEditor into Firebase. Luckily, POEditor also has an API which we can use for this. Using this API, we can automatically loop over the POEditor projects and write translations to our database.</p><p>First off, we need to get an API key for our POEditor account. This can be found under <strong>Account Settings &gt; API Access</strong>. Next, we need the ID of our Firebase project in order to write to it. Place both of these in a new file (do not commit them to Git), and import these in your script. Then, go to your Firebase project and go to <strong>Settings &gt; Service Account</strong> and click on the button ‘Generate new private key’. Place the downloaded file in the same directory as your script file, and also keep it away from Git. Next, it is a good idea to define a list of blacklisted projects (consisting of {name, id} objects), which will not be read by the script, and add your main translations project to this list. Else, all of the terms in your main translation project will also be written to Firebase, which we do not want. Finally, we need to define how our HTTP requests will be handled. We will only use the API endpoints to list projects, languages per project and terms per language, so only these three have to be defined. This is shown in the code snippet below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5871a3a792f5b9bf51e0876cb728efea/href">https://medium.com/media/5871a3a792f5b9bf51e0876cb728efea/href</a></iframe><p>Now we can start writing our script. First, we need to setup everything for our script, and then select all projects in our POEditor projects list that are not blacklisted, and return a list of projectNames and project IDs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01aefea0b7bb5c1e9ff3abcfb5a28975/href">https://medium.com/media/01aefea0b7bb5c1e9ff3abcfb5a28975/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b600fc8fd2a9b6f015dae8bd8f990eac/href">https://medium.com/media/b600fc8fd2a9b6f015dae8bd8f990eac/href</a></iframe><p>Then, pass this list of projects to writeTranslationsPerProject, which looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b123f28d177872bfc11531adea8e74a/href">https://medium.com/media/8b123f28d177872bfc11531adea8e74a/href</a></iframe><p>This function calls constructTranslationsperLanguage() for each project, which prepares a JSON object of translations, and then writes it to our database. Afterwards, we automatically stop the process since it would otherwise keep running indefinitely.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07d6d38d3e686cc41144a4957e435943/href">https://medium.com/media/07d6d38d3e686cc41144a4957e435943/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52c0177ca85393587167824a8307d03d/href">https://medium.com/media/52c0177ca85393587167824a8307d03d/href</a></iframe><p>Note the encodeAsFirebaseKey function. Object keys in Firebase realtime database are not allowed to contain certain characters like commas and full stops. In order to still allow terms to contain these characters, we can escape them as is done here. We could also have used something like encodeURI() or encodeURIComponent(), but since these functions do not encode full stops and encode more characters than are strictly necessary here, we have chosen to encode our strings manually. When the script is finished running, all translations should be written to your Firebase database.</p><h3>Markup in translatable strings</h3><p>Going back to the component in the last section, you might have noticed the following part:</p><p><strong>&lt;tr i18n&gt;&lt;td&gt;Original&lt;/td&gt; &lt;td&gt;Translated&lt;/td&gt; &lt;/tr&gt;</strong></p><p>If we run ng xi18n, this will result in the following entry in our messages.xlf file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb11466c599bd2c7a9335b8f6fabe21b/href">https://medium.com/media/cb11466c599bd2c7a9335b8f6fabe21b/href</a></iframe><p>Angular is denoting here that the source string contains HTML markup, which is useful since we do not want to lose this information. However, we run into a problem when we try to import this file into POEditor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wR-xQg6aNUqymwD9cJcEVw.png" /><figcaption>Result of importing messages.xlf in POEditor</figcaption></figure><p>As you can see, the information about the enclosing markup has been omitted. POEditor is a general purpose translation tool which simply does not support Angular’s xliff format as extensively as it could. This problem could be circumvented by splitting strings like this one in multiple smaller strings until no nested HTML tags are left. However, often the context in which a certain text appears matters for the translator, and splitting every piece of text in small substrings could mean that the translators will not be able to correctly judge what the context of a string is. We therefore need a better way to do this.</p><p>Luckily, this problem can be solved relatively easily by escaping the &lt; and &gt; of the &lt;x&gt; tags. When importing terms, POEditor ignores everything that is between &lt;&gt; characters, but will add everything without a problem if we escape these characters before importing the terms. This can be done using the following script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f3835237b6516cfbf487d4f3b9153a7/href">https://medium.com/media/9f3835237b6516cfbf487d4f3b9153a7/href</a></iframe><p>Afterwards, we can import the resulting xliff file to obtain the following strings in POEditor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqEIxr0q568xHxLnrEOU8A.png" /><figcaption>Escaped strings in POEditor</figcaption></figure><p>Great stuff, our HTML is saved! When exporting the translations of the resulting POEditor project, we also need to unescape these same strings. This can be done with the following script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39d10e52643266fe0e29f597e11a2fa8/href">https://medium.com/media/39d10e52643266fe0e29f597e11a2fa8/href</a></iframe><p>This script reads the exported translations.xlf file for each language that is defined in the languages array, and rewrites the translation lines containing <strong>&amp;lt;x some-more-text &amp;bt; </strong>to <strong>&lt;x some-more-text&gt;, </strong>after which the result is written back in the appropriate translation file.</p><p>Both scripts can be run by first compiling it using <strong>tsc path-to-file &amp;&amp; node path-to-compiled-file</strong>. Afterwards, the resulting files can be used when building the app for different languages. For example, to build the French version of this demo app, we would run:</p><p><strong>ng build — output-path=dist/fra — aot — configuration=config-alias — base-href /fra/ — i18n-file=src/i18n/messages.fra.xlf — i18n-format=xlf — i18n-locale=fra</strong></p><p>If we then deploy to firebase, we can access the French version of our site by browsing to &lt;name-of-app&gt;.firebaseapp.com/fra.</p><h4>Concluding remarks and looking ahead</h4><p>Angular i18n and POEditor are powerful tools to help us internationalize an application, but there are some problems that should be known and mitigated before starting the internationalization of your Angular app. This week, <a href="https://blog.angular.io/version-9-of-angular-now-available-project-ivy-has-arrived-23c97b63cfa3">Angular 9</a> was finally released. One of its key features is a significant overhaul of how internationalization works, using the new <a href="https://blog.ninja-squad.com/2019/12/10/angular-localize/">@angular/localize package</a>. This package features great stuff like improved build times when building for multiple locales, as well as the possibility to extract strings from Typescript files for translation. This mitigates part of the problem we explored in “Translating dynamic values”, although the problem still exists when the strings are not present in your Typescript files but are for example read from a database. I18n seems to be more developer-friendly in Angular 9, exactly how painless it will be is a topic for a future blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2c559f5629" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/internationalizing-an-angular-8-app-using-firebase-and-poeditor-2b2c559f5629">Internationalizing an Angular 8 app using Firebase and POEditor</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect GitLab with DigitalOcean’s Kubernetes]]></title>
            <link>https://medium.com/joolsoftware/connect-gitlab-with-digitaloceans-kubernetes-439076b9de17?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/439076b9de17</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[app-review]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gitlab-ci]]></category>
            <dc:creator><![CDATA[Chris Smits]]></dc:creator>
            <pubDate>Wed, 24 Apr 2019 08:54:42 GMT</pubDate>
            <atom:updated>2019-04-25T06:36:21.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UL6oWjUgYrSX7c3C3vGgg.png" /></figure><h4>The road towards Review Apps</h4><p>How cool would it be to have a Kubernetes Cluster managed by DigitalOcean and use it to test each branch in your self-hosted GitLab repository separately, as a <a href="https://docs.gitlab.com/ee/ci/review_apps/">Review App</a>? If you want to find out, stick to this blog and we’ll guide you through it step by step.</p><h4>Prerequisites:</h4><ol><li>A <a href="https://cloud.digitalocean.com/">DigitalOcean</a> account</li><li>Knowledge about <a href="https://cloud.digitalocean.com/">DigitalOcean’s</a> dashboard</li><li>Knowledge about <a href="https://docs.gitlab.com/">GitLab</a></li><li>Basic UNIX experience</li></ol><p>Log in or register at <a href="https://cloud.digitalocean.com/">https://cloud.digitalocean.com/</a> and create a new droplet. Choose the GitLab one-click app image and during the setup, add your SSH keys to the droplet. Register a domain or sub-domain, and point it to the IP address of the GitLab instance.</p><h4>Connect to your GitLab droplet</h4><p>To connect to your droplet you need an IP address. You can find your droplet’s IP address in the DigitalOcean dashboard. Open a terminal and type in the following command:</p><pre>ssh root@&lt;DROPLET_IP&gt;</pre><p>You should see Welcome to DigitalOcean&#39;s One-Click GitLab Droplet.</p><h4>Configure the external URL for GitLab</h4><p>In order for GitLab to display correct repository clone links to your users it needs to know the URL under which it is reached by your users, e.g. <a href="https://gitlab.example.com./">https://gitlab.example.com.</a></p><p>By default, when you specify an external_url starting with ‘https’, Nginx will no longer listen for unencrypted HTTP traffic on port 80. If you want to redirect all HTTP traffic to HTTPS you can use the redirect_http_to_https setting.</p><p>Add or edit the following lines in /etc/gitlab/gitlab.rb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/545c09940d88957fbd5b999c1f9bad8b/href">https://medium.com/media/545c09940d88957fbd5b999c1f9bad8b/href</a></iframe><h4>Enable Let’s Encrypt for GitLab</h4><p>Add the following entries to /etc/gitlab/gitlab.rb to enable Let’s Encrypt support for the primary domain:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d8a2c1dad6ce5a71eb631200bc787a/href">https://medium.com/media/05d8a2c1dad6ce5a71eb631200bc787a/href</a></iframe><h4>Reboot your GitLab instance</h4><p>Run sudo gitlab-ctl reconfigure for the changes to take effect.</p><h3>Create a DigitalOcean Kubernetes Cluster</h3><p>DigitalOcean provides a nice way to create a Kubernetes Cluster without manual hassle.</p><ul><li>Go to your DigitalOcean dashboard.</li><li>Create a Kubernetes cluster.</li><li>Download the Kubernetes YAML file at the bottom of the page of your DigitalOcean Managed Kubernetes dashboard and move it somewhere you can find it on your local machine.</li></ul><p>To connect to your Kubernetes Cluster you need to setup kubectl on your local machine with your Kubernetes Cluster YAML config.</p><ul><li>Install kubectl locally (<a href="https://kubernetes.io/docs/tasks/tools/install-kubectl/">https://kubernetes.io/docs/tasks/tools/install-kubectl/</a>) and follow the install instructions for your platform.</li><li>You can either copy the contents of the YAML file directly in the config file in the ~/.kube directory or create an environment variable KUBECONFIG=/path/to/config/file in your ~/.bashrc.</li></ul><h3>Configure Service Accounts in your Kubernetes Cluster</h3><p>In order for GitLab to authenticate with your Kubernetes Cluster we need to create a Service Account. Open a new terminal session and let’s start creating a Service Account!</p><p>First off we need to create a new namespace for GitLab.</p><pre>kubectl create namespace gitlab-namespace</pre><p>Let’s set our context to the newly created namespace so we don’t have to consistently add the --namespace=gitlab-namespace option to the commands.</p><pre>kubectl config set-context $(kubectl config current-context) --namespace=gitlab-namespace</pre><p>Now we are going to create the actual Service Account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81771e0d9cad675d01d96568a3681769/href">https://medium.com/media/81771e0d9cad675d01d96568a3681769/href</a></iframe><pre>kubectl create -f service-account.yml</pre><p>Next up is setting the correct permissions for the gitlab-user in the gitlab-namespace.</p><pre>kubectl create clusterrolebinding gitlab-cluster-admin-binding --clusterrole=cluster-admin --serviceaccount=gitlab-namespace:gitlab-user</pre><p>And</p><pre>kubectl create clusterrolebinding permissive-binding --clusterrole=cluster-admin --user=admin --user=kubelet --group=system:serviceaccounts</pre><h3>Kubernetes dashboard</h3><p>To enter your Kubernetes dashboard you can follow the steps on: <a href="https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/">https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/</a>.</p><p><strong>TL;DR</strong></p><p>Execute the following commands in your terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d762e87cc27c8787c01ac164462fb1/href">https://medium.com/media/58d762e87cc27c8787c01ac164462fb1/href</a></iframe><p>Now setup a proxy to your Kubernetes Cluster.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e5fc909a47fada08ca85428daee23df/href">https://medium.com/media/4e5fc909a47fada08ca85428daee23df/href</a></iframe><p>Use the link below to visit your Kubernetes Cluster:</p><p><a href="http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/#!/overview?namespace=default">http://localhost:8001/api/v1/namespaces/kube-system/services/https:kubernetes-dashboard:/proxy/#!/overview?namespace=default</a></p><h3>GitLab Kubernetes Integration</h3><p>To use your newly created or existing Kubernetes Cluster in GitLab you will need connect it to a project. Go to your project and navigate to Operations/Kubernetes in the sidebar on the left.</p><p>Once you are on the Kubernetes page in GitLab you will see a big green button with the text ‘Add Kubernetes Cluster’. Click on it to continue adding your Kubernetes Cluster.</p><p>You will see a panel with 2 tabs; Create new Cluster on GKE and Add existing cluster. You should go to Add existing cluster since we created ours on DigitalOcean.</p><p>Now it is time to enter your existing Kubernetes Cluster details. You can retrieve this information by performing the following steps in your terminal.</p><p><strong>ProTip</strong>: You should save the details in a file for later use.</p><h4>Get Service Account definition</h4><p>Execute the following command kubectl describe serviceAccounts gitlab-user to get information about the service-account we created earlier. Below is a dump of the result that we got in the terminal, you should see something similar.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b35a4515876ca3fd3a8699e96a40aaa/href">https://medium.com/media/5b35a4515876ca3fd3a8699e96a40aaa/href</a></iframe><p>The things that are important here are the Mountable secrets and Tokens.</p><h4>Get secret definition</h4><p>Execute the following command kubectl describe secret [gitlab-user-token-b468q] to get the token. The result below is something you should be seeing in your terminal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58170a74cca76b8cf1c47af4615fb475/href">https://medium.com/media/58170a74cca76b8cf1c47af4615fb475/href</a></iframe><h4>Getting the token’s certificate</h4><p>We are interested in the token which is base64 encoded. The token has a payload with the certificate in it. Execute the following to retrieve the certificate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a7ac53a4a762c15901f6f121b311373/href">https://medium.com/media/8a7ac53a4a762c15901f6f121b311373/href</a></iframe><p>In the terminal you see the certificate starting with -----BEGIN CERTIFICATE-----. Copy everything including -----END CERTIFICATE----- to your the file your are using to keep track of the details.</p><h4>Get your Kubernetes Cluster API URL</h4><p>You can find the API URL by executing the following command kubectl config view. You should see something similar to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6ae5814faedb155fc395599c07dd0a3/href">https://medium.com/media/a6ae5814faedb155fc395599c07dd0a3/href</a></iframe><h4>Enter details in GitLab</h4><p>Now that you have all the details we can start entering them in GitLab. Go back to GitLab and you should see a form with the following input fields (Some may not be visible to you).</p><p><strong>Kubernetes Cluster name</strong></p><p>The name you wish to give the cluster.</p><p><strong>Environment scope</strong></p><p>The default environment scope is *, which means all jobs, regardless of their environment, will use that cluster. Each scope can only be used by a single cluster in a project, and a validation error will occur if otherwise. Also, jobs that don’t have an environment keyword set will not be able to access any cluster.</p><p><strong>API URL</strong></p><p>It’s the URL that GitLab uses to access the Kubernetes API. Kubernetes exposes several APIs, we want the “base” URL that is common to all of them, e.g., https://kubernetes.example.com rather than <a href="https://kubernetes.example.com/api/v1">https://kubernetes.example.com/api/v1</a>. We got the URL from the kubectl config view command we did earlier.</p><p><strong>CA Certificate</strong></p><p>If the API is using a self-signed TLS certificate, you’ll also need to include the ca.crt contents here. We decoded this from the token.</p><p><strong>Token</strong></p><p>GitLab authenticates against Kubernetes using service tokens, which are scoped to a particular namespace. Enter the base64 encoded token here.</p><p><strong>Project namespace (optional, unique)</strong></p><p>You don’t have to fill it in; by leaving it blank, GitLab will create one for you.</p><p><strong>RBAC-enabled cluster</strong></p><p>Enable it, your cluster is role-based this was done in chapter 2.</p><p>Once you filled in all the fields with the correct values. You can add the Kubernetes Cluster and you will be redirected to the Kubernetes Cluster page in Gitlab. Next step is to install some Helm Charts.</p><h3>Install Helm Charts</h3><p>The Kubernetes cluster page gives you some packages that you can install. Begin with Helm Tiller. Once this package is installed you get access to the other packages.</p><p>If you only want to use your Kubernetes cluster for pipelines, you will need to install the Gitlab Runner package.</p><p>If you want to run Review Apps and use Let’s Encrypt you will need to install the following package as well:</p><h3>Gitlab’s Kubernetes Review Apps</h3><p>This is an example of a simple Nginx web-server that does nothing more than to serve the Nginx index.html.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a37c074199c7bc46794833ac4b5f8831/href">https://medium.com/media/a37c074199c7bc46794833ac4b5f8831/href</a></iframe><p>The .gitlab-ci.yml now has a review_app and a stop_review_app job. The review_app job applies 3 ConfigMaps to your Kubernetes Cluster. It creates a Deployment, Service and an Ingress LoadBalancer.</p><p>Below you will find the Kubernetes ConfigMaps used in the review_app stage in the .gitlab-ci.yml. Don&#39;t forget to substitute the environment variables, YAML will not do this for you. You can substitute the environment variables like this in your CI job, before executing the kubectl commands:</p><pre>envsubst &lt; /path/to/templates/kubernetes-service.yml &gt; /path/to/kubernetes-service.yml</pre><p>When a request is sent to your server, the Ingress LoadBalancer will try to resolve it based on the host. By default it will be forwarded to the default backend controller. To forward the request to your Nginx webserver you will need to create a service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c527e70e99d3f26f194057c14f01347/href">https://medium.com/media/2c527e70e99d3f26f194057c14f01347/href</a></iframe><p>Deployments are used to create a set of containers, just like with docker-compose you have the freedom to choose an image, set ports and bind volumes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a41bb4bd4aeec0e54c5a9dc8b8454e71/href">https://medium.com/media/a41bb4bd4aeec0e54c5a9dc8b8454e71/href</a></iframe><p>Last but not least is the Ingress LoadBalancer. This will map any host to a service in the rules block. Basically all you have to do is say to the Ingress LoadBalancer that any traffic on the host ${CI_ENVIRONMENT_SLUG}.example.com will be forwarded to the ${CI_ENVIRONMENT_SLUG}-app-service.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de5000da5df026aeb9093628929bec1/href">https://medium.com/media/9de5000da5df026aeb9093628929bec1/href</a></iframe><h3>Kubernetes CronJob</h3><p>Sometimes you want to run scheduled commands which are executed in a different container. Kubernetes has a type for that, it’s called CronJob. Below is a example of how you can integrate this in your Review App.</p><p>Create a bash script with the following contents with filename cronjob.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48691da1faf8f6062a17cbab86a9fdca/href">https://medium.com/media/48691da1faf8f6062a17cbab86a9fdca/href</a></iframe><p>This will run a Job every 15 minutes and dynamically resolves the pod name of the app container we created in the configuration in chapter 6. In the .gitlab-ci.yml go to the job review_app and add the following lines to the script array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d339c64efce5c32c751f56278a429383/href">https://medium.com/media/d339c64efce5c32c751f56278a429383/href</a></iframe><p>The reason we need the sleep 5 is so we give Kubernetes the time to create the pods we need for the CronJob.</p><p>Don’t forget to remove the CronJob in the stop_review_app job with the following command.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff0b6f77a360a6e58488087ba19f8108/href">https://medium.com/media/ff0b6f77a360a6e58488087ba19f8108/href</a></iframe><h3>That’s all folks</h3><p>That was quite a blog, but we hope you managed to create your Kubernetes Cluster and integrated it in your GitLab repository. If you have any questions or run into any problems, drop a comment below and we hope to give you an answer.</p><p>Due to the fact that multiple authors are not supported by Medium. I would like to add that <a href="https://medium.com/@r.banffer">Robin Bänffer</a> is co-author in this blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439076b9de17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/connect-gitlab-with-digitaloceans-kubernetes-439076b9de17">Connect GitLab with DigitalOcean’s Kubernetes</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up an Angular CLI project with Docker Compose]]></title>
            <link>https://medium.com/joolsoftware/how-to-set-up-an-angular-cli-project-with-docker-compose-a3ec78f179ab?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/a3ec78f179ab</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[angular-cli]]></category>
            <dc:creator><![CDATA[Onno de Jong]]></dc:creator>
            <pubDate>Mon, 15 Apr 2019 11:39:35 GMT</pubDate>
            <atom:updated>2019-04-15T11:43:57.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cx5qHdUMRGiQeyNdnnBSZw.png" /><figcaption><strong>Design by:</strong> Vivian Bierhuizen</figcaption></figure><h3>Introduction</h3><p>In this post I would like to give a quick introduction about how to get your Angular project running in Docker. When developing our application locally, the expectation is that the container will reload our new application just like you are used to when developing locally.</p><p>This solution will work on existing angular projects as well as on new projects.</p><p>We will start of with creating a Dockerfile and use the Docker Compose tool to run our service.</p><h4>What are we going to do</h4><p>This post will guide you all the way from creating an Angular project with the CLI to a Docker setup, including reload on file changes.</p><p>In order to do so, we need the following prerequisites as displayed bellow.</p><ul><li>Node 8+</li><li>Angular CLI</li><li>Docker V18+</li><li>Preferably a Linux OS, but Mac will do as well. I won’t encourage Windows.</li></ul><h4>Installing Node on your machine</h4><p>This post won’t cover how to install Node, but here is a link to the official download page.</p><p><a href="https://nodejs.org/en/download/">https://nodejs.org/en/download/</a></p><h4>Installing the Angular CLI</h4><p>The first step is to install the Angular CLI on your local machine. The Angular CLI is the command line interface that provides multiple useful tools including creating new projects, components and services.</p><pre>npm install -g @angular/cli </pre><h4>Create a new project</h4><p>Create a new project.</p><pre>ng new angulardockerproject</pre><p>navigate to the project folder.</p><pre>cd angulardockerproject</pre><h4>The Dockerfile</h4><p>To run a Docker container we need an image. This image is defined in a Docker file.</p><p>In the Docker file we can use the following instructions:</p><p>FROM,WORKDIR ,COPY, RUN, ENV, EXPOSE, CMD</p><p>Docker then, will read these instructions to build a Docker container, but we’ll get to that later.</p><p>Lets create one in the project folder.</p><pre><em>touch Dockerfile</em></pre><p>Within this Dockerfile, we will define the Docker image. In order to do this we need to add a starting point, which is another image. To define a starting point we use the <em>FROM</em> instruction, followed by the image we would like to use.</p><blockquote>To use an empty image we could use “FROM scratch”, but we will use the Node:8 image because that is exactly what we need for our Angular environment.</blockquote><pre># This defines our starting point<br>FROM node:8 </pre><p>Amazing, we’ve defined our starting point. Let’s define an instruction to create a working directory for our app. First we need to create a directory with the <em>RUN</em> instruction, after that we will make that our working directory using the <em>WORKDIR</em> instruction.</p><pre>RUN mkdir /usr/src/app <br> <br>WORKDIR /usr/src/app</pre><p>Now we have defined our directory, we are ready to install the Angular CLI, lets do that right away. The node image provides us with NPM, which means we can install NPM packages with the RUN command.</p><pre>RUN npm install -g @angular/cli </pre><p>The next thing we need to do is to copy our Angular application to our Docker instance. We can do that using the COPY instruction. The copy instruction uses two paths as parameters similar to the CP command.</p><pre>COPY . . </pre><p>That’s it, that is the Dockerfile for now. It is the bare minimum but it should be enough for our example.</p><p>Lets test our Dockerfile by building it.</p><pre>docker build -t testimage .</pre><p>To see our image(s) we can use the following command.</p><pre>docker images</pre><p>For now, we will remove our image again. Because we are going to build our image with Docker compose. Removing the image is simple, check your IMAGE ID that you can see in the Docker image output.</p><blockquote>Image id’s look like this: d304814c7120</blockquote><pre>docker image rm &lt;your image id&gt;</pre><h4>The docker-compose file</h4><p>A Docker file is enough to build, but we want to be able to start multiple containers with one file. For example, if we also want to add our Node Express back-end application and our database which all contain their own Dockerfile, we could manage them within a single configuration.</p><p>This is where we can use the docker-compose tool.</p><blockquote>Docker compose is a tool which reads a docker-compose YAML file to start your application services.</blockquote><p>Lets create one outside our Angular project folder.</p><pre>cd ../<br>touch docker-compose.yml</pre><p>A Docker compose file starts of with the version of the configuration file that we are going to use.</p><pre>version: &#39;3.5&#39;</pre><p>Below the version we start defining our services. Our service will be called angular-service.</p><p>Here we also need to define the container name we generate with the CONTAINER_NAME instruction and the build location of our Dockerfile with the BUILD instruction.</p><p>Next we map our volumes from our local directory to the directory that we make in our environment with the VOLUMES instruction.</p><p>Then we specify on which port we want to run our application and what port we have exposed in our Dockerfile with the PORTS instruction.</p><pre>version: &#39;3.5&#39; # We use version 3.5 syntax<br>services: # Here we define our service(s)<br>    angular-service: # The name of the service<br>      container_name: angularcontainer  # Container name<br>      build: ./angulardockerproject # Location of our Dockerfile<br>      volumes: # Volume binding<br>        - &#39;./angulardockerproject:/usr/src/app&#39; <br>      ports: <br>        - &#39;4200:4200&#39; # Port mapping<br>      command: &gt; <br>        bash -c &quot;npm install &amp;&amp; ng serve --host 0.0.0.0 --port 4200&quot;</pre><p>The COMMAND instruction is a way to instruct Docker to run <em>npm install</em> and <em>ng serve</em>. This is one way to do it, I will use this example for now but there are other ways to install the node packages and run the application.</p><blockquote>The following command opens bash in the running container:</blockquote><blockquote>docker exec -i -t container_name /bin/bash</blockquote><blockquote>In this container you could also install the node packages and serve the application.</blockquote><h4>Run docker compose</h4><p>Run the docker-compose.yml file by the following command. We use the build parameter to build the image we defined in our Dockerfile if it not exists already. I like to use the -d parameter to run docker in the background.</p><pre>docker-compose up --build -d</pre><h4>How to monitor what is happening</h4><p>To see which Docker containers are running, we can run.</p><pre>docker ps</pre><p>To see all of the images that are built.</p><pre>docker images</pre><p>To stop a container, we can use.</p><pre>docker container stop angularcontainer</pre><h4>Conclusion</h4><p>In this document we learned how to create a Dockerfile to define our image(s). How to use docker compose to run our container and we learned how to monitor our running containers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ec78f179ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/how-to-set-up-an-angular-cli-project-with-docker-compose-a3ec78f179ab">How to set up an Angular CLI project with Docker Compose</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Typescript Transformers with Angular CLI]]></title>
            <link>https://medium.com/joolsoftware/custom-typescript-transformers-with-angular-cli-7f4150797e05?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/7f4150797e05</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[transformation]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[David Kingma]]></dc:creator>
            <pubDate>Wed, 27 Mar 2019 09:15:37 GMT</pubDate>
            <atom:updated>2019-03-27T09:15:37.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSirDSHLHjsbU8LuFh9iNg.png" /></figure><blockquote>We will be hacking on the Angular CLI build using private API’s. Keep in mind that these could break without prior notice!</blockquote><p>The Angular CLI uses the AngularCompilerPlugin to transpile typescript. It is a webpack plugin that uses the typescript compiler together with various Typescript transformers to transpile the typescript to workable code for the browser. <a href="https://blog.angularindepth.com/do-you-know-how-angular-transforms-your-code-7943b9d32829">See this article from Alexey Zuev on how Angular uses code tranformations</a>.</p><p>Looking for a way to add custom typescript transformations to an Angular project I found out that the <a href="https://github.com/manfredsteyer/ngx-build-plus">ngx-build-plus</a> project by Manfred Steyer supports <a href="https://github.com/manfredsteyer/ngx-build-plus#using-plugins">plugins </a>that allows you to add or manipulate plugins to the Webpack configuration. The plugin interface has methods for pre/post hooks and a method for the config manipulation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7838a37924f5172c7858aacf95ad97d/href">https://medium.com/media/b7838a37924f5172c7858aacf95ad97d/href</a></iframe><p>Inside the webpack configuration that is passed to the config method you will find a webpack plugins array that (amongst others) will contain the AngularCompilerPlugin. The AngularCompilerPlugin has a _transformers property that contains all the typescript transformers that will be passed to the Typescript compiler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6614f424485e7fe30c31e6e2f5e38f58/href">https://medium.com/media/6614f424485e7fe30c31e6e2f5e38f58/href</a></iframe><p>For this example we create a dummy Typescript transformer that logs the filenames to the console.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfcd84e0755e0d338ced5a02afa2d6ad/href">https://medium.com/media/bfcd84e0755e0d338ced5a02afa2d6ad/href</a></iframe><p>First we need to compile the plugin, as it is written in typescript:</p><pre><em>tsc --skipLibCheck --module umd -w</em></pre><p>And now we can run a normal Angular CLI build with the plugin:</p><pre><em>ng build --aot --plugin ~dist/out-tsc/ng-ts-register-transformer.js</em></pre><p>Output looks like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*NQumG41thexSI9PGy4GxXg.png" /><figcaption>Console output when applying the dummy transformer</figcaption></figure><p>As you can see it outputs not only your sourcefiles, but also generated files like .ngfactory.ts and .ngstyle.ts files. This is due to the fact that the AOT compiler generates these files before the typescript transformers are executed. This might change when Ivy is introduced in Angular 8.0.</p><p>An example repository can be found at <a href="https://github.com/Joolnl/ng-ts-transformations">https://github.com/Joolnl/ng-ts-transformations</a>.</p><h3>References</h3><ul><li><a href="https://blog.angularindepth.com/do-you-know-how-angular-transforms-your-code-7943b9d32829">https://blog.angularindepth.com/do-you-know-how-angular-transforms-your-code-7943b9d32829</a></li><li><a href="https://dev.doctorevidence.com/how-to-write-a-typescript-transform-plugin-fc5308fdd943">https://dev.doctorevidence.com/how-to-write-a-typescript-transform-plugin-fc5308fdd943</a></li><li><a href="https://github.com/manfredsteyer/ngx-build-plus">https://github.com/manfredsteyer/ngx-build-plus</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f4150797e05" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/custom-typescript-transformers-with-angular-cli-7f4150797e05">Custom Typescript Transformers with Angular CLI</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unittesting Angular components with Cypress]]></title>
            <link>https://medium.com/joolsoftware/unittesting-angular-components-with-cypress-202a38d9f81a?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/202a38d9f81a</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[David Kingma]]></dc:creator>
            <pubDate>Mon, 14 Jan 2019 15:42:17 GMT</pubDate>
            <atom:updated>2019-01-21T08:30:45.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIjKcxaoEI0MfYel2lnQVg.png" /></figure><h3>Unit testing Angular components with Cypress</h3><p>Cypress is a test runner mainly focused on end-to-end tests. It works much like protractor, but in its own way. It doesn’t use webdriver which makes it quicker, but it also doesn’t make it cross-browser as it is running your tests in Chrome.</p><p>In this blogpost I’ll show you how I got it to run unit tests, but people only interested in the end result can skip ahead to the `Getting it all up &amp; running`.</p><p>In januari 2018 I was triggered by the following <a href="https://twitter.com/bahmutov/status/954007764556230656">twitter post</a> from <a href="https://twitter.com/bahmutov">Gleb Bahmutov</a>:</p><h3>Gleb Bahmutov on Twitter</h3><p>What&#39;s the minimal Angular web app with bootstrap? I am trying to recreate same component tests as in https://t.co/QcWJcutty7 or https://t.co/dgIWbKiC9P and there seems to be a lot of steps to do for Angular :(</p><p>The reason I was surprised is that I could not believe it would be that hard. But boy was I wrong. Months passed and still no progress on the <a href="https://github.com/bahmutov/cypress-angular-unit-test">Github repository</a>, where I was expecting a quick reply from anybody in the Angular community. In July I finally found the time to have a better look at what was going wrong.</p><h3>Resource loading</h3><p>After cloning the repository and running the cypress spec file I could reproduce the issue easily: The component still wouldn’t be rendered correctly to the target iframe. Instead some other html fragment was shown that didn’t reveal its origin. After changing the templateUrl property in the @Component annotation to an inline template property the issue seemed resolved. I didn’t know of an easy way to fix this issue and posted my intermediate results on github:</p><p><a href="https://github.com/bahmutov/cypress-angular-unit-test/issues/1#issuecomment-406709957">How to scaffold a component in the test iframe? · Issue #1 · bahmutov/cypress-angular-unit-test</a></p><p>Before I woke up the next morning <a href="https://github.com/geocine">Aivan Monceller</a> had <a href="https://github.com/bahmutov/cypress-angular-unit-test/pull/2">solved the resource loading issue</a> by modifying the ts-loader cypress plugin to inline the resources using the webpack plugin ‘angular2-template-loader’!</p><h3>Getting it all up &amp; running</h3><ol><li>Create a new angular app using the angular CLI:<br>ng new angular-cypress-unit<br>And change to the newly created directory:<br>cd angular-cypress-unit</li><li>Install Cypress and all the dependencies we’ll need for it to compile the Angular app<br>npm install — save-dev cypress <a href="http://twitter.com/cypress/webpack-preprocessor">@cypress/webpack-preprocessor</a> angular2-template-loader ts-loader</li></ol><p>3. Add Cypress scripts to your package.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bae92bbc3fc9b7b1bcc9aae844cfab8/href">https://medium.com/media/7bae92bbc3fc9b7b1bcc9aae844cfab8/href</a></iframe><p>4. Run Cypress to create the initial directory structure in ./cypress:<br>npm run cy:open</p><p>5. Copy the spec file from Gleb Bahmutov’s repository <a href="https://github.com/bahmutov/cypress-angular-unit-test/blob/master/cypress/integration/spec.ts">https://github.com/bahmutov/cypress-angular-unit-test/blob/master/cypress/integration/spec.ts</a> in ./cypress/integration. You can optionally remove the ./cypress/integration/example directory that is generated by default with example tests.</p><p>6. You will also need to copy the files from <a href="https://github.com/bahmutov/cypress-angular-unit-test/tree/master/cypress/plugins">https://github.com/bahmutov/cypress-angular-unit-test/tree/master/cypress/plugins</a> to your local ./cypress/plugins directory as it contains the modified Cypress plugin (see the <a href="https://github.com/bahmutov/add-typescript-to-cypress/blob/master/src/cy-ts-preprocessor.js">original</a>) that takes care of Typescript and angular template inlining preprocessing. The plugin extends the default Cypress webpack configuration.</p><p>7. Place a tsconfig.json file in the ./cypress directory that sets the scope of the typescript compiler to integration/*.ts and sets some compiler options to emit decorator metadata that is required for Angular JIT compiling</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d969e6a8e5784a17bff92be229fa4bb/href">https://medium.com/media/3d969e6a8e5784a17bff92be229fa4bb/href</a></iframe><p>8. If we run Cypress again it finally compiles correctly, but the Angular dependency injector gives the following error:</p><p>Error: Can’t resolve all parameters for ApplicationModule: (?).</p><p>This is because we need the reflection polyfill for the JIT compiling. You can import it by adding the following line to the spec.ts file. Make sure that this import statement is before any @angular import statement.</p><p>// Required for JIT in NG-7<br>import ‘core-js/es7/reflect’;</p><p>By now you should be able to run your first cypress unit test! You might need to change the assertions in the original spec file to match your project name.</p><h3>Using the Angular private API</h3><p>To make the individual rendering of the components work without bootstrapping a whole Angular application, we could use the private Angular API renderComponent en compileComponent as discussed by <a href="https://medium.com/u/355b1dfe86ae">Uri Shaked</a> in his <a href="https://blog.angularindepth.com/my-adventures-running-angular-ivy-inside-stackblitz-yes-it-is-possible-f4984fafd7d4">blog post on how to make Ivy work in Stackblitz</a>. All private Angular APIs are prefixed with a ɵ as a kind reminder that they are private.</p><blockquote>Private API means: can be changed or removed without prior notice!</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aac68673455f6621fab7fdfcb4f86b5/href">https://medium.com/media/7aac68673455f6621fab7fdfcb4f86b5/href</a></iframe><p>Using the Angular private API makes the code much more readable except for line 13 where we need to find the component definition in the annotations, but this could be easily extracted away from our test code.</p><h3>Conclusion</h3><p>Getting Cypress up &amp; running for Angular unit tests is indeed not as easy as a developer would want. We haven’t even looked at possible zone.js /(fake) async issues. The main problems were getting compiled the way Angular does and rendering a single component instead of the whole application.</p><p>The build process using the webpack preprocessor for Cypress could possibly be handled by <a href="https://www.npmjs.com/package/@ngtools/webpack">@ngtools/webpack</a>, which would make it less error prone.</p><p>A fully working repository, which is a fork of <a href="https://github.com/bahmutov/cypress-angular-unit-test">Gleb Bahmutovs Angular 5 version</a> can be found at <a href="https://github.com/meDavid/cypress-angular-unit-test/tree/angular7">https://github.com/meDavid/cypress-angular-unit-test/tree/angular7</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=202a38d9f81a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/unittesting-angular-components-with-cypress-202a38d9f81a">Unittesting Angular components with Cypress</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending Firebase with Cloud functions & ElasticSearch]]></title>
            <link>https://medium.com/joolsoftware/extending-firebase-with-cloud-functions-elasticsearch-129fbbb951e0?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/129fbbb951e0</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[firebase-cloud-functions]]></category>
            <dc:creator><![CDATA[David Kingma]]></dc:creator>
            <pubDate>Thu, 04 May 2017 15:14:02 GMT</pubDate>
            <atom:updated>2017-05-05T11:59:20.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUx1UfhyyfJ57ZS_jBSzdQ.png" /></figure><p>Firebase is a hosted noSQL solution from Google that really focuses on the realtime aspect and the ease of use for developers. It features easy user authentication, security rules, realtime communication and blob storage. With its great features come some limitations regarding query support. Firebase only support startAt(), endAt(), and equalTo() conditions and not any form of fulltext support, let alone aggregations / facets. In this tutorial we’ll show you how to add fulltext query and aggregation support to Firebase using ElasticSearch and Firebase Cloud functions.</p><p>We won’t bother with a frontend for now, but focus on the Elasticsearch and Firebase cloud function part. We’ll use an example cars database found online and add data and queries in firebase using the Firebase cli.</p><p>If you are already experienced with Firebase or have a running Elasticsearch instance, you can skip the setup part and jump right into the Firebase cloud functions.</p><h3>Setup Firebase</h3><p>To get started with firebase you need to create a new Firebase project in your <a href="https://console.firebase.google.com/">Firebase console</a>, click the ‘Add project’ button, name your project and click the ‘create project’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2JtIj0ubDFHM41Opk6xyGA.png" /></figure><p>Upgrade to Firebase plan to ‘Blaze’ to allow for network connection to the Elasticsearch VM we are about to create. <a href="https://firebase.google.com/pricing/">The Blaze plan will cost actual money</a>. After completing the update, it might take a few minutes to be acutally completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CsCutDQ7EppqFXSSs598tg.png" /></figure><h3>Setup ElasticSearch VM</h3><p>Go to <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a> and login with your Google account or use <a href="https://console.cloud.google.com/freetrial">https://console.cloud.google.com/freetrial</a> to get a free trial to Google Cloud Platform with $300 credit (but it does require a creditcard). When you are in the Google Cloud Console, go to the Cloud Launcher using the sidenav, search for ‘Elasticsearch’ (Inception!) and select the Bitnami image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OX7XStD6mqsZJXkbllApUg.png" /></figure><p>The Bitnami image is the cheap option, which is perfectly fine to get some hands-on experience. When you have selected the Bitnami Elasticsearch VM, you click on ‘Launch on Compute Engine’ button. This might trigger an ‘Enable billing’ dialog if you didn’t already have billing enabled. In the following screen you can reduce the VM machine type to ‘micro’ instead of ‘small’ as we’re not using it for any production load in this tutorial and click the ‘deploy’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zs1kDbTqAcCYtxsZxQz1cA.png" /></figure><p>The deployment might take a little while but the deployment manager will eventually present you with the details we need to get data in the search index and query the search index: The IP adress (ephemeral, but usable for now) and the credentials for elasticsearch. After a successfull deployment you can find the instance in the sidenav menu under ‘Compute Engine’. Keep track of the Site address, Admin user and Admin password, you will need these later when configuring the Firebase cloud function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a8J1TPIT51HJUknkWdbtJw.png" /></figure><h3>Setup Elasticsearch mapping</h3><p>For a basic UI in your browser to send and receive some elasticsearch requests you can install the Chrome Sense extension. Its a bit buggy, but works good enough.</p><p><a href="https://chrome.google.com/webstore/detail/sense-beta/lhjgkmllcaadmopgmanpapmpjgmfcfig?hl=en">Sense (Beta)</a></p><p>Now we need to tell elastic search what kind of data we’ll be sending and querying. The configuration of these mappings can be done sending an HTTP request using the Sense Chrome extension (or any other http client like Curl). It will require the credentials shown in the Bitnami Elasticsearch VM. The default username is always ‘user’.</p><p><a href="https://gist.github.com/meDavid/c5388f661d3ee7b73dcc992f71145da0">Here you can find our Elasticsearch cars mapping</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WT4vpJAyVL9LHmez3LqGgQ.png" /></figure><h3>Setup Firebase tools</h3><p>&gt; npm install -g firebase-tools<br><br>The first command installs the firebase CLI tool. This tool helps you to do import, export and deployment of firebase projects. Deployment can consist of static files, security rules and cloud functions.We’ll focus on the cloud functions.</p><p>&gt; firebase login</p><p>The second command will authenticate you with firebase using your default browser. If all goes well, it will show you a ‘Firebase CLI Login Successful’ page and you can close the browser. These credentials are now used whenever you deploy, import or export using the Firebase CLI.</p><p>&gt; firebase init functions</p><p>Next we initialize a firebase functions project. You will be asked to select a firebase project. A new functions directory will be bootstrapped with some npm dependencies together with a .firebaserc and firebase.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7onaLPaFKhEO5L5QTwc5w.png" /></figure><h3>The Firebase Cloud functions</h3><p>Now we have all the basics setup: A firebase project in the cloud, an Elasticsearch instance and a local project folder.</p><p>Firebase Cloud functions are a kind of triggers with a callback that gets executed when one of the following happens:</p><ul><li>Written to the database</li><li>User is created or deleted</li><li>Something changed in the file storage</li><li>An Http(s) call is made</li><li>A message is published on a topic in Google pubsub</li><li>A specified Firebase analytics event</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a58cd7b7359a55f42cfdd98a40f3a26/href">https://medium.com/media/9a58cd7b7359a55f42cfdd98a40f3a26/href</a></iframe><p>For our case with Elasticsearch we’ll use the database onWrite event to monitor anything that is written to /cars/{carId} . cardId is a placeholder that can be retrieved as an event parameter.</p><p>To communicate with the Elasticsearch VM we’ll require some additional dependencies:</p><p>&gt; npm install --save request request-promise lodash</p><p>First we’ll filter the data we receive from firebase to only include the fields used in Elasticsearch, then we post the json object to the Elasticsearch cars index. For our credentials and host configuration we use firebase config variables to seperate the code from the configuration. If we don’t receive any data it means that the data is deleted and we can safely delete it in the Elasticsearch index.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e1b4776f8c957cd7ee891a59a459801/href">https://medium.com/media/5e1b4776f8c957cd7ee891a59a459801/href</a></iframe><blockquote>Keep in mind that the Firebase cloud function will not be called when / or /cars gets deleted or you use the firebase-admin sdk or console import!</blockquote><p>To set the needed firebase config variables we use the Firebase CLI functions:config:set command:</p><p>&gt; firebase functions:config:set elasticsearch.username=&quot;user&quot; elasticsearch.password=&quot;my_password&quot; elasticsearch.url=&quot;http://104.154.41.53/elasticsearch/&quot;</p><p>And now its time to deploy our first Firebase cloud function!</p><p>&gt; firebase deploy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*ddBVvJLbb_A8M2jW9HAzyg.png" /></figure><p>When all is successfull you can see the ‘indexCarsToElastic’ function in the Firebase console under ‘Functions’. Test it by manipulating the test cars data and look at the Logs tab in the Firebase Functions console.</p><h3>Import test data</h3><p>Now it’s time to import some cars data using a node script that will read the first 1000 lines of a cars dataset. We will need a firebase service-account. You can download the keys for the service account in the <a href="https://console.firebase.google.com/">Firebase console</a> =&gt; Project settings =&gt; Service accounts page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pkqe2qZ7C4QZTdHOlzP4Sg.png" /></figure><p>Place the service account key json file in a new import directory (outside the functions directory), download<a href="https://gist.githubusercontent.com/meDavid/be86b68c4943185bcc089b45ec074a4c/raw/a42ed4b9cd731151f0192d2c8b33b8c0c40138dc/cars.json"> this file as cars.json</a> in that same import directory and copy the following file as import.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d8026515b8e78553c5085a9858bba92/href">https://medium.com/media/5d8026515b8e78553c5085a9858bba92/href</a></iframe><p>Now, lets run our import using the following command</p><p>&gt; npm install --save firebase-admin<br>&gt; node import.js</p><p>When all data is imported, we can <a href="https://gist.github.com/meDavid/bb8a3a4975d5399b6be3d8b89ea1e67b">query Elasticsearch</a> with some aggregations and we would receive 1000 hits in total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScHm-DmvD5lokbs5AjiOTg.png" /></figure><p>All firebase Cloud function invocations can be seen in the logs. You will see errors when for example the Elasticsearch VM was not available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-vd9L4woUOUluXBKSWDjw.png" /></figure><h3>Conclusion</h3><p>The actual code needed to run triggers based on the Firebase database writes is minimal. Just the way we like it. As said: the indexing of Elasticsearch is pretty basic. We’ll need to improve the error handling, find ways to trigger re-indexing when needed but Firebase cloud functions are definitly a better solution then the previous solutions like <a href="https://github.com/firebase/flashlight/">Flashlight</a> and <a href="https://github.com/firebase/firebase-queue">Firebase queues</a>.</p><p>Liked it? Questions? Improvements? <a href="https://twitter.com/medavidk">Let me know!</a></p><h3>References</h3><ul><li>Cars dataset used: <a href="https://raw.githubusercontent.com/amercader/car-fuel-and-emissions/master/datapackage.json">https://raw.githubusercontent.com/amercader/car-fuel-and-emissions/master/datapackage.json</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html">Elasticsearch</a></li><li><a href="https://docs.bitnami.com/google/apps/elasticsearch/%60">Bitnami Elasticsearch</a></li><li><a href="https://chrome.google.com/webstore/detail/sense-beta/lhjgkmllcaadmopgmanpapmpjgmfcfig?hl=en">Google Chrome Sense extension</a> (buggy, but still helpfull)</li><li><a href="https://firebase.google.com/docs/cli/">Firebase CLI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=129fbbb951e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/extending-firebase-with-cloud-functions-elasticsearch-129fbbb951e0">Extending Firebase with Cloud functions &amp; ElasticSearch</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Symfony Workflow component (1/3)]]></title>
            <link>https://medium.com/joolsoftware/techblog-symfony-workflow-component-1-3-3056a05dc27f?source=rss----5317e4a37e7e---4</link>
            <guid isPermaLink="false">https://medium.com/p/3056a05dc27f</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Jool Software Professionals]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 13:47:59 GMT</pubDate>
            <atom:updated>2018-10-01T14:05:54.796Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*L2qsQ-Q2ihCuXiccjqAEuQ.png" /></figure><p>With the release of Symfony 3.2 a new workflow component was added that implemented a <a href="https://en.wikipedia.org/wiki/Petri_net#Workflow_nets">workflow net</a> or a <a href="https://en.wikipedia.org/wiki/Finite-state_machine">state machine</a>. This component helps to separate the business workflow logic from other application logic and can help to visualize the workflow and mark the current state it is in.</p><p>This blog post is part 1 of a small series on the workflow component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*o79K865pJ7B0vA-Mw-KkCg.png" /><figcaption>Creditcard application workflow</figcaption></figure><ol><li>Introduction to the workflow component (this blog post)</li><li>Scheduled transitions using a job scheduler, for example to send reminders.</li><li>Improve the configuration, testability and visualize the workflow</li></ol><p>For this introduction we’ll use a creditcard application usecase as example. The applicant will need to confirm the applications emailaddress, the application needs to be verified and a new creditcard needs to be created.</p><p>For the workflow component to work we need to configure a <strong>workflow definition</strong>, a <strong>marking store</strong> and a <strong>subject</strong>. A workflow definition consists of places (states), transitions between the places and guards that conditionally block transitions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66b254cb4c56f9f7a18ed56985cbfefd/href">https://medium.com/media/66b254cb4c56f9f7a18ed56985cbfefd/href</a></iframe><h3><strong>The marking store</strong></h3><p>The marking store keeps track of the place where the subject (in this case the creditcard application) is inside the workflow. By default the marking store will manipulate the ‘marking’ property on your subject. If we have a creditcard application $application in the place start and apply the transition confirm_email the marking store would set the $application-&gt;marking property to email_confirmed.</p><p>By default the marking store will manipulate the ‘marking’ property on your subject, but you can change this by supplying an arguments property to the marking_store configuration. In the following example we change the property name to ‘state’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bab57b49acdb8382a3e4f27f38f38c9d/href">https://medium.com/media/bab57b49acdb8382a3e4f27f38f38c9d/href</a></iframe><p>The marking store will only manipulate the property, but will not take care of any persistence. If we implemented a service persisting_marking_store with our own implementation of the <em>MarkingStoreInterface we could configure it using the service configuration property.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c2cb5d56b50ce37185bd36c7d47235e/href">https://medium.com/media/0c2cb5d56b50ce37185bd36c7d47235e/href</a></iframe><p>For an example of a persisting marking store see the <a href="https://github.com/GlobalTradingTechnologies/workflow-extensions-bundle/blob/master/MarkingStore/OrmPersistentMarkingStore.php">OrmPersistentMarkingStore </a>in the GTT <a href="https://github.com/GlobalTradingTechnologies/workflow-extensions-bundle">workflow-extension-bundle</a>.</p><h3><strong>Multiple-state workflow</strong></h3><p>When the workflow supports parallel processes the subject can be in multiple places at once and we’ll need to configure the <em>MultipleStateMarkingStore</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ea96f5738037a5be15c882887b90a4d/href">https://medium.com/media/8ea96f5738037a5be15c882887b90a4d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*08IC47_kHWFfQ_sPoAz6vQ.png" /><figcaption>Multiple-state workflow</figcaption></figure><p>But in our example we’ll use a state machine which always has a single place/state.</p><blockquote>The type names for marking stores were <a href="https://github.com/symfony/symfony/commit/08464c9f2c059c5292fc9bfe991d6b74437389c9">changed</a>:<br>- property_accessor -&gt; multiple_state<br>- scalar -&gt; single_state<br>You might still see examples with the old configuration names.</blockquote><p>When your workflow type is <em>state_machine a </em><em>multiple_state</em> marking store is valid but doesn’t add any extra functionality as a state machine has only a single state.</p><h3><strong>Initiate workflow</strong></h3><p>To get a hold of a specific workflow you can use the following service name syntax: $container-&gt;get(&#39;workflow.&#39; . $workflowName), or when you use a state machine: $container-&gt;get(&#39;state_machine&#39; . $workflowName). Keep in mind that while the service name differs between a normal workflow and a statemachine the prefix workflow for event names in both cases.</p><h3><strong>Apply workflow transition</strong></h3><p>You can apply a transition using $workflow-&gt;apply(&#39;confirm_email&#39;, $subject). For our example application we implement a controller that would confirm the emailaddress using a link containing a unique hash</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d25852fd058cba9aaddf8602631414b/href">https://medium.com/media/8d25852fd058cba9aaddf8602631414b/href</a></iframe><h3><strong>Transition events</strong></h3><p>Applying a transition will dispatch the following sequence of events:</p><ol><li>Guard the transition<br>workflow[.&lt;workflow_name&gt;].guard[.&lt;transition_name&gt;]<br>The guard event is used the apply conditions to a transition and can block the transition.</li><li>Leave the <em>from </em>place<br>workflow[.&lt;workflow_name&gt;].leave[.&lt;from_place_name&gt;]</li><li>Transition<br>workflow[.&lt;workflow_name&gt;].transition[.&lt;transition_name&gt;]<br>This event can be used to apply an action on this transition such as sending an email.</li><li>Enter the <em>to</em> place<br>workflow[.&lt;workflow_name&gt;].enter[.&lt;to_place_name&gt;]</li><li>Entered the to place (<a href="https://github.com/symfony/symfony/pull/20787">Only ≥ Symfony 3.3</a>)<br>workflow[.&lt;workflow_name&gt;].entered[.&lt;to_place_name&gt;]<br>This is the same as the enter event but now the marking store is updated.</li><li>Announce new applicable transitions<br>workflow[.&lt;workflow_name&gt;].transition[.&lt;transition_name&gt;]<br>Listener to this event if you want to automatically apply a transition.</li></ol><h3><strong>Listen for a transition</strong></h3><p>Using the generated workflow events we could listen for the confirm_email transition event and send an email when the user confirms his creditcard application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85807383aa25c5422cd45dfdb0a89194/href">https://medium.com/media/85807383aa25c5422cd45dfdb0a89194/href</a></iframe><h3><strong>Guard a workflow transition</strong></h3><p>To conditionally guard a workflow transition the application can listen for guard events. If any of the guard listeners set $guardEvent-&gt;setBlocked(true) the transition will not be available.</p><p>In the creditcard example we can require an additional approved credit limit when the user requests a creditcard with a limit above $ 200. We implement a Guard listener that listens for the workflow.creditcard_application_flow.guard.create_card event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c91b10aa29daf774d07bffc93cb5e835/href">https://medium.com/media/c91b10aa29daf774d07bffc93cb5e835/href</a></iframe><p>In Symfony 3.3+ you will also be able to define the <a href="https://github.com/symfony/symfony/pull/21935">guards using an expression in the workflow definition</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fd8c0723aba0ae65c8fac7c04413c16/href">https://medium.com/media/1fd8c0723aba0ae65c8fac7c04413c16/href</a></iframe><h3>What’s next?</h3><p>In part 2 of this serie we’ll have a look at how you can schedule transitions and hook transitions to application events. We’ll build a reminder transtion that ‘ll be applied if the user hasn’t confirmed its creditcard application in 3 days.</p><h3>References</h3><ul><li><a href="https://github.com/lyrixx/SFLive-Paris2016-Workflow">https://github.com/lyrixx/SFLive-Paris2016-Workflow</a></li><li><a href="http://symfony.com/blog/new-in-symfony-3-2-workflow-component">http://symfony.com/blog/new-in-symfony-3-2-workflow-component</a></li><li><a href="https://github.com/symfony/symfony/pull/21935">https://github.com/symfony/symfony/pull/21935</a> (Guard expression support)</li><li><a href="https://github.com/symfony/symfony/pull/20787">https://github.com/symfony/symfony/pull/20787</a> (Support for the entered workflow event)</li><li><a href="https://github.com/GlobalTradingTechnologies/workflow-extensions-bundle">https://github.com/GlobalTradingTechnologies/workflow-extensions-bundle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3056a05dc27f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/joolsoftware/techblog-symfony-workflow-component-1-3-3056a05dc27f">Symfony Workflow component (1/3)</a> was originally published in <a href="https://medium.com/joolsoftware">Jool Software Professionals</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>