<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mor Kadosh on Medium]]></title>
        <description><![CDATA[Stories by Mor Kadosh on Medium]]></description>
        <link>https://medium.com/@morkadosh?source=rss-5f9a8c663703------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JnLSjbES5LSSaJU3.</url>
            <title>Stories by Mor Kadosh on Medium</title>
            <link>https://medium.com/@morkadosh?source=rss-5f9a8c663703------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:42:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@morkadosh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build beautiful, accessible tables that work everywhere with Lit, Tanstack Table and Twind]]></title>
            <link>https://medium.com/@morkadosh/build-beautiful-accessible-tables-that-work-everywhere-with-lit-tanstack-table-and-twind-1275049d53a1?source=rss-5f9a8c663703------2</link>
            <guid isPermaLink="false">https://medium.com/p/1275049d53a1</guid>
            <category><![CDATA[tanstack-table]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[lit]]></category>
            <dc:creator><![CDATA[Mor Kadosh]]></dc:creator>
            <pubDate>Wed, 22 May 2024 16:03:51 GMT</pubDate>
            <atom:updated>2024-05-22T16:36:57.686Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://lit.dev/">Lit</a> is a simple but yet powerful library for creating Web Components. Although Web Components and Lit have gained popularity in the last years, it still feels like there is still some way to go with the ecosystem.</p><p><a href="https://tanstack.com/table/latest">Tanstack Table</a> is a library that provides a headless UI for creating performant tables &amp; datagrids.</p><p>Recently, an addition to Tasntack Table introduced a support for Lit.</p><p>In this article, we will learn how to build tables using Lit &amp; Tanstack Table, and we will end up styling our table using <a href="http://twind.style/">Twind</a>, which gives us a super easy way to integrate Tailwind into our Lit Elements.</p><p>First on foremost, we need to check @tanstack/lit-table into our project:</p><pre>npm install --save @tanstack/lit-table<br><br>// or<br>pnpm add @tanstack/lit-table<br><br>// or<br>yarn add @tanstack/lit-table<br></pre><p>Let’s start by creating a simple scaffold for our Table element:</p><pre>import { html, LitElement } from &quot;lit&quot;;<br>import { customElement } from &quot;lit/decorators.js&quot;;<br><br>@customElement(&quot;my-table&quot;)<br>export class MyTable extends LitElement {<br>  protected render() {<br>    return html`Hello Table!`;<br>  }<br>}</pre><p>The next thing we want to do, is to add the TableController provided by @tanstack/lit-table . This controller will ultimately grant us access to the table instance:</p><pre>import { html, LitElement } from &quot;lit&quot;;<br>import { customElement } from &quot;lit/decorators.js&quot;;<br>import { TableController } from &quot;@tanstack/lit-table&quot;;<br><br>@customElement(&quot;my-table&quot;)<br>export class MyTable extends LitElement {<br>  private tableController = new TableController(this);<br><br>  protected render() {<br>    return html`Hello Table!`;<br>  }<br>}</pre><p>Now as the controller is hooked to our element, we can create the table. Notice, that we also added <a href="https://lit.dev/docs/components/properties/">properties</a> to enable passing our table element the required columns and data . We also made our element accept a generic type variable, to make type safety better:</p><pre>import { html, LitElement } from &quot;lit&quot;;<br>import { customElement, property } from &quot;lit/decorators.js&quot;;<br>import {<br>  ColumnDef,<br>  getCoreRowModel,<br>  TableController,<br>  RowData,<br>} from &quot;@tanstack/lit-table&quot;;<br><br>@customElement(&quot;my-table&quot;)<br>export class MyTable&lt;TData extends RowData&gt; extends LitElement {<br>  private tableController = new TableController&lt;TData&gt;(this);<br><br>  @property()<br>  private columns: ColumnDef&lt;TData, any&gt;[] = [];<br><br>  @property()<br>  private data: TData[] = [];<br><br>  protected render() {<br>    const table = this.tableController.table({<br>      columns: this.columns,<br>      data: this.data,<br>      getCoreRowModel: getCoreRowModel(),<br>    });<br><br>    return html`Hello Table!`;<br>  }<br>}<br><br>declare global {<br>  interface HTMLElementTagNameMap {<br>    &quot;my-table&quot;: MyTable&lt;unknown&gt;;<br>  }<br>}</pre><p>And now, we are ready to render our table!</p><p>We’ll start with the basics, having all of our table parts rendered directed to the main element:</p><pre>import { html, LitElement } from &quot;lit&quot;;<br>import { customElement, property } from &quot;lit/decorators.js&quot;;<br>import {<br>  ColumnDef,<br>  getCoreRowModel,<br>  TableController,<br>  RowData,<br>  flexRender,<br>} from &quot;@tanstack/lit-table&quot;;<br>import { repeat } from &quot;lit/directives/repeat.js&quot;;<br><br>@customElement(&quot;my-table&quot;)<br>export class MyTable&lt;TData extends RowData&gt; extends LitElement {<br>  private tableController = new TableController&lt;TData&gt;(this);<br><br>  @property()<br>  private columns: ColumnDef&lt;TData, any&gt;[] = [];<br><br>  @property()<br>  private data: TData[] = [];<br><br>  protected render() {<br>    const table = this.tableController.table({<br>      columns: this.columns,<br>      data: this.data,<br>      getCoreRowModel: getCoreRowModel(),<br>    });<br><br>    return html`<br>      &lt;table&gt;<br>        &lt;thead&gt;<br>          ${table.getHeaderGroups().map(<br>            (headerGroup) =&gt; html`<br>              &lt;tr&gt;<br>                ${headerGroup.headers.map(<br>                  (header) =&gt; html`<br>                    &lt;th&gt;<br>                      ${header.isPlaceholder<br>                        ? null<br>                        : flexRender(<br>                            header.column.columnDef.header,<br>                            header.getContext(),<br>                          )}<br>                    &lt;/th&gt;<br>                  `,<br>                )}<br>              &lt;/tr&gt;<br>            `,<br>          )}<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          ${repeat(<br>            table.getRowModel().rows,<br>            (row) =&gt; row.id,<br>            (row) =&gt;<br>              html` &lt;tr&gt;<br>                ${row<br>                  .getVisibleCells()<br>                  .map(<br>                    (cell) =&gt; html`<br>                      &lt;td&gt;<br>                        ${flexRender(<br>                          cell.column.columnDef.cell,<br>                          cell.getContext(),<br>                        )}<br>                      &lt;/td&gt;<br>                    `,<br>                  )}<br>              &lt;/tr&gt;`,<br>          )}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    `;<br>  }<br>}<br><br>declare global {<br>  interface HTMLElementTagNameMap {<br>    &quot;my-table&quot;: MyTable&lt;unknown&gt;;<br>  }<br>}</pre><p>Note that in order to render the table rows, we used the <a href="https://lit.dev/docs/templates/lists/#the-repeat-directive"><strong>repeat</strong></a> directive provided by Lit, to ensure more efficient diffing and rendering when and if the data updates.</p><p>Now as we have the basic structure for our table, we can try it out with some sample data:</p><pre>import { makeData, Person } from &quot;./makeData.ts&quot;;<br><br>const columns: ColumnDef&lt;Person&gt;[] = [<br>  {<br>    accessorKey: &quot;firstName&quot;,<br>    header: &quot;First Name&quot;,<br>    cell: (data) =&gt; data.getValue(),<br>  },<br>  {<br>    accessorKey: &quot;lastName&quot;,<br>    header: &quot;Last Name&quot;,<br>    cell: (data) =&gt; data.getValue(),<br>  },<br>  {<br>    accessorKey: &quot;age&quot;,<br>    header: &quot;Age&quot;,<br>    cell: (data) =&gt; data.getValue(),<br>  },<br>  {<br>    accessorKey: &quot;createdAt&quot;,<br>    header: &quot;Created At&quot;,<br>    cell: (data) =&gt; data.getValue(),<br>  },<br>];<br><br>const data = generateData(10);<br><br>@customElement(&quot;my-element&quot;)<br>export class MyElement extends LitElement {<br>  render() {<br>    return html`&lt;my-table .columns=${columns} .data=&quot;${data}&quot;&gt;&lt;/my-table&gt; `;<br>  }<br><br>  static styles = css``;<br>}<br><br>declare global {<br>  interface HTMLElementTagNameMap {<br>    &quot;my-element&quot;: MyElement;<br>  }<br>}</pre><p>generateData is a function that creates random entries.</p><p>Drum rolls please…🥁🥁🥁</p><p>We have a table!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hnViGDAFiyeKHP1ibv4nNw.png" /></figure><h3>Sorting</h3><p>Next — we would like to add some sorting.</p><p>In order to achieve that, we need to add to our table the getSortedRowModel , and the appropriate event handlers:</p><pre>import { html, LitElement } from &quot;lit&quot;;<br>import { customElement, property } from &quot;lit/decorators.js&quot;;<br>import {<br>  ColumnDef,<br>  getCoreRowModel,<br>  TableController,<br>  RowData,<br>  flexRender,<br>  getSortedRowModel,<br>} from &quot;@tanstack/lit-table&quot;;<br>import { repeat } from &quot;lit/directives/repeat.js&quot;;<br>import { styleMap } from &quot;lit/directives/style-map.js&quot;;<br>import &quot;./sort-caret.ts&quot;;<br><br>@customElement(&quot;my-table&quot;)<br>export class MyTable&lt;TData extends RowData&gt; extends LitElement {<br>  private tableController = new TableController&lt;TData&gt;(this);<br><br>  @property()<br>  private columns: ColumnDef&lt;TData, any&gt;[] = [];<br><br>  @property()<br>  private data: TData[] = [];<br><br>  protected render() {<br>    const table = this.tableController.table({<br>      columns: this.columns,<br>      data: this.data,<br>      getCoreRowModel: getCoreRowModel(),<br>      getSortedRowModel: getSortedRowModel(),<br>    });<br><br>    return html`<br>      &lt;table&gt;<br>        &lt;thead&gt;<br>          ${table.getHeaderGroups().map(<br>            (headerGroup) =&gt; html`<br>              &lt;tr&gt;<br>                ${headerGroup.headers.map(<br>                  (header) =&gt; html`<br>                    &lt;th&gt;<br>                      &lt;div<br>                        style=${styleMap({<br>                          cursor: header.column.getCanSort()<br>                            ? &quot;pointer&quot;<br>                            : &quot;default&quot;,<br>                        })}<br>                        @click=&quot;${header.column.getToggleSortingHandler()}&quot;<br>                      &gt;<br>                        ${header.isPlaceholder<br>                          ? null<br>                          : flexRender(<br>                              header.column.columnDef.header,<br>                              header.getContext(),<br>                            )}<br>                        &lt;sort-caret<br>                          .type=&quot;${header.column.getIsSorted()}&quot;<br>                        &gt;&lt;/sort-caret&gt;<br>                      &lt;/div&gt;<br>                    &lt;/th&gt;<br>                  `,<br>                )}<br>              &lt;/tr&gt;<br>            `,<br>          )}<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>          ${repeat(<br>            table.getRowModel().rows,<br>            (row) =&gt; row.id,<br>            (row) =&gt;<br>              html` &lt;tr&gt;<br>                ${row<br>                  .getVisibleCells()<br>                  .map(<br>                    (cell) =&gt; html`<br>                      &lt;td&gt;<br>                        ${flexRender(<br>                          cell.column.columnDef.cell,<br>                          cell.getContext(),<br>                        )}<br>                      &lt;/td&gt;<br>                    `,<br>                  )}<br>              &lt;/tr&gt;`,<br>          )}<br>        &lt;/tbody&gt;<br>      &lt;/table&gt;<br>    `;<br>  }<br>}<br><br>declare global {<br>  interface HTMLElementTagNameMap {<br>    &quot;my-table&quot;: MyTable&lt;unknown&gt;;<br>  }<br>}</pre><p>sort-caret is another custom element you can find here:</p><pre>import { customElement, property } from &quot;lit/decorators.js&quot;;<br>import { html, LitElement, nothing } from &quot;lit&quot;;<br>import { styleMap } from &quot;lit/directives/style-map.js&quot;;<br><br>@customElement(&quot;sort-caret&quot;)<br>export class SortCaret extends LitElement {<br>  @property()<br>  type: null | &quot;desc&quot; | &quot;asc&quot; = null;<br><br>  protected render() {<br>    if (!this.type) return nothing;<br>    return html`<br>      &lt;svg<br>        style=${styleMap({<br>          transform: this.type === &quot;desc&quot; ? `rotate(180deg)` : null,<br>        })}<br>        width=&quot;15&quot;<br>        height=&quot;15&quot;<br>        xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>        viewBox=&quot;0 0 320 512&quot;<br>      &gt;<br>        &lt;!--!Font Awesome Free 6.5.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2024 Fonticons, Inc.--&gt;<br>        &lt;path<br>          d=&quot;M182.6 137.4c-12.5-12.5-32.8-12.5-45.3 0l-128 128c-9.2 9.2-11.9 22.9-6.9 34.9s16.6 19.8 29.6 19.8H288c12.9 0 24.6-7.8 29.6-19.8s2.2-25.7-6.9-34.9l-128-128z&quot;<br>        /&gt;<br>      &lt;/svg&gt;<br>    `;<br>  }<br>}</pre><p>And the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*V6Qt-KfkFv-Ko29Kljmh9g.gif" /><figcaption>Our table support sorting now</figcaption></figure><h3>Pagination</h3><p>Up until now, our table played nicely with a small set of data. However, in the real world, we might need to be able to render a much larger one.</p><p>Luckily, @tanstack/lit-table supports pagination out of the box, and the implementation is pretty easy.</p><p>Similarly to Sortiing, adding the support for the paginated rows, is as easy as adding the pagination model to the table configuration:</p><pre>const table = this.tableController.table({<br>  columns: this.columns,<br>  data: this.data,<br>  getCoreRowModel: getCoreRowModel(),<br>  getSortedRowModel: getSortedRowModel(),<br>  <br>  // New Pagination Model<br>  getPaginationRowModel: getPaginationRowModel(),<br>});</pre><p>And add the Pagination controllers:</p><pre>&lt;pagination-controller<br>  .hasNextPage=${table.getCanNextPage()}<br>  .hasPreviousPage=${table.getCanPreviousPage()}<br>  .nextPage=${table.nextPage}<br>  .pageCount=${table.getPageCount()}<br>  .pageIndex=${table.getState().pagination.pageIndex}<br>  .pageSize=${table.getState().pagination.pageSize}<br>  .setPageSize=&quot;${table.setPageSize}&quot;<br>  .previousPage=${table.previousPage}<br>  .firstPage=${table.firstPage}<br>  .lastPage=${table.lastPage}<br>&gt;&lt;/pagination-controller&gt;</pre><pre>import { customElement, property } from &quot;lit/decorators.js&quot;;<br>import { html, LitElement } from &quot;lit&quot;;<br><br>@customElement(&quot;pagination-controller&quot;)<br>export class PaginationController extends LitElement {<br>  @property()<br>  private hasNextPage: boolean;<br><br>  @property()<br>  private hasPreviousPage: boolean;<br><br>  @property()<br>  private nextPage: () =&gt; void;<br><br>  @property()<br>  private previousPage: () =&gt; void;<br><br>  @property()<br>  private firstPage: () =&gt; void;<br><br>  @property()<br>  private lastPage: () =&gt; void;<br><br>  @property()<br>  private pageSize: number = 10;<br><br>  @property()<br>  private setPageSize: (pageSize: number) =&gt; void;<br><br>  protected render() {<br>    return html`&lt;div&gt;<br>      &lt;div&gt;<br>        Rows per page:<br>        &lt;select @change=&quot;${(e) =&gt; this.setPageSize(e.target.value)}&quot;&gt;<br>          ${[10, 20, 30, 40, 50].map(<br>            (pageSize) =&gt; html`<br>              &lt;option ?selected=&quot;${this.pageSize === pageSize}&quot;&gt;<br>                ${pageSize}<br>              &lt;/option&gt;<br>            `,<br>          )}<br>        &lt;/select&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        1-5 of 13<br><br>        &lt;button<br>          .disabled=${!this.hasPreviousPage}<br>          @click=&quot;${() =&gt; this.firstPage()}&quot;<br>        &gt;<br>          &lt;&lt;<br>        &lt;/button&gt;<br>        &lt;button<br>          .disabled=${!this.hasPreviousPage}<br>          @click=&quot;${() =&gt; this.previousPage()}&quot;<br>        &gt;<br>          &lt;<br>        &lt;/button&gt;<br>        &lt;button<br>          .disabled=${!this.hasNextPage}<br>          @click=&quot;${() =&gt; this.nextPage()}&quot;<br>        &gt;<br>          &gt;<br>        &lt;/button&gt;<br>        &lt;button<br>          .disabled=${!this.hasNextPage}<br>          @click=&quot;${() =&gt; this.lastPage()}&quot;<br>        &gt;<br>          &gt;&gt;<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;`;<br>  }<br>}<br><br>declare global {<br>  interface HTMLElementTagNameMap {<br>    &quot;pagination-controller&quot;: PaginationController;<br>  }<br>}</pre><p>And walla — we have a paginator.</p><h3>Make me pretty 💅!</h3><p>In order to add some sheek to our table, we need to add some styling.</p><p>In order to do so, we can use <a href="https://twind.style/">Twind</a> which provides a very easy to use Tailwind classes with Lit elements:</p><pre>npm install --save @twind/core @twind/with-web-components @twind/preset-autoprefix @twind/preset-tailwind<br><br>// or<br><br>pnpm add @twind/core @twind/with-web-components @twind/preset-autoprefix @twind/preset-tailwind<br><br>// or<br>yarn add @twind/core @twind/with-web-components @twind/preset-autoprefix @twind/preset-tailwind</pre><p>And define a configuration file:</p><pre>// twind.config.ts<br><br>import { defineConfig } from &#39;@twind/core&#39;<br>import presetTailwind from &quot;@twind/preset-tailwind&quot;;<br>import presetAutoprefix from &quot;@twind/preset-autoprefix&quot;;<br><br>export default defineConfig({<br>    presets: [presetTailwind(), presetAutoprefix()]<br>})</pre><p>Only then we can use the @withTwind decorator and enjoy Twind:</p><pre>import config from &#39;./../twind.config&#39;<br>import install from &quot;@twind/with-web-components&quot;;<br><br>const withTwind = install(config)<br><br><br>@customElement(&quot;my-table&quot;)<br>@withTwind<br>export class MyTable&lt;TData extends RowData&gt; extends LitElement {<br>  ....<br><br>  render() {<br>    ....<br>    return html`<br>      &lt;table class=&quot;border-collapse&quot;&gt;<br>       ....<br>    `;<br>  }<br>}</pre><p>You can take the styling from here 😄</p><p>I used <a href="https://flowbite.com/">flowbite</a>, which gave these incredible results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4H6AWpAmOo6Y69HHzozynw.png" /></figure><h3>Wrap Up</h3><p>In this article, we built a Web-Components based table with Lit &amp; and Tanstack Table. Then, we added styling using Twind.</p><p>Obviously there is a lot more to Tanstack Table which was not covered in the article such as filtering, column sizing, grouping and much more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1275049d53a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterator Pattern in TypeScript]]></title>
            <link>https://medium.com/@morkadosh/miterator-pattern-in-typescript-6244b4e08c7f?source=rss-5f9a8c663703------2</link>
            <guid isPermaLink="false">https://medium.com/p/6244b4e08c7f</guid>
            <dc:creator><![CDATA[Mor Kadosh]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 08:04:31 GMT</pubDate>
            <atom:updated>2023-09-24T08:04:56.008Z</atom:updated>
            <content:encoded><![CDATA[<p>The Iterator pattern is a widely recognized design pattern that offers an elegant solution for traversing objects seamlessly. In this article, we will dive deep into the practical application of this pattern, using a simple example to illustrate its power.</p><p>Consider a scenario where we have a class representing a rule engine. Each rule within the engine is represented as an object, containing a unique name and an execution method:</p><pre>interface Rule {<br>  name: string;<br>  execute(): void;<br>}</pre><p>The rule engine essentially acts as a repository for these rules, providing easy access and a mechanism for adding new ones:</p><pre>class RuleEngine {<br> private rules: Rule[] = [];<br>  <br>  public getRules() {<br>   return this.rules;<br>  }<br>  <br>  public addRule(rule: Rule) {<br>   if (!this.ruleExistsWithName(rule.name)) {<br>     this.rules.push(rule);<br>    }<br>  }<br>  <br>  private ruleExistsWithName(name: string) {<br>   return this.rules.find(rule =&gt; rule.name === name);<br>  }<br>}</pre><p>As evident, each rule is stored within an array, which implies that adding a new rule to the engine comes at an approximate cost of O(n).</p><p>Seems straightforward, right?</p><p>Now, picture another team needing to utilize this rule engine:</p><pre><br>const ruleEngine = new RuleEngine();<br><br>ruleEngine.addRule({<br> name: &#39;First Rule&#39;,<br>  execute: () =&gt; {<br>   // do something<br>  }<br>});<br><br>ruleEngine.addRule({<br> name: &#39;Second Rule&#39;,<br>  execute: () =&gt; {<br>   // do something<br>  }<br>});</pre><p>To execute these rules, one would naturally open the RuleEngine code and discover that getAllRules returns an array of rules. So, following the standard practice, we iterate over the rules array:</p><pre>const rules = ruleEngine.getAllRules();<br><br>rules.forEach((rule) =&gt; {<br>   rule.execute();<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/0*qQKbF2AIz3zCibme" /></figure><p>Seems like a success story in the making, right? Well, let’s see how this unfolds.</p><h3>Let the troubles begin…</h3><p>Initially, our rule engine worked like a charm during its first month in production. However, its popularity soared, with users adding millions of rules. At this point, the RuleEngine core team recognized that the naive implementation using an array was no longer feasible due to its prohibitive cost. Consequently, they decided to revamp the internal rule storage mechanism, opting for a simple hash map:</p><pre>class RuleEngine {<br> private rules: Record&lt;string, Rule&gt; = {};<br>  <br>  public getAllRules() {<br>   return this.rules;<br>  }<br>  <br>  public addRule(rule: Rule) {<br>   if (!this.ruleExistsWithName(rule.name)) {<br>     this.rules[rule.name] = rule<br>    }<br>  }<br>  <br>  private ruleExistsWithName(name: string) {<br>   return this.rules[name] !== undefined;<br>  }<br>}</pre><p>At this point, it becomes evident that our previous forEach approach no longer works, given that the rules are no longer stored in an array. Fortunately, the team employed TypeScript and caught this issue before it wreaked havoc in production. However, it meant that they had to make changes in code owned by another team. The RuleEngine acknowledged that their initial implementation exposed too many implementation details.</p><p><strong>Note</strong>: Although alternatives like Set or Map that provide iterators for keys and values exist, this article primarily focuses on the broader concept.</p><h3>The Iterator Pattern</h3><p>Fortunately, this predicament is a well-known challenge in Software Engineering, and, as with many other challenges, great minds have already devised a solution.</p><p>The Iterator pattern is a simple Design Pattern that equips clients with convenient methods to traverse Data Structures without requiring an in-depth understanding of their internal workings or structure.</p><p>In modern JavaScript, there are even more efficient ways to tackle this issue, but let’s start from the basics. Typically, an iterator adheres to the following interface::</p><pre>interface Iterator&lt;T&gt; {<br>  next: T;<br>  hasNext(): bool;<br>}</pre><p>With this interface in mind, we can create a class that, when given a RuleEngine, generates an iterator for rules:</p><pre>class RuleEngineIterator implements Iterator&lt;Rule&gt; {<br> private index: number;<br>  private rules: Rule[];<br>  <br>  constructor(ruleEngine: RuleEngine) {<br>   this.index = 0;<br>    this.rules = rules;<br>  }<br><br> next() {<br>   const rule = this.rules[this.index];<br>   this.index++;<br>   return rule;<br>  }<br>  <br> hasNext() {<br>   return this.index &lt; this.rules.length;<br>  }<br>}</pre><p>Now, traversing the rules becomes a straightforward task. Additionally, we’ll introduce a new method, createIterator, within the RuleEngine class to ensure flexibility and prevent the exposure of internal implementation details:</p><pre>public createIterator() {<br>  return new RuleEngineIterator(Object.values(this.rules));<br>}</pre><p>Now, let’s put into a test drive:</p><pre>const iterator = ruleEngine.createIterator();<br><br>while (iterator.hasNext()) {<br> const rule = iterator.next();<br>  rule.execute();<br>}</pre><p>Easy as Sunday Morning! We are now free to change the internal structure of the Rules Engine data strucutre without worrying how clients are going terators</p><h3>Modern JavaScript iterators</h3><p>JavaScript, as a ever evolving language provides us a pretty neat way for creating iterators, without creating more classes.</p><p>One way, is using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#generator_functions">Generators</a> . For example, let’s modify our createIterator method:</p><pre>public function* createIterator() {<br>const rulesList = Object.values(this.rules);<br>  for (let i = 0; i &lt; rulesList.length; i++) {<br>     yield rulesList[i];<br>  }<br>}</pre><p>Note the * sign which tells JavaScript to handle this function as a generator factory. Then, we simply iterate through the rules array, and yield each item of the array.</p><p>This let’s use use the iterator as following:</p><pre>let result = rulesIterator.next();<br><br>while(!result.done) {<br>  result.value.execute();<br>  result = rulesIterator.next();<br>}</pre><h3>Wrap Up</h3><p>The Iterator pattern has stood the test of time and remains a powerful tool. Surprisingly, many of us overlook its potential in our day-to-day coding endeavors. Leveraging iterators for our data structures ensures that clients using our code remain shielded from internal implementations, allowing us to make changes without the fear of breaking their workflows. It’s a win-win for both developers and end-users. Happy iterating!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6244b4e08c7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep your Design System safe from visual changes.]]></title>
            <link>https://medium.com/@morkadosh/keep-your-design-system-safe-from-visual-changes-9cd4b36c85e0?source=rss-5f9a8c663703------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cd4b36c85e0</guid>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[visual-testing]]></category>
            <category><![CDATA[snapshot-testing]]></category>
            <dc:creator><![CDATA[Mor Kadosh]]></dc:creator>
            <pubDate>Sat, 09 Sep 2023 12:00:50 GMT</pubDate>
            <atom:updated>2023-09-09T12:00:50.478Z</atom:updated>
            <content:encoded><![CDATA[<p>So your team’s UI/UX designer had a simple request to tweak one of our company’s sleek Design System components.</p><p>It seemed harmless at first, so we let it go live. But surprise, surprise! It ended up breaking another component that relied on the tweaked one, all because we forgot to give it a quick test spin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QSCSnmA4-5bQ0TGH" /></figure><p>Before you rush to undo the code, let’s kick back for a moment and think about what we can do to stop this mix-up from happening again.</p><p>In this article we’ll go over two main methods for testing our components for changes —<strong> Snapshot Tests</strong> and <strong>Visual Regression Tests</strong> (VRT).</p><h3>Option one — Snapshot testing</h3><p>Snapshot testing has long been a common practice in the world of modern frameworks and component-based design. Well-known testing tools like J<a href="https://jestjs.io/docs/snapshot-testing">est</a> and <a href="https://vitest.dev/guide/snapshot.html">Vitest</a> make it super easy to use. In simple terms, snapshot tests capture a function’s output and save it as a reference for future comparisons.</p><p>During subsequent test runs, the function’s output is checked against the saved snapshot. If they match, the test passes; if not, it fails. To fix failing tests, you just need to update the snapshots to reflect the new baseline. This process encourages developers to think carefully about their changes.</p><p>You can apply this concept to your components too. For example, let’s explore how it works with a basic <strong>Button</strong> component using Vitest (we’ll use <strong>tailwind</strong> here, but you can adapt it to your favorite framework):</p><pre>// Button.tsx<br><br>import { MouseEvent, ReactNode } from &quot;react&quot;;<br>import classnames from &quot;classnames&quot;;<br><br>export interface ButtonProps {<br>  children: ReactNode;<br>  onClick?(event: MouseEvent&lt;HTMLButtonElement&gt;): void;<br>  addClassName?: string;<br>}<br><br>export function Button({ children, onClick, addClassName }: ButtonProps) {<br>  const className = classnames(<br>    &quot;px-3 rounded text-xs py-1 bg-blue-500 text-white&quot;,<br>    addClassName,<br>  );<br>  return (<br>    &lt;button onClick={onClick} className={className}&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*kgU_HW_J9oEpbqGyEoIswQ.png" /></figure><p>And assuming we have another component, ButtonGroup that composes a group of buttons together:</p><pre>// ButtonGroup.tsx<br><br>import React, { ReactElement, isValidElement, cloneElement } from &quot;react&quot;;<br>import { ButtonProps } from &quot;./Button&quot;;<br><br>interface ButtonGroupProps {<br>  children: React.ReactElement&lt;ButtonProps&gt; | React.ReactElement&lt;ButtonProps&gt;[];<br>}<br><br>function getButtonClassName(<br>  index: number,<br>  children: ButtonGroupProps[&quot;children&quot;],<br>) {<br>  if (Array.isArray(children)) {<br>    if (index === 0) return &quot;rounded-none rounded-l-lg&quot;;<br>    if (children.length - 1 === index) return &quot;rounded-none rounded-r-lg&quot;;<br>    return &quot;rounded-none&quot;;<br>  }<br><br>  return &quot;&quot;;<br>}<br>export function ButtonGroup({ children }: ButtonGroupProps) {<br>  return (<br>    &lt;div className=&quot;flex&quot; role=&quot;group&quot;&gt;<br>      {React.Children.map(children, (child, index) =&gt; {<br>        if (!isValidElement(child)) {<br>          return child;<br>        }<br>        return cloneElement(child as ReactElement&lt;ButtonProps&gt;, {<br>          addClassName: getButtonClassName(index, children),<br>        });<br>      })}<br>    &lt;/div&gt;<br>  );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*bbW8v9g2Hn6hp8hT292yEQ.png" /><figcaption>A group of buttons playing nicely together</figcaption></figure><p>Let’s create our first snapshot test for the ButtonGroup component, using Vitest as the test runner, and <a href="https://testing-library.com/docs/react-testing-library/intro/">testing-library</a> as the renderer:</p><pre>// ButtonGroup.test.tsx<br><br>import { describe, expect, test } from &quot;vitest&quot;;<br>import { render } from &quot;@testing-library/react&quot;;<br>import { Button } from &quot;./Button.tsx&quot;;<br>import { ButtonGroup } from &quot;./ButtonGroup.tsx&quot;;<br><br>describe(&quot;ButtonGroup component&quot;, () =&gt; {<br>  test(&quot;Group with 3 buttons matches snapshot&quot;, () =&gt; {<br>    const { asFragment } = render(<br>      &lt;ButtonGroup&gt;<br>        &lt;Button&gt;Test1&lt;/Button&gt;<br>        &lt;Button&gt;Test2&lt;/Button&gt;<br>        &lt;Button&gt;Test3&lt;/Button&gt;<br>      &lt;/ButtonGroup&gt;,<br>    );<br><br>    expect(asFragment()).to.matchSnapshot();<br>  });<br><br>  test(&quot;Group with 2 buttons matches snapshot&quot;, () =&gt; {<br>    const { asFragment } = render(<br>        &lt;ButtonGroup&gt;<br>          &lt;Button&gt;Test1&lt;/Button&gt;<br>          &lt;Button&gt;Test2&lt;/Button&gt;<br>        &lt;/ButtonGroup&gt;,<br>    );<br><br>    expect(asFragment()).to.matchSnapshot();<br>  });<br>});</pre><p>Running the test using vitest run --environment jsdom creates a new __snapshots__ folder with a single file ButtonGroup.test.tsx.snap . This folder should be commited to your version control:</p><pre>// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html<br><br>exports[`ButtonGroup component &gt; Group with 2 buttons matches snapshot 1`] = `<br>&lt;DocumentFragment&gt;<br>  &lt;div<br>    class=&quot;flex&quot;<br>    role=&quot;group&quot;<br>  &gt;<br>    &lt;button<br>      class=&quot;px-3 rounded text-xs py-1 bg-blue-500 text-white rounded-none rounded-l-lg&quot;<br>    &gt;<br>      Test1<br>    &lt;/button&gt;<br>    &lt;button<br>      class=&quot;px-3 rounded text-xs py-1 bg-blue-500 text-white rounded-none rounded-r-lg&quot;<br>    &gt;<br>      Test2<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/DocumentFragment&gt;<br>`;<br><br>exports[`ButtonGroup component &gt; Group with 3 buttons matches snapshot 1`] = `<br>&lt;DocumentFragment&gt;<br>  &lt;div<br>    class=&quot;flex&quot;<br>    role=&quot;group&quot;<br>  &gt;<br>    &lt;button<br>      class=&quot;px-3 rounded text-xs py-1 bg-blue-500 text-white rounded-none rounded-l-lg&quot;<br>    &gt;<br>      Test1<br>    &lt;/button&gt;<br>    &lt;button<br>      class=&quot;px-3 rounded text-xs py-1 bg-blue-500 text-white rounded-none&quot;<br>    &gt;<br>      Test2<br>    &lt;/button&gt;<br>    &lt;button<br>      class=&quot;px-3 rounded text-xs py-1 bg-blue-500 text-white rounded-none rounded-r-lg&quot;<br>    &gt;<br>      Test3<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/DocumentFragment&gt;<br>`;</pre><p>Now, a fellow developer of yours adds a “tiny” change to the Button component to fullfil a product requirement and adds margins around the Button component:</p><pre>// Button.tsx <br><br>const className = classnames(<br>  &quot;... m-1&quot;,<br>  addClassName,<br>);</pre><p>Reckless developer does not test all components using this Button and are possibly affected by this change, for example the ButtonGroup component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*tdePcX35NdGu0_no8S8BUA.png" /><figcaption>Yak!</figcaption></figure><p>Luckily, developer is being held from merging by the Snapshot tests failing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOgwPmjmnmI_-m1GCqdSDQ.png" /></figure><p>Now hopefully they will review the change and revisit their proposed solution.</p><p>It appears that Snapshot testing can indeed serve as a valuable tool for safeguarding our components against potential errors. However, it is essential to acknowledge certain significant drawbacks associated with this approach:</p><ol><li><strong>Complex Snapshot Reports</strong>: The process of interpreting Snapshot test failure reports may not always be straightforward. This is primarily because it necessitates a manual comparison of raw HTML outputs, often requiring us to execute the impacted components manually in order to fully comprehend the extent of the issue.</li><li><strong>Visual Incongruity</strong>: On occasion, modifications to our code can result in changes to the generated HTML output, even when there is no discernible visual alteration. This incongruity can complicate the assessment of whether a change is truly problematic.</li></ol><p>To illustrate these concepts, we will proceed with a modification to our Button component. In this adjustment, we will substitute the existing horizontal padding with the inclusion of horizontal margins around its child elements. It’s worth noting that while this modification may appear unconventional, it serves purely as an example:</p><pre>--- a/src/Button.tsx<br>+++ b/src/Button.tsx<br>@@ -9,12 +9,12 @@ export interface ButtonProps {<br> <br> export function Button({ children, onClick, addClassName }: ButtonProps) {<br>   const className = classnames(<br>-    &quot;px-3 rounded text-xs py-1 bg-blue-500 text-white&quot;,<br>+    &quot;rounded text-xs py-1 bg-blue-500 text-white&quot;,<br>     addClassName,<br>   );<br>   return (<br>     &lt;button onClick={onClick} className={className}&gt;<br>-      {children}<br>+      &lt;div className=&quot;mx-3&quot;&gt;{children}&lt;/div&gt;<br>     &lt;/button&gt;<br>   );<br> }</pre><p>As you can observe, even though we’ve thrown in an extra div layer and played around with class names, there’s really no noticeable change from the user’s point of view. Surprisingly (or not), the snapshot tests are failing, disclosing the weakness of this method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*I7uc9UCZygHZYeaH_jlvbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H3H5FG1PgIN-55gVOhWM4w.png" /></figure><p>What can we do next to make sure our tests actually catch real visual changes?</p><h3>Visual Regression Tests to the rescue</h3><p>In contrast to snapshot tests, Visual Regression Tests capture real screenshots of our components and compare them across multiple test runs. Leveraging these tests as our primary component visual testing tools will play a major role in guaranteeing that our modifications do not adversely affect the appearance of our components. Furthermore, some of these tests also evaluate changes across various browsers and viewport sizes, enhancing their reliability and coverage.</p><p>There are a few tools out there such as <a href="https://github.com/garris/BackstopJS">Backstop</a> and <a href="https://www.chromatic.com/">Chromatic</a> for that purpose.</p><p>Today I will focus on Chromatic, as this is the tool of choice of my team.</p><p><strong>Chromatic </strong>is a commercial enterprise that, in addition to furnishing an enterprise-grade solution, also offers a free version Visual Regression Testing (VRT) tool. This tool is designed to seamlessly integrate with your <a href="https://storybook.js.org/">Storybook</a> configuration and conduct Visual Regression tests on your components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*9Rezv796puXutsxK.png" /></figure><p>Chromatic offers a cloud-based platform for visual component review. It uses your Git history to link commits with component visuals, maintaining baseline snapshots. Approved changes replace the snapshot for that component on the branch, becoming the new baseline upon main branch merge. Setting up Chromatic is detailed in the <a href="https://www.chromatic.com/docs/">official docs</a>; this article focuses on how it works and provides practical insights.</p><p>So, at this point I’ll assume that Chromatic is plugged into your Project. Don’t worry, they have a great and incredebly easy onboarding process.</p><p>Run npx chromatic --project-token=**** (replace the **** with the access token provided by chromatic). Now, you should see Chromatic in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9Q0rKPwhUx97tbfnH1_8g.png" /></figure><p>Obviously no visual changes to our components, since we didn’t change anything 😃</p><p>When you log in to the Chromatic platform, you’ll find a list of “builds.” Each build corresponds to a Chromatic branch paired with another branch. Next to each build, you’ll notice a status circle. <strong>Green </strong>means that the build passed without finding any visual changes. <strong>Yellow </strong>requires<strong> </strong>a review, and <strong>Red</strong> are declinbed builds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cfVKB1V__Bbg2BbI6F5UA.png" /></figure><p>Now, let’s revert the modifications we made to the Button earlier. We’ll eliminate the inner divand reinstate the padding. In doing so, we shouldn’t anticipate any tangible visual alterations to our components.</p><pre>--- a/src/Button.tsx<br>+++ b/src/Button.tsx<br>@@ -9,12 +9,12 @@ export interface ButtonProps {<br> <br> export function Button({ children, onClick, addClassName }: ButtonProps) {<br>   const className = classnames(<br>-    &quot;rounded text-xs py-1 bg-blue-500 text-white&quot;,<br>+    &quot;rounded text-xs py-1 bg-blue-500 text-white px-3&quot;,<br>     addClassName,<br>   );<br>   return (<br>     &lt;button onClick={onClick} className={className}&gt;<br>-      &lt;div className=&quot;mx-3&quot;&gt;{children}&lt;/div&gt;<br>+      {children}<br>     &lt;/button&gt;<br>   );<br> }</pre><p>Let’s rerun Chromatic once more, and as anticipated, we shouldn’t anticipate any visual changes in our components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-7k2Q5h01OVrlCe76UnfQ.png" /></figure><p>That’s fantastic! If we were using snapshot tests, our tests would fail right now. However, because this change doesn’t actually impact users, Chromatic allows it. It’s a safe adjustment to make.</p><p>Now, let’s explore the outcome when we introduce a visual change. We’ll add a margin to the Button component and then execute Chromatic, just as our fellow developer tried to:</p><pre>--- a/src/Button.tsx<br>+++ b/src/Button.tsx<br>@@ -9,7 +9,7 @@ export interface ButtonProps {<br> <br> export function Button({ children, onClick, addClassName }: ButtonProps) {<br>   const className = classnames(<br>-    &quot;rounded text-xs py-1 bg-blue-500 text-white px-3&quot;,<br>+    &quot;rounded text-xs py-1 bg-blue-500 text-white px-3 mx-1&quot;,<br>     addClassName,<br>   );<br>   return (</pre><p>Whoopsi! Chromatic caught us off the guard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8ES275jzfdXHa8YKxsKGw.png" /></figure><p>And in the Chromatic platform we can review this change and decide what to do next:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRYjLDB8IRfTU8y3cjx21w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6ACaYZCvfu8ePQXx-C1oA.png" /></figure><p>Chromatic detected a visual change on <strong>ButtonGroup</strong> due to a change in <strong>Button!</strong></p><p>Clicking on the component row, we can now review the proposed change and decide if we want to accept or decline it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HGi9WwPvo1iYB-WYzjgt8Q.png" /></figure><p>If we opt to accept this modification, it will serve as our new baseline, much like updating Snapshots. However, if we choose to decline it, we’ll need to rectify the change and then rerun Chromatic.</p><p>Simple but yet awesome.</p><h3>Chromatic for real teams</h3><p>To streamline the process, it’s highly recommended to integrate Chromatic into your <strong>CI</strong> system. When initially running Chromatic, use your main branch as the starting point. Chromatic associates snapshot baselines with corresponding commit hashes. On each branch, Chromatic compares these baselines with branch-specific snapshots. If changes are accepted, they become new baselines upon merging into the main branch.</p><p><strong>A helpful tip</strong>: Configure your pipelines to fail on branches with visual changes. This encourages developers to promptly address any visual regressions.</p><p>For detailed information on automating Chromatic, consult the Chromatic documentation for your chosen CI system, and set up Chromatic for your team’s benefit.</p><h3>Appendix 1: GitLab CI and Squash Merge</h3><p>In our self-hosted GitLab setup, we use squash merging to the main branch by default. T</p><p>his posed a challenge with Chromatic because GitLab generates a new squashed merge commit hash when merging feature branches into the main branch.</p><p>As a solution, after merging a branch into the main branch, we run Chromatic on the main branch with the --auto-accept-changes option to create new baselines associated with the squashed merge commit hash.</p><p>Since we primarily use GitLab for CI and Jenkins for deployment, we set up an automated Jenkins job to perform this task. Developers who encounter synchronization issues with Chromatic can resolve them by rebasing or merging the main branch into their feature branches before running Chromatic.</p><p>Read more about this issue <a href="https://www.chromatic.com/docs/gitlab#gitlab-squashrebase-merge-and-the-main-branch">here</a>.</p><h3>Wrap Up</h3><p>Safeguarding our components against unintended changes is crucial and achievable. With proper testing, we ensure users experience our products as intended, avoiding the inconvenience of code reversions or disrupting our colleagues’ work.</p><p>For those with Design Systems or custom components, I highly recommend integrating the kind of tests that fits your team.</p><p>Above all, prioritize tools that offer seamless automation for developers. Let’s make testing a breeze and keep those smiles on our developers’ faces!😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cd4b36c85e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate your Code Reviews with Danger]]></title>
            <link>https://medium.com/@morkadosh/automate-your-code-reviews-with-danger-392339683fcd?source=rss-5f9a8c663703------2</link>
            <guid isPermaLink="false">https://medium.com/p/392339683fcd</guid>
            <category><![CDATA[danger]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mor Kadosh]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 07:09:26 GMT</pubDate>
            <atom:updated>2023-09-01T08:25:20.761Z</atom:updated>
            <content:encoded><![CDATA[<p>So, picture this: You’re in your development team, and a developer commits a change to a super-secret file, and boom, it sneaks right into production. Or someone adds a shiny new package but forgets to update the lockfile, and suddenly, your environments are as broken as a skateboard on a gravel road.</p><p>Now, here’s the kicker: a well-done code review could’ve stopped those slip-ups cold. But, let’s face it, developers are just folks like you and me, and folks tend to forget stuff.</p><p>Instead of putting all our eggs in the “hope developers remember” basket, why not automate the process? Enter Danger, our trusty code watchdog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*diSdMWHj51v_HYUN.png" /></figure><p>Originally in Ruby, Danger now comes in different flavors, including TypeScript, Python, Kotlin, and Swift. In this piece, we’re diving headfirst into the TypeScript version.</p><p>Danger is all about one simple thing — the Dangerfile. This file holds the rules we want to slap on every pull request itching to get into our codebase.</p><p>Enough chit-chat, let’s rock ’n’ roll and write our very first Danger rule!</p><p>Imagine you’ve got a codebase with a file so sensitive and volatile, that each change to it, from some reason, might cause a serious damage to production— nobody should ever touch it (seriously, if you have such a file, why?).</p><p>A smarty-pants fellow suggest writing a new danger rule to fail MRs that modify this file.</p><p>Here’s what the Dangerfile might look like:</p><pre>// dangerfile.ts<br>import { danger, fail } from &#39;danger&#39;;<br>import * as path from &#39;path&#39;;<br><br>function failIfSensitiveFileWasChanged() {<br>    const modifiedFiles = danger.git.modified_files;<br>    const sensitiveFiles = [path.relative(__dirname, &#39;sensitive-file.ts&#39;)];<br>    const changedSensitiveFiles = modifiedFiles.reduce((changedFilesAcc, file) =&gt; {<br>        if (sensitiveFiles.includes(file)) {<br>            return [...changedFilesAcc, file];<br>        }<br>        return changedFilesAcc;<br>    }, []);<br>    if (changedSensitiveFiles.length &gt; 0) {<br>        fail(`Oops! Sensitive files got a makeover. Better revert those changes on these files: ${JSON.stringify(changedSensitiveFiles)}`);<br>    }<br>}<br>failIfSensitiveFileWasChanged();</pre><p>This code is about as straightforward as a Sunday morning. First, we ask Danger for the list of files modified in the branch with danger.git.modified_files (behind the scenes, Danger&#39;s doing a diff between the default branch and the current one). Then, we simply compare that list with our sensitive files list. If there&#39;s a match, we slam on the brakes and leave a “friendly” note.</p><p>But hold on! How do we test this bad boy before shipping it to the actual CI system? Well, Danger’s got our back with a local interface.</p><p>Toss this script into your package.json:</p><pre>{<br>  &quot;name&quot;: &quot;my-danger-test&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;danger:local&quot;: &quot;danger local&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;danger&quot;: &quot;^11.2.8&quot;,<br>    &quot;typescript&quot;: &quot;^5.2.2&quot;<br>  }<br>}</pre><p>Now, to give this rule a test ride, create a fresh local branch and make a change to your sensitive file:</p><pre>git checkout -b test-danger &amp;&amp; echo &quot; &quot; &gt;&gt; sensitive-file.ts &amp;&amp; git add sensitive-file.ts &amp;&amp; git commit -m &quot;testing danger&quot;</pre><p>Run yarn danger:local. Whoopsi!, we modified a sensitive file (Duh), and Danger doesn’t like that. It caught that local mishap right in its tracks, just as we wanted.</p><p>Now, as our rule proved to work fine, we can add this process to our Ci systems.</p><p>Start by adding this script to your package.json:</p><pre>{<br>  &quot;name&quot;: &quot;my-danger-test&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;danger:local&quot;: &quot;danger local&quot;,<br>    &quot;danger:ci&quot;: &quot;danger ci --failOnErrors&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;danger&quot;: &quot;^11.2.8&quot;,<br>    &quot;typescript&quot;: &quot;^5.2.2&quot;<br>  }<br></pre><p>Now, depending on your CI environment, add the needed code to run the yarn danger:ci script on each introduced MR.</p><p>In Gitlab CI, it might look as following:</p><pre>Danger (Automated Code Review):<br>  stage: ...<br>  image: ...<br>  variables:<br>    DANGER_GITLAB_API_TOKEN: $GITLATOKEN<br>  script:<br>    - yarn danger:ci</pre><p>Two quick things to keep in mind:</p><ol><li>The --failOnErrors flag tells Danger to throw a fit in CI whenever something goes south.</li><li>DANGER_GITLAB_API_TOKEN—don&#39;t forget to toss Danger a token so it can chat with your merge requests. Check the docs for the lowdown.</li></ol><p>Now, when I open a new MR with the evil change in it, Danger blocks my MR from merging:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*Y9fJIcZ_0bzwjFI1mkBq1A.png" /></figure><p>Before we wrap up, let me drop some wisdom from our own journey with this tool:</p><ul><li>When in doubt, go with “Fail” instead of “Warn.” Warnings? They’re like whispers in the wind; folks often ignore them. Same goes for Danger — if a Danger rule can save your codebase from disaster, go ahead and slap that “Fail” label on it.</li><li>Keep your fail/warn messages informative and actionable. Don’t get to the point where individuals reach out to you with panic. Make sure the message instructs the developers what they should do next in order to pass the barrier.</li><li>For async Danger rules, don’t forget to use schedule.</li><li>Get your team in on the action. At first, they might raise an eyebrow, but watch how fast Danger becomes your trusty sidekick, and how quickly folks jump in to add new rules.</li></ul><p>And there you have it! You’re all set to automate those code reviews. No more pleading with your team, “Please don’t touch this file,” because the Danger bot’s got your back. It’s time to level up your code quality game, the easy way. Happy coding, amigo! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=392339683fcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serve a Create-React-App Application With Nest.Js for Better SEO and Social Sharing.]]></title>
            <link>https://medium.com/swlh/serve-a-create-react-app-application-on-with-nest-js-for-better-seo-and-social-sharing-7093a71d3fc3?source=rss-5f9a8c663703------2</link>
            <guid isPermaLink="false">https://medium.com/p/7093a71d3fc3</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[create-react-app]]></category>
            <category><![CDATA[seo]]></category>
            <dc:creator><![CDATA[Mor Kadosh]]></dc:creator>
            <pubDate>Thu, 23 Jul 2020 18:45:26 GMT</pubDate>
            <atom:updated>2020-07-25T08:06:42.606Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago, I started working on an exciting side project. I chose to work with <strong>create-react-app</strong> on the client-side, and <strong>Nest.js</strong> on the server, both great solutions for my needs.</p><p>After a few months of the product running on the wild, I turned to improve my websites’ SEO metrics.</p><p>My journey began as I started to follow every piece of advice I found in this field, which was pretty new to me.</p><p>From improving the <a href="https://developers.google.com/web/tools/lighthouse"><strong>Lighthouse</strong></a><strong> </strong>to a near-perfect score, and to add unique meta tags and title for every page of the app. As some of my app’s pages are user-content based, those meta tags often were totally dynamic.</p><p>To do so, I used a great library called <a href="https://github.com/nfl/react-helmet"><strong>react-helmet</strong></a><strong> </strong>which was super easy to implement.</p><p><strong>The problem </strong>— Google and the social media platforms such as Facebook and Twitter couldn’t crawl those dynamic metadata tags. It is true that Google’s crawlers improved tremendously and can even execute Javascript nowadays, but It never worked to me. Even after I tried to follow the techniques suggested in <a href="https://medium.com/mixed-marketing-technology/our-solution-to-make-seo-work-for-a-react-js-site-rankwatch-blog-9a311b86fb5f">this post</a>.</p><p>Than I began exploring the option of migrating to <strong>Next.js</strong> which is without a doubt the best and most robust solution for SSR with React (server side rendering) there is out there.</p><p>After spending a handful of hours trying to migrate my app, it started to look as a bad direction for me. I’m not saying it wasn’t possible, but probably not worth it in my case.</p><p>I than found the following vague documentation page in the official create-react-app website: <a href="https://create-react-app.dev/docs/title-and-meta-tags/#generating-dynamic-meta-tags-on-the-server">https://create-react-app.dev/docs/title-and-meta-tags/#generating-dynamic-meta-tags-on-the-server</a> which I didn’t know before.</p><p>In short, CRA suggests to edit the static <strong>index.html</strong> by adding <strong>placeholders</strong> where the static meta and title tags used to be, and then serve the app on the server.</p><p>As I couldn’t find any proper tutorial or guidance that shows how to do that with CRA &amp; Nest.js stack, I decided to write one myself.</p><p>In this guide, we will create a simple recipes app with CRA &amp; Nest, and we will implement some techniques that will allow crawlers to get the dynamic metadata from our app, and display it correctly. After that, we will create a dynamic sitemap for our app, to make our SEO even better.</p><h3>Agenda</h3><ol><li>Create a simple app with CRA and Nest.js.</li><li>Serve the app from Nest.js and add <strong>dynamic meta tags</strong></li><li>Make the app more discoverable by implementing a dynamic <strong>sitemap</strong></li></ol><h3>The Server</h3><p>If you don’t have the Nest.js cli, run:</p><pre>yarn global add @nestjs/cli</pre><pre># or</pre><pre>npm install -g @nestjs/cli</pre><p>We’ll start of by creating the server side of our app:</p><pre>nest new cookbook-server</pre><p>Let’s create a simple <strong>RecipeModule </strong>that will contain all the pieces needed to fetch recipes from our server:</p><pre>nest g module recipe<br>nest g service recipe<br>nest g controller recipe</pre><p><em>For simplicity, we will use static server data, but real-world apps will probably use a database or any other source of data. In this tutorial I used </em><a href="https://github.com/raywenderlich/recipes/blob/master/Recipes.json"><em>https://github.com/raywenderlich/recipes/blob/master/Recipes.json</em></a></p><p>And the code:</p><h4>recipe.module.ts:</h4><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { RecipeService } from &#39;./recipe.service&#39;;<br>import { RecipeController } from &#39;./recipe.controller&#39;;</pre><pre>@Module({<br>  providers: [RecipeService],<br>  controllers: [RecipeController]<br>})<br>export class RecipeModule {}</pre><h4>recipe.controller.ts:</h4><pre>import { Controller, <strong><em>Get</em></strong>, NotFoundException, Param } from &#39;@nestjs/common&#39;;<br>import { RecipeService } from &#39;./recipe.service&#39;;</pre><pre>@Controller(&#39;api/recipe&#39;)<br>export class RecipeController {<br>  constructor(private readonly recipeService: RecipeService) {}</pre><pre>  @Get()<br>  public async getAll() {<br>    return this.recipeService.getAllRecipes();<br>  }</pre><pre>  @Get(&#39;:name&#39;)<br>  public async getOne(@Param(&#39;name&#39;) name: string) {<br>    const recipe = this.recipeService.getRecipeByName(name);<br>    if (!recipe) {<br>      throw new NotFoundException();<br>    }<br>    return recipe;<br>  }<br>}</pre><p><strong>Note:</strong> I set the controller prefix to be api/recipe.</p><p>Ideally, we would use Nest’s setGlobalPrefix which gives us the ability to prefix all api paths automatically.</p><p>Later we will find out that using setGlobalPrefix is not suitable for us since we will create a non-api controller, and currently there’s no way to exclude this global prefix for specific controllers.</p><p>Theres’ an open issue for that: <a href="https://github.com/nestjs/nest/issues/963">https://github.com/nestjs/nest/issues/963</a></p><h4>recipe.service.ts:</h4><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import data from &#39;./recipe.data&#39;;<br><br>@Injectable()<br>export class RecipeService {<br>  public getAllRecipes() {<br>    return data;<br>  }<br><br>  public getRecipeByName(name: string) {<br>    return data.find(recipe =&gt; recipe.name === name);<br>  }<br>}</pre><p>And that’s it…for now.</p><p>We got our recipe cookbook up and running. Let’s jump to the client side.</p><h3>The Client</h3><p>In this section we will not implement the client app, but assume it’s existence.</p><p>The app we’ll work with 2 routes: recipe list and recipe page:</p><pre>import React from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import { RecipeList } from &#39;./RecipeList&#39;;<br>import {Switch, Route} from &#39;react-router&#39;;<br>import {BrowserRouter} from &#39;react-router-dom&#39;;<br>import RecipePage from &quot;./RecipePage&quot;;<br>function App() {<br>    return (<br>        &lt;div className=&quot;App&quot;&gt;<br>          &lt;BrowserRouter&gt;<br>            &lt;Switch&gt;<br>              &lt;Route path={&#39;/recipe/:name&#39;} exact component={RecipePage} /&gt;<br>              &lt;Route path={&#39;/&#39;} component={RecipeList} /&gt;<br>            &lt;/Switch&gt;<br>          &lt;/BrowserRouter&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default App;</pre><p>The exact implementation details of each piece/component here is not the main focus of this article, so I will leave it to the reader.</p><p>Now, as our app is deployed, and our users are happy, John, who really really liked our Pizza recipe, wants to share it with his friends on Facebook.</p><p>So John goes to the page, copies the link and pastes it on Facebook. What will he see?</p><p>To answer this question, we’ll have to be introduced to the <a href="https://www.ogp.me/"><strong>open graph</strong> </a>protocol.</p><p>In short, this protocol uses meta tags on our webpage in order to generate meaningful shareable data. For example, if you ever shared a news article from CNN for example, it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*IWQYciXwdmA6eaTMg3y2WQ.png" /></figure><p>The first solution I came across to was <a href="https://github.com/nfl/react-helmet">react-helmet</a> which allows us to add raw html tags to our web page from within React components. So at the time I thought, if Google can run JS, and I can easily implement react-helmet on my side, it could be enough. Is it?</p><p>Searching online for a react solution for dynamic meta tags, you’ll probably come across <a href="https://github.com/nfl/react-helmet">react-helmet</a>.</p><p>react-helmet is a great and easy to use library, that simply allows you to manage and change the document head. So, if we use it in our recipe page, it should add them open-graph and title tags to our page. Sound perfect right?</p><p>Let’s try give it a try.</p><p>Assuming this code is implemented in the <em>Recipe Page:</em></p><pre>&lt;Helmet&gt;<br>    &lt;title&gt;My Recipes - {data.name}&lt;/title&gt;<br>    &lt;meta property=&quot;og:title&quot; content={`My Recipes - ${data.name}`} /&gt;<br>    &lt;meta property=&quot;og:description&quot; content={data.description} /&gt;    <br>    &lt;meta property=&quot;og:image&quot; content={data.imageURL} /&gt;<br>&lt;/Helmet&gt;</pre><p>Easy.</p><p>Now, let’s try to crawl a sample page with open graph.</p><p><em>To do so locally, I used a chrome extension called </em><a href="https://chrome.google.com/webstore/detail/open-graph-preview/ehaigphokkgebnmdiicabhjhddkaekgh?hl=en"><em>Open Graph Preview</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*hJsEvXVGjGc_QFqH0zI5Xw.png" /></figure><p>No Pizza for John🍕😥</p><p>But what happens if we use the actual browser and visit the same URL?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*BtJlHiUKCSstzVJNVrCo1g.png" /></figure><p>At this point, I came across the <a href="https://medium.com/mixed-marketing-technology/our-solution-to-make-seo-work-for-a-react-js-site-rankwatch-blog-9a311b86fb5f">following post </a>that demonstrates how to solve this exact problem. TL;DR, if you manage to render your page completely in less then ~5 seconds, then your’e all set. Not my case though. <strong>For me</strong>, it didn’t work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*FQokcOixXZwq54Ab.jpg" /><figcaption>I wish it worked for me as well.</figcaption></figure><p>So are we done with react-helmet? no sir.</p><p>As our final result will not render React on the server like Next and similar do, but will use a different technique, most of our code will still run on the client side.</p><p>Therefore, it’s still important to set the meta tags and title for every page of our app, so our users will be able to see them (mostly the title in this case).</p><p>Remember:<em> </em><strong><em>you are building an app for users, not for search engines.</em></strong></p><h3>Generating the meta tags on the server</h3><p>Back to the official CRA documentation: <a href="https://create-react-app.dev/docs/title-and-meta-tags/">https://create-react-app.dev/docs/title-and-meta-tags/</a></p><p>To some it up, CRA team suggests that this problem could be solved by implementing some changes to our web server.</p><p>Now we will see how it is possible to be made with Nest.</p><h3>Configuration</h3><p>As this article does not focus on how to build a complete application from scratch, I will assume that your app can handle configuration loading.</p><p>In the code examples below, I will make a use of a configService which loads an environment file (.env ) into memory, and make every configuration accessible via get method. Similarly to the <a href="https://docs.nestjs.com/techniques/configuration">official docs</a>.</p><p>The only configuration I added for this article is the build path of the create-react-app. For instance:</p><pre>CLIENT_BUILD_PATH=/var/www/build</pre><h3>Serving the static assets</h3><p>Now we’ll create a new <strong>module</strong>, <strong>controller</strong> and <strong>service</strong> to handle our client app.</p><p><strong><em>Side Note:</em></strong><em> </em>Why not using the default app.module for that? keep reading to find out.</p><p>I named this module client but feel free to name it better:</p><pre>nest g module client<br>nest g controller client<br>nest g service client</pre><h4><strong>client.controller.ts:</strong></h4><pre>import { Controller, <strong><em>Get </em></strong>} from &#39;@nestjs/common&#39;;<br>import { ClientService } from &#39;./client.service&#39;;<br><br>@Controller()<br>export class ClientController {<br>  constructor(private readonly clientService: ClientService) {}<br><br>  @Get(&#39;*&#39;)<br>  public async get() {<br>    return this.clientService.getApp();<br>  }<br>}</pre><p><strong>NOTE!</strong> we used a wildcard route here. make sure that <strong>ClientController</strong> is loaded <strong>last</strong>. As order <strong>does matter </strong>when it comes to routes, we don’t want every request to be caught here.</p><h4>client.service.ts</h4><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import * as fs from &#39;fs&#39;;<br>import * as <strong><em>path </em></strong>from &#39;path&#39;;<br><br>@Injectable()<br>export class ClientService {<br>  public async getApp() {<br>    const basePath = this.configService.get(&#39;CLIENT_BUILD_PATH&#39;);<br>    const filePath = path.resolve(path.join(basePath, &#39;index.html&#39;));<br>    return new <strong><em>Promise</em></strong>((resolve, reject) =&gt; {<br>      fs.readFile(filePath, &#39;utf8&#39;, (err: NodeJS.ErrnoException, data: string) =&gt; {<br>        if (err) {<br>          reject(err);<br>        } else {<br>          resolve(data);<br>        }<br>      });<br>    });<br>  }<br>}</pre><p>We’re set to keep going, but 2 notes first:</p><ol><li>Our client controller is <strong>not prefixed</strong> with as I would like to take advantage of the / route. You can do otherwise.</li><li>If you use a <strong>response interceptor,</strong> you will probably need to change it in such way that <strong>only</strong> responses from API calls are intercepted, for example:</li></ol><pre>@Injectable()<br>export class TransformInterceptor&lt;T&gt; implements NestInterceptor&lt;T, Response&lt;T&gt;&gt; {<br>  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;Response&lt;T&gt;&gt; {<br>    const response = context.switchToHttp().getResponse();<br>    const arg = context.getArgByIndex(0);<br>    if (arg &amp;&amp; !arg.route.path.includes(&#39;api&#39;)) {<br>      return next.handle();<br>    }</pre><pre>.....<br>}</pre><p>So what happens now if we open the app in the browser?</p><p>Well, not much:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtYC6wWWZvGdALNWk7wY5w.png" /></figure><p>Well, we could pretty much expect that, no?</p><p>As our <strong>index.html</strong> file requests for the static assets (js, css, manifest), and since our server does not have an appropriate way of dealing them, they failed to load.</p><p>One possible technique we can apply here is by adding a <strong>middleware </strong>to our client module:</p><p>Create a file client.middleware.ts:</p><pre>import { Injectable, NestMiddleware } from &#39;@nestjs/common&#39;;<br>import { Request, Response } from &#39;express&#39;;<br>import { AppService } from &#39;./app.service&#39;;</pre><pre>@Injectable()<br>export class ClientMiddleware implements NestMiddleware {<br>  constructor(private readonly clientService: ClientService) {}<br>  async use(req: Request, res: Response, next: () =&gt; void) {<br>    if (/[^\\/]+\.[^\\/]+$/.test(req.path)) {<br>      const file = getAssetPath(req.path);<br>      res.sendFile(file, (err) =&gt; {<br>      if (err) {<br>       res.status(err.status).end();<br>      }<br>     });<br>    } else {<br>      return next();<br>    }<br>  }<br>}</pre><p>Where getAssetPath is simply a utility function that will help us find the asset on the server:</p><pre>import * as path from &#39;path&#39;<br>...</pre><pre>getAssetPath(url: any) {<br>  const basePath = this.configService.get(&#39;CLIENT_BUILD_PATH&#39;);<br>  return path.join(basePath, url);<br>}</pre><p><strong>Note: </strong>I used a pretty simple way to check if the requested resource is a file or not, feel free to improve it.</p><pre>@Module({<br>  providers: [ClientService],<br>  controllers: [ClientController]<br>})<br>export class ClientModule{<br>  configure(consumer: MiddlewareConsumer) {<br>    consumer<br>      .apply(ClientMiddleware)<br>      .forRoutes(ClientController);<br>  }<br>}</pre><p>Let’s test our app again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8F2fjj3TerRZf-g9iCGgQ.png" /></figure><p>It works!</p><p>Now we’ll navigate to a recipe page and see what happens : <a href="http://localhost:5000/recipe/Big%20Night%20Pizza.."><strong>http://localhost:5000/recipe/Big%20Night%20Pizza</strong></a></p><p>As we can see, the title and meta tags <strong>did change</strong>. But does it mean we are done? probably not.</p><p><em>This is the point when some of the crawlers might read your meta tags, but it is not guaranteed. From my own experience with a real-world app, they didn’t.</em></p><p>A quick test with open graph shows that our work is not finished yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*3Qy9JIrTd_acHo8PzuJXuQ.png" /></figure><p>As you can imagine, the crawler didn’t run our Javascript code, but only fetched the static tags in our index.html file.</p><p>Then as advised by the CRA docs, we’ll replace the static tags with some placeholders, which will be then replaced with real values:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;%PUBLIC_URL%/favicon.ico&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>    &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt;<br><strong>    &lt;meta<br>      name=&quot;description&quot;<br>      content=&quot;__PAGE_DESCRIPTION__&quot;<br>    /&gt;</strong><br>    &lt;link rel=&quot;apple-touch-icon&quot; href=&quot;%PUBLIC_URL%/logo192.png&quot; /&gt;<br>    &lt;link rel=&quot;manifest&quot; href=&quot;%PUBLIC_URL%/manifest.json&quot; /&gt;<br><strong>    &lt;title&gt;__PAGE_TITLE__&lt;/title&gt;<br>    &lt;meta property=&quot;og:title&quot; content=&quot;__PAGE_TITLE__&quot; /&gt;<br>    &lt;meta property=&quot;og:description&quot; content=&quot;__PAGE_DESCRIPTION__&quot; /&gt;<br>    &lt;meta property=&quot;og:image&quot; content=&quot;__PAGE_IMAGE__&quot; /&gt;</strong><br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Building the client app withyarn build, and crawling the app once again now yields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*vNP9kV2PwUEfg1z5yBZi9g.png" /></figure><p>Ok, so now all we have to do is to parse the served index.html file, fetch the recipe metadata and replace the placeholders in the file. We’ll do so by changing the implementation of getApp to accept some metadata attributes, and replace the placeholders with them:</p><h4><strong>client.service.ts</strong></h4><pre>interface IPageMetadata {<br>  title?: string;<br>  description?: string;<br>  image?: string;<br>}<br>...</pre><pre>public async getApp(<strong>pageMetadata: IPageMetadata = DEFAULT_META</strong>) {<br>  const basePath = this.configService.get(&#39;CLIENT_BUILD_PATH&#39;);<br>  const filePath = path.resolve(path.join(basePath, &#39;index.html&#39;));<br>  return new <strong><em>Promise</em></strong>((resolve, reject) =&gt; {<br>    fs.readFile(filePath, &#39;utf8&#39;, (err: NodeJS.ErrnoException, data: string) =&gt; {<br>      if (err) {<br>        reject(err);<br>      } else {<br><strong>        data = data.replace(/__PAGE_TITLE__/g, pageMetadata.title || DEFAULT_TITLE);<br>        data = data.replace(/__PAGE_DESCRIPTION__/g, pageMetadata.description || DEFAULT_DESCRIPTION);<br>        data = data.replace(/__PAGE_IMAGE__/g, pageMetadata.image || DEFAULT_IMAGE);</strong><br>        resolve(data);<br>      }<br>    });<br>  });<br>}</pre><p>Now let’s test it by crawling the main page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*QeWuEPT1GAnLJl1Ne_gkBw.png" /></figure><p>That’s a progress.</p><p>Now, we can simply use the beauty and simplicity of Nest, to do the same thing for recipes.</p><p>We first need to import the recipes module into our client module, and inject recipe.service to our client.controller :</p><h4>client.module.ts</h4><pre>@Module({<br>  imports: [<br>    RecipeModule,<br>  ...<br>})</pre><h4><strong>client.controller.ts</strong></h4><pre>mport { Controller, <strong><em>Get</em></strong>, Param } from &#39;@nestjs/common&#39;;<br>import { ClientService } from &#39;./client.service&#39;;<br><strong>import { RecipeService } from &#39;../recipe/recipe.service&#39;;<br></strong><br>@Controller()<br>export class ClientController {<br>  constructor(<br>    private readonly clientService: ClientService,<br><strong>    private readonly recipeService: RecipeService,<br></strong>  ) {}<br><br><strong>  @Get(&#39;recipe/:name&#39;)<br>  public async getRecipe(@Param(&#39;name&#39;) name: string) {<br>    const recipe = await this.recipeService.getRecipeByName(name);<br>    const meta = {<br>      title: recipe.name,<br>      description: recipe.description,<br>      image: recipe.imageURL,<br>    };<br><br>    return this.clientService.getApp(meta);<br>  }<br></strong><br>  @Get(&#39;*&#39;)<br>  public async get() {<br>    return this.clientService.getApp();<br>  }<br>}</pre><p>(this is a mock code, feel free to make it more organised and “safe”).</p><p>Time to test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*sdcl25_LxoBjhl4W5TBbZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*lXmhcn4UkxuXjdAm.jpg" /></figure><h3>Generating a dynamic Sitemap</h3><p>A <a href="https://en.wikipedia.org/wiki/Site_map">sitemap</a> is an XML file that contains a list of pages of a website. Having a sitemap in your app can help search engines discover your pages more easily.</p><p>In our case, we would like to allow search engines discover our recipe pages (in addition to every static page).</p><p>You can create a separate module and controller for that, but in order to keep this article simple I will only create a service, and use the existing client.controller :</p><pre>nest g service sitemap</pre><p>Also, make sure to install <a href="https://www.npmjs.com/package/xmlbuilder">xmlbuilder</a> which will assist us to build the map:</p><pre>yarn add xmlbuilder</pre><p>Our sitemap will contain the <strong>page</strong> <strong>url</strong> and <strong>lastmod </strong>which indicates when this page was modified, and might help search engines to know if they should crawl it again. For more possible entries, checkout <a href="https://www.sitemaps.org/protocol.html">this webiste</a>.</p><p>Let’s add an appropriate handle inclient.controller.ts</p><pre>@Get(&#39;sitemap.xml&#39;)<br>@Header(&#39;Content-Type&#39;, &#39;application/xml&#39;)<br>public async getSiteMap() {<br>  return this.sitemapService.getSiteMap();<br>}</pre><p>And here’s a possible implementation forsitemap.service.ts:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import * as builder from &#39;xmlbuilder&#39;;<br>import { RecipeService } from &#39;../recipe/recipe.service&#39;;<br>import { XMLElement } from &#39;xmlbuilder&#39;;</pre><pre>@Injectable()<br>export class SitemapService {<br>  constructor(private readonly recipeService: RecipeService) {}</pre><pre>  public async getSitemap() {<br>    const recipes = await this.recipeService.getAllRecipes();<br>    return this.buildXML(recipes);<br>  }</pre><pre>  private async buildXML(recipes: IRecipe[]) {<br>    const xml = builder<br>      .create(&#39;urlset&#39;)<br>      .att(&#39;xmlns&#39;, &#39;http://www.sitemaps.org/schemas/sitemap/0.9&#39;);<br>    recipes.forEach(recipe =&gt; {<br>      this.buildEntry(xml, `recipe/${recipe.name}`, recipe.uploadDate);<br>    });</pre><pre>    return xml.end({ pretty: true });<br>  }</pre><pre>  private buildEntry(xml: XMLElement, uri: string, date: string) {<br>    const baseUrl = &#39;http://localhost:5000&#39;;<br>    xml<br>      .ele(&#39;url&#39;)<br>      .ele(&#39;loc&#39;, `${baseUrl}/${uri}`)<br>      .up()<br>      .ele(&#39;lastmod&#39;, date)<br>      .up();<br>  }<br>}</pre><p>And before we keep going any further, let’s test this route on the browser <a href="http://localhost:5000/sitemap.xml">http://localhost:5000/sitemap.xml</a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsBU7BtnyM3USEwaARizFA.png" /></figure><p>Remember the middleware we applied before? well, seems like it still works :)</p><p>Let’s modify it a bit to exclude the request for <strong>sitemap.xml:</strong></p><pre>export class AppModule {<br>  configure(consumer: MiddlewareConsumer) {<br>    consumer<br>      .apply(ClientMiddleware)<br><strong>      .exclude({ path: &#39;/sitemap.xml&#39;, method: RequestMethod.<em>GET </em>})<br></strong>      .forRoutes(ClientController);<br>  }<br>}</pre><p>Testing in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*nyMWNyjsLUxxja7LWO677Q.png" /></figure><p>And all you have left to do is to submit the sitemap to Google or any other service.</p><h3>Conclusion</h3><p>We learned how we can serve our react app, created with create-react-app using Nest, generate dynamic meta tags for every page, without actually migrating to a SSR designated frameworks like <strong>Next,</strong> which can be very costly for some apps. and even generating a dynamic sitemap to make those pages discoverable more easily.</p><p>I do strongly recommend you to think about all the options available when starting a new project. If SEO is a big deal for you, you should consider using frameworks like <strong>Next</strong> at the first place. In this article I presented some solutions for common SEO problems for those of you who already implemented their app with Nest and CRA.</p><p>You should also improve your SEO metrics with <strong>gzip</strong> compression, which will eventually load your app faster, and is pretty easy to achieve with @<strong>nest/serve-static </strong>and<strong> the express/compression </strong>modules.</p><p>Of course, most of the techniques implemented here with Nest can easily be implemented with a “plain” express server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7093a71d3fc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/serve-a-create-react-app-application-on-with-nest-js-for-better-seo-and-social-sharing-7093a71d3fc3">Serve a Create-React-App Application With Nest.Js for Better SEO and Social Sharing.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Same name but different: use your published version of an npm package, with the same name of the…]]></title>
            <link>https://medium.com/@morkadosh/same-name-but-different-use-your-published-version-of-an-npm-package-with-the-same-name-of-the-961a9a7cd44?source=rss-5f9a8c663703------2</link>
            <guid isPermaLink="false">https://medium.com/p/961a9a7cd44</guid>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Mor Kadosh]]></dc:creator>
            <pubDate>Sat, 30 Nov 2019 10:00:58 GMT</pubDate>
            <atom:updated>2019-11-30T10:03:51.669Z</atom:updated>
            <content:encoded><![CDATA[<h3>Same name but different: use your published version of an npm package, with the same name of the original one</h3><p>So you installed an exciting <strong>npm package</strong> in your project and used it happily. One day, you find out that this package is missing something that you can not continue without. You either look for a workaround, open a pull request to the package or god forbid, look for an alternative. But the clock is ticking, you have no time to wait.</p><p>You are about to give up on this relationship.</p><p><strong>Solution</strong>: <a href="https://docs.npmjs.com/creating-and-publishing-scoped-public-packages">publish your own version of the package</a>, and install it aliased with the same name of the original one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*vmDjgO-O5L8ihvu6.png" /></figure><p>This could be easily done with:</p><p>Using <strong>Yarn:</strong></p><pre>yarn add &lt;alias (original <strong>package </strong>name)&gt;@npm:&lt;<strong>new package </strong>name&gt;</pre><p>Using <strong>npm:</strong></p><pre>npm install --save &lt;alias (original <strong>package </strong>name)&gt;@npm:&lt;<strong>new package </strong>name&gt;</pre><p>An example:</p><pre>yarn add <strong>class</strong>-validator@npm:@kadoshms/<strong>class</strong>-validator</pre><p>This will install my own version of the <strong>class-validator</strong> package, aliased with the original name, which will allow me to use my own version of the package, while importing it regularly:</p><pre><strong>import </strong>{ IsString, MinLength } <strong>from </strong>&#39;class-validator&#39;;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961a9a7cd44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>