<?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 Mamadou CISSE on Medium]]></title>
        <description><![CDATA[Stories by Mamadou CISSE on Medium]]></description>
        <link>https://medium.com/@mciissee?source=rss-aba318037b1d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CH01oCIP7aNI_i55nHPP-Q.jpeg</url>
            <title>Stories by Mamadou CISSE on Medium</title>
            <link>https://medium.com/@mciissee?source=rss-aba318037b1d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:55:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mciissee/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[My docs are the source of truth my AI codes from]]></title>
            <link>https://medium.com/@mciissee/angular-finally-has-its-nextra-18a5438b6f7f?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/18a5438b6f7f</guid>
            <category><![CDATA[nextra]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 21:33:55 GMT</pubDate>
            <atom:updated>2026-07-13T22:03:22.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cd_3eWlKunpnkNHRC9qrfQ.png" /><figcaption>Nge doc page</figcaption></figure><p><em>One folder of Markdown, in the same repo as the code: the spec the AI designs and tests against, the docs site I ship, and the RAG behind my in-app chatbot.</em></p><p>We have been saying it for years: documentation should live next to the code. Docs-as-code, same repo, reviewed in the same pull request. Good advice, and still not enough, because the docs lag. The code changes in the PR, the docs get a “TODO: update later,” and three sprints on, the two describe different products.</p><p>The AI era finally gave me a reason to close that gap, and a strange new incentive to keep it closed: the AI is now one of the readers, and one of the writers.</p><p>Here is how I work now. It started as a convenience and became the backbone of how I build.</p><h3>The setup: product docs as plain Markdown, in the repo</h3><p>My product documentation is plain Markdown, one page per feature, each with a small frontmatter block. It lives in the same repository as the code it describes. Nothing exotic: text files, versioned with the thing they document.</p><p>That frontmatter is not decoration. It is structured metadata that later feeds retrieval. Hold that thought.</p><h3>The loop: the docs are the spec the AI builds from</h3><p>When I ask an AI assistant to build a feature, it does not start from my prompt alone. It starts from that product documentation as the source of truth. It designs against it, writes tests against it, audits the change against it. And at the end of a delivery, it updates the docs to match what actually shipped.</p><p>Read that last part again, because it is the whole trick. The documentation is an input to the work and an output of it. Code and docs cannot drift, because the same pass that changes one changes the other. The spec, the implementation, and the description of the implementation converge by construction.</p><p>It also makes the AI better. A model handed a clear, current spec designs more coherently and audits more honestly than one guessing from a diff. The docs are the context. Keeping them sharp is not overhead, it is how I get reliable code.</p><h3>The publish: same Markdown, automatic siteThe requirements were small</h3><p>When I ship to production, those Markdown files are pulled into a documentation site automatically: navigation, search, the works. The published site is generated from the exact files the code was built against, so the docs in production always match the product in production. There is no separate “update the docs site” task, because there is no separate docs site. Depending on the project, that site can carry technical documentation next to the product docs, and sit behind a login.</p><p>This step is the reason I rebuilt <a href="https://cisstech.github.io/nge/docs/nge-doc/getting-started">nge-doc</a>. My Angular docs library had existed for years, but this way of working needed something precise from it: point it at the Markdown folder, get a static site on deploy, and emit machine-readable versions of the same content, an llms.txt and an MCP server, so the docs the AI writes are docs an AI can also read back. I redesigned it around exactly that. You can see the result on <a href="https://cisstech.github.io/nge">its own docs</a>.</p><h3>The third job: the frontmatter becomes a chatbot</h3><p>Remember the frontmatter. Because every page carries clean metadata and clean Markdown, the same corpus is already shaped for retrieval. If I want a documentation chatbot inside the app, the RAG is sitting right there: labelled, well-chunked pages, no scraping, no separate pipeline. The docs that specced the feature and shipped the site also answer questions about it.</p><p>One folder. Three jobs. The spec the AI builds from, the site users read, and the knowledge base the assistant retrieves from. The same files, always in sync, because they are literally the same files.</p><h3>Why this holds together</h3><p>Take any one piece away and it is a nice habit. Together they are a system:</p><ul><li>Docs in the repo, reviewed and versioned with the code.</li><li>Docs as the AI’s source of truth, so design, tests, and audits share one definition of the product, and the docs get updated as part of shipping.</li><li>Docs auto-published, so what users see always matches production.</li><li>Docs structured for retrieval, so an in-app assistant answers from the truth, not from guesses.</li></ul><p>The result is the thing every team claims to want and few actually have: a single source of truth that is mechanically, always up to date. Plus code that is more reliable, because the AI that wrote it worked from a spec instead of vibes.</p><p>Markdown is what makes it possible. It is the one format a human reads, a diff tracks, a static site renders, and a language model ingests without ceremony. Choose a heavier format and one of those readers falls out.</p><h3>The practice, not the platform</h3><p>None of this needs a big platform: Markdown files, a frontmatter convention, an AI assistant pointed at them, and a build step that publishes the folder on deploy. <a href="https://cisstech.github.io/nge/docs/nge-doc/getting-started">nge-doc</a> is just the piece I happened to need for the Angular world. The tool is the small part. The way of working is the point.</p><p>Your documentation is about to have more readers than it ever had, and some of them write your code now. Treat it like the source of truth it already is.</p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18a5438b6f7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A guide to bidirectional integration between Angular and React]]></title>
            <link>https://medium.com/@mciissee/a-guide-to-bidirectional-integration-between-angular-and-react-9ac216f8083f?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ac216f8083f</guid>
            <category><![CDATA[micro-frontends]]></category>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 15:29:16 GMT</pubDate>
            <atom:updated>2025-07-12T01:02:00.582Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="What if Angular and React could finally work together?" src="https://cdn-images-1.medium.com/max/1024/1*HFgAFULaghgPyTPaqI3raw.png" /></figure><p>How to build a maintainable monorepo where Angular and React components coexist using custom elements and Nx</p><h4>The challenge of integrating frameworks</h4><p>In web development, teams often need to integrate different frameworks. You might have a large, stable application built with Angular and want to use React for new features, or need to merge products from different tech stacks without a complete rewrite. A common question is how to make Angular and React coexist in the same application without creating a complex web of dependencies.</p><p>This article presents a solution for bidirectional integration using <strong>custom elements (web components)</strong>, managed within an <strong>Nx monorepo</strong>. I’ll walk you through the architecture of a <a href="https://github.com/cisstech/angular-x-react">sample repository</a> that demonstrates how to use React components in Angular and Angular components in React.</p><h4>The architecture: Decoupled by design</h4><p>The core principle of this architecture is <strong>separation of concerns</strong>. Instead of creating direct dependencies between the Angular and React applications, they are treated as independent entities. The integration happens through a framework-agnostic contract: standard HTML custom elements.</p><p>Here’s a high-level overview:</p><ol><li><strong>Producer projects</strong>: We have “producer” projects , an Angular library and a React library. Their job is to compile their components into standalone JavaScript bundles that register themselves as custom elements.</li><li><strong>Framework-agnostic bundles</strong>: The build process for these libraries is configured to output framework-agnostic JavaScript and CSS. For example, a React component like `&lt;MyButton /&gt;` becomes a custom element `&lt;my-button-react&gt;` that can be used in any HTML file.</li><li><strong>Consumers load scripts</strong>: The main Angular and React applications (“consumers”) don’t import any source code from the other framework. Instead, they load the compiled JavaScript bundles via a simple `&lt;script&gt;` tag in their `index.html`.</li></ol><figure><img alt="Diagram of the solution" src="https://cdn-images-1.medium.com/max/1024/1*fLwEKQTOEzwkqFYbB6GTeA.png" /></figure><p>This approach keeps the build systems separate and avoids conflicting dependencies.</p><h4>How it works in practice</h4><p>Let’s dive into the two integration directions.</p><p><strong>Using Angular components in a React app</strong></p><p>This is useful when you have a library of robust, tested Angular components (like a charting library) that you want to use in a new React project.</p><ol><li><strong>Wrapping with @angular/elements</strong>: In the Angular “producer” app, the `createCustomElement` function from <a href="https://angular.dev/guide/elements">@angular/elements</a> is used to wrap Angular components. This function handles the translation from Angular’s change detection and inputs/outputs to the custom element’s attribute-based API.</li><li><strong>Building for React</strong>: The Angular build is configured in <strong>project.json</strong> to output its compiled JavaScript bundle directly into the <strong>public</strong> folder of the React application.</li><li><strong>Consuming in React</strong>: The React app includes the bundle with a <strong>&lt;script&gt;</strong> tag. Now, it can use the Angular component like a regular HTML element. A `global.d.ts` file can also be used to provide TypeScript with type definitions for the custom tags, enabling type-safety in JSX.</li></ol><pre>// In the React App (apps/react/src/app/app.tsx)<br>// No Angular imports needed!<br>// Just use the custom element tag.<br>&lt;ngx-charts<br> config={JSON.stringify(chartConfig)}<br> data={JSON.stringify(chartData)}<br>/&gt;</pre><p>Notice how complex data is passed: by serializing it to a JSON string. The Angular component is responsible for parsing it. This “props down, events up” pattern keeps communication simple.</p><p><strong>Using React components in an Angular app</strong></p><p>This is a great strategy for incremental migration. You can build new features in React and embed them into an existing Angular application.</p><ol><li><strong>Wrapping with a custom utility</strong>: In the React “producer” library, a lightweight wrapper leverages <strong>ReactDOM.createRoot()</strong> to render a React component inside a custom element’s Shadow DOM. This utility also handles mapping attributes to React props.</li><li><strong>Building for Angular</strong>: The library’s Vite configuration (<strong>vite.config.ts</strong>) is set up to output its bundle directly into the Angular app’s <strong>public </strong>directory.</li><li><strong>Lazy loading with MutationObserver</strong>: Instead of loading the React component bundle immediately, a <a href="https://developer.mozilla.org/fr/docs/Web/API/MutationObserver">MutationObserver</a> is used in the Angular app. This observer watches the DOM for the appearance of the React custom element tag (e.g., <strong>&lt;react-hello-world&gt;</strong>). When it sees the tag, it dynamically injects the corresponding script, which then “upgrades” the element into a fully interactive React component. This is an efficient way to implement micro-frontends.</li></ol><pre>&lt;!-- In an Angular Template (apps/angular/src/app/app.html) --&gt;<br>&lt;!-- This just works. Angular doesn&#39;t know or care it&#39;s a React component. --&gt;<br>&lt;react-hello-world<br> [attr.name]=&quot;angularSignal()&quot;<br> (onNameChange)=&quot;handleNameChange($event)&quot;<br>/&gt;</pre><h4>Key benefits of this approach</h4><p>This architecture provides a pattern for building scalable and maintainable applications.</p><ul><li><strong>Decoupling</strong>: Your Angular and React teams can work independently. As long as they respect the custom element contract (attributes for props, custom events for outputs), they don’t need to know about each other’s internal implementation.</li><li><strong>Incremental migration</strong>: You can safely migrate a legacy Angular app to React (or vice-versa) one component at a time. The <strong>MutationObserver</strong> pattern ensures you only pay the performance cost for the components that are actually rendered.</li><li><strong>Micro-frontend ready</strong>: This pattern is a good foundation for a micro-frontend architecture. Each library can be a self-contained feature, owned by a different team, and deployed independently.</li><li><strong>Powered by Nx</strong>: An Nx monorepo helps manage this setup. Nx understands the dependencies between your apps and libraries, allowing you to run commands like `nx build angular` and automatically trigger builds for its dependencies. It provides a unified toolkit for linting, testing, and building across both frameworks.</li></ul><h4>Check it out for yourself</h4><p>The best way to understand this architecture is to see it in action. A fully functional repository is available on GitHub to clone and run.</p><p><a href="https://github.com/cisstech/angular-x-react/">https://github.com/cisstech/angular-x-react/</a></p><p>The <strong>README.md</strong> contains detailed, step-by-step instructions for getting started, running the builds, and deploying the applications to GitHub Pages.</p><p>Live demo is available at <a href="https://cisstech.github.io/angular-x-react">https://cisstech.github.io/angular-x-react/.</a></p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac216f8083f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compute Your Dashboard in O(n) with the Iterator + Aggregators Pattern]]></title>
            <link>https://medium.com/@mciissee/compute-your-dashboard-in-o-n-with-the-iterator-aggregators-pattern-61d1f32634f9?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d1f32634f9</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 05:43:10 GMT</pubDate>
            <atom:updated>2025-06-25T05:44:14.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Dashboard view with a caption : You can compute this Dashboard in O(n)" src="https://cdn-images-1.medium.com/max/1024/1*mj06jV6AxEWCdJFg7hn5qg.png" /></figure><p>In many projects, each metric in a dashboard is computed with its own SQL query:</p><pre>SELECT COUNT(*)      FROM events WHERE type = &#39;A&#39;;<br>SELECT AVG(value)    FROM events WHERE type = &#39;B&#39;;<br>SELECT SUM(amount)   FROM events WHERE type = &#39;C&#39;;<br>-- and so on…</pre><ul><li><strong>M queries</strong> → network overhead, table locks, higher latency</li><li>Overall complexity <strong>O(M × N)</strong> (where N is the number of rows scanned per query)</li></ul><p>Our goal: read the dataset <strong>once</strong>, then compute <strong>all</strong> metrics in memory (or using cursor) in <strong>O(N)</strong>, regardless of how many business rules (BRs) we have.</p><h4>The “Iterator + Aggregators” pattern</h4><ul><li><strong>Single SQL read (filter &amp; projection)</strong><br>Fetch only the columns you need for the time window you care about:</li></ul><pre>SELECT<br> user_id, event_type, value, timestamp<br>FROM events<br>WHERE timestamp BETWEEN :start AND :end;</pre><ul><li><strong>In-memory iteration</strong><br>Loop over the result set (in memory or via a streaming cursor).</li><li><strong>Isolated aggregators</strong><br>Define a common interface, each business rule becomes its own Aggregator&lt;T, R&gt; implementation.</li></ul><pre>export interface Aggregator&lt;T, R&gt; {<br>  /** Unique key for the result */<br>  id: string;<br>  /** Process one record */<br>  accumulate(record: T): void;<br>  /** Return the final result */<br>  getResult(): R;<br>}</pre><ul><li><strong>Dynamic result mapping</strong><br>After the single pass, build your dashboard object by reading each aggregator’s id and getResult().</li></ul><figure><img alt="Flowchart of the Iterator + Aggregators pattern" src="https://cdn-images-1.medium.com/max/770/1*4Ak06XuuRemvMfot65VYMQ.png" /><figcaption>Flowchart of the Iterator + Aggregators pattern</figcaption></figure><h4>Concrete Example: E-commerce Orders Dashboard</h4><h4><strong>Business Rules (BR)</strong></h4><ul><li><strong>BR1 — </strong>Total number of orders</li><li><strong>BR2 — </strong>Total revenue</li><li><strong>BR3 — </strong>Average order value</li><li><strong>BR4 — </strong>Percentage of premium (fast-delivery) orders</li></ul><p><strong>Projected Schema</strong></p><pre>SELECT<br>  order_id,<br>  customer_id,<br>  total_amount,   -- order total<br>  is_premium,     -- boolean flag<br>  created_at<br>FROM orders<br>WHERE created_at BETWEEN :start AND :end;</pre><p><strong>Aggregator Interface</strong></p><pre>// aggregator.interface.ts<br>export interface Aggregator&lt;T, R&gt; {<br>  /** Unique key for the dashboard result */<br>  id: string;<br>  /** Incorporate one record */<br>  accumulate(record: T): void;<br>  /** Retrieve the aggregated result */<br>  getResult(): R;<br>}</pre><p><strong>Implementing Aggregators</strong></p><pre>// aggregators/order-count.aggregator.ts<br>import { Aggregator } from &#39;./aggregator.interface&#39;;<br>import { Order }      from &#39;./order.model&#39;;<br><br>export class OrderCountAggregator implements Aggregator&lt;Order, number&gt; {<br>  id = &#39;totalOrders&#39;;<br>  private count = 0;<br><br>  accumulate(order: Order): void {<br>    this.count++;<br>  }<br><br>  getResult(): number {<br>    return this.count;<br>  }<br>}<br><br>// aggregators/total-revenue.aggregator.ts<br>export class TotalRevenueAggregator implements Aggregator&lt;Order, number&gt; {<br>  id = &#39;totalRevenue&#39;;<br>  private sum = 0;<br><br>  accumulate(order: Order): void {<br>    this.sum += order.total_amount;<br>  }<br><br>  getResult(): number {<br>    return this.sum;<br>  }<br>}<br><br>// aggregators/average-order-value.aggregator.ts<br>export class AverageOrderValueAggregator implements Aggregator&lt;Order, number&gt; {<br>  id = &#39;averageOrderValue&#39;;<br>  private sum = 0;<br>  private count = 0;<br><br>  accumulate(order: Order): void {<br>    this.sum   += order.total_amount;<br>    this.count += 1;<br>  }<br><br>  getResult(): number {<br>    return this.count &gt; 0 ? this.sum / this.count : 0;<br>  }<br>}<br><br>// aggregators/premium-rate.aggregator.ts<br>export class PremiumOrderRateAggregator implements Aggregator&lt;Order, number&gt; {<br>  id = &#39;premiumOrderRate&#39;;<br>  private premiumCount = 0;<br>  private totalCount   = 0;<br><br>  accumulate(order: Order): void {<br>    this.totalCount++;<br>    if (order.is_premium) {<br>      this.premiumCount++;<br>    }<br>  }<br><br>  getResult(): number {<br>    return this.totalCount &gt; 0<br>      ? (this.premiumCount / this.totalCount) * 100<br>      : 0;<br>  }<br>}</pre><p><strong>Dashboard Service Orchestration</strong></p><pre>// dashboard.service.ts<br>import {<br>  OrderCountAggregator,<br>  TotalRevenueAggregator,<br>  AverageOrderValueAggregator,<br>  PremiumOrderRateAggregator,<br>} from &#39;./aggregators&#39;;<br>import { OrderRepository } from &#39;./order.repository&#39;;<br><br>export class DashboardService {<br>  constructor(private orderRepo: OrderRepository) {}<br><br>  async computeDashboard(start: Date, end: Date) {<br>    // 1. Single SQL read + projection<br>    const orders = await this.orderRepo.fetchOrders(start, end);<br><br>    // 2. Instantiate all aggregators<br>    const aggregators: Aggregator&lt;Order, any&gt;[] = [<br>      new OrderCountAggregator(),<br>      new TotalRevenueAggregator(),<br>      new AverageOrderValueAggregator(),<br>      new PremiumOrderRateAggregator(),<br>    ];<br><br>    // 3. Single pass over data (O(N × K), but K &lt; N in practice)<br>    for (const order of orders) {<br>      aggregators.forEach(agg =&gt; agg.accumulate(order));<br>    }<br><br>    // 4. Build result dynamically<br>    const dashboard: Record&lt;string, any&gt; = {};<br>    aggregators.forEach(agg =&gt; {<br>      dashboard[agg.id] = agg.getResult();<br>    });<br><br>    return dashboard;<br>  }<br>}</pre><h4>Key Benefits</h4><ul><li><strong>Linear performance (O(N))</strong>: one in-memory (or cursor) pass, even for 10, 50 or 100 metrics.</li><li><strong>Isolation &amp; atomicity</strong>: each aggregator holds its own state, no shared mutable variables.</li><li><strong>Extensibility</strong>: add a new BR by creating a new aggregator, no changes to SQL or orchestration code.</li><li><strong>Open/Closed Principle</strong>: the dashboard orchestration code is <strong>closed for modification. </strong>You never touch it when adding a new metrit. The code is <strong>open for extension</strong> via new aggregator classes.</li><li><strong>Testability</strong>: each aggregator can be unit-tested in isolation with dummy data.</li><li><strong>Maintainability</strong>: clear code structure, dynamic mapping based on id properties.</li></ul><p>By reading the dataset only once and delegating each business rule to a dedicated, self-contained component, you get dashboards that are both <strong>scalable</strong> and <strong>easy to evolve</strong>.</p><h3>If you liked this…</h3><p>I share practical frontend patterns, performance tips, and underused web APIs.<br>If that’s your kind of thing, feel free to follow or reach out.</p><p>And if you’ve used event delegation in a creative or large-scale way, I’d love to hear about it.</p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d1f32634f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You are attaching click handlers to every list item ? there’s a better way]]></title>
            <link>https://medium.com/@mciissee/you-are-attaching-click-handlers-to-every-list-item-theres-a-better-way-4cbc06e2fe75?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cbc06e2fe75</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 10:40:06 GMT</pubDate>
            <atom:updated>2025-06-23T10:51:19.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6gJZD0vhpLfR-93L08cmA.png" /></figure><h3>You are attaching click handlers to every list item ? there’s a better way</h3><p>In most frontend codebases, it’s common to see a pattern repeated over and over again:</p><blockquote><em>A list of items. Each item has its own </em><em>click handler.</em></blockquote><p>It works. But it comes with subtle performance costs, extra memory usage, and boilerplate code that could easily be avoided. In this article, I’ll walk through <strong>why this approach isn’t always ideal</strong>, and how you can <strong>simplify your code using event delegation, </strong>a technique that’s both powerful and surprisingly underused in modern frontend frameworks like React and Angular.</p><h3>The usual approach: a handler on every item</h3><p>Let’s take a typical example in React:</p><pre>items.map((item) =&gt; (<br>  &lt;div key={item.id} onClick={() =&gt; handleClick(item)}&gt;<br>    {item.label}<br>  &lt;/div&gt;<br>))</pre><p>Or in Angular</p><pre>@for (item of items; track item.id) {<br>  &lt;div (click)=&quot;handleClick(item)&quot;&gt;<br>    {{ item.label }}<br>  &lt;/div&gt;<br>}</pre><p>This is straightforward, easy to read, and totally fine for small lists. But if you start dealing with longer, dynamic lists or if the list changes frequently, you might be paying for that simplicity in the form of:</p><ul><li>Memory overhead (one handler per item)</li><li>Re-renders when items update</li><li>Repetitive code</li></ul><h3>A better mental model: from mics to cameras</h3><p>Imagine you’re giving a talk. You want to hear questions from the audience.</p><p>You could:</p><ul><li>Give each person in the audience their own microphone (a separate click handler)</li><li>Or set up <strong>one camera and mic at the front</strong> of the room to detect who’s speaking</li></ul><p>Most codebases choose the first option by default, when the second is often simpler and more scalable.</p><p>That second option is <strong>event delegation</strong>.</p><h3>What is event delegation?</h3><p>Event delegation means:</p><ul><li>Attaching <strong>a single event listener</strong> to a <strong>common parent</strong></li><li>Using the event object to figure out <strong>which child element was clicked</strong></li></ul><p>This works because of how events bubble in the DOM: a click on a child element will propagate up the DOM tree, where you can handle it once, centrally.</p><h3>How to implement event delegation</h3><p>Here’s how it looks in practice.</p><p>React:</p><pre>const MyList = ({ items }) =&gt; {<br>  const handleClick = (e) =&gt; {<br>    const item = e.target.closest(&#39;[data-id]&#39;)<br>    if (item) {<br>      const id = item.dataset.id<br>      console.log(&#39;Clicked item:&#39;, id)<br>    }<br>  }<br><br>  return (<br>    &lt;div onClick={handleClick}&gt;<br>      {items.map((item) =&gt; (<br>        &lt;div key={item.id} data-id={item.id} style={{ border: &#39;1px solid&#39; }}&gt;<br>          {item.label}<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Angular:</p><pre>&lt;div (click)=&quot;handleContainerClick($event)&quot;&gt;<br>  &lt;div *ngFor=&quot;let item of items&quot; [attr.data-id]=&quot;item.id&quot;&gt;<br>    {{ item.label }}<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br>---<br><br>handleContainerClick(event: MouseEvent) {<br>  const target = (event.target as HTMLElement).closest(&#39;[data-id]&#39;);<br>  if (target) {<br>    const id = target.getAttribute(&#39;data-id&#39;);<br>    console.log(&#39;Clicked item:&#39;, id);<br>  }<br>}<br></pre><p>No matter how long or dynamic your list is, you now have a single click listener doing the work.</p><h3>When is this actually useful?</h3><p>You’ll start to see the benefits of event delegation when:</p><ul><li>Your list contains <strong>hundreds or thousands of items</strong></li><li>Items are <strong>dynamically inserted or removed</strong></li><li>You want to handle clicks centrally (for analytics, UI state, etc.)</li><li>You’re building performance-sensitive UIs (e.g. virtual scroll, data grids)</li></ul><h3>Trade-offs</h3><p>Event delegation isn’t always the right tool. A few things to keep in mind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tARwYJdeQk-oshOohhsamg.png" /><figcaption>Event delegation vs Per-item handler comparison</figcaption></figure><h3>A quick disclaimer before you refactor everything</h3><p>This article isn’t here to tell you that your current approach is wrong, or that you <em>must</em> replace all your onClicks with event delegation.</p><p>In most apps, having a handler per item works just fine.</p><p>But if you ever find yourself rendering a <strong>large list of interactive elements</strong>, and you start noticing performance issues or feel like your JSX/templates are getting noisy, now you know there’s a native, scalable alternative you can try.</p><p>It’s just one more tool in your frontend toolbox.</p><h3>Game dev brain? Here’s a quick one</h3><p>If you’ve done any game development, this might feel familiar:</p><p><em>You’re building a first-person game.<br>You want to detect what object the player is aiming at.<br>Do you:</em></p><ul><li>A: Attach a trigger or collision detector to every object?</li><li>B: Send a signal from the player’s camera and detect what it hits?</li></ul><p>Think about it for a second.<br>Now ask yourself: which one sounds more scalable?</p><p>That’s basically what <strong>event delegation</strong> is in the browser world.</p><h3>Conclusion</h3><p>Most of the time, using onClick or (click) per item won’t break anything. But when your UI grows and starts to demand more performance or flexibility, this small pattern shift can save you time, memory, and cognitive load.</p><p>Instead of scattering handlers across every component, you can let the DOM do what it’s built to do: <strong>bubble events upward and delegate intelligently</strong>.</p><h3>If you liked this…</h3><p>I share practical frontend patterns, performance tips, and underused web APIs.<br>If that’s your kind of thing, feel free to follow or reach out.</p><p>And if you’ve used event delegation in a creative or large-scale way, I’d love to hear about it.</p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cbc06e2fe75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Visibility with Intersection Observer]]></title>
            <link>https://medium.com/@mciissee/mastering-visibility-with-intersection-observer-9d4989ffa27c?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d4989ffa27c</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 16:09:03 GMT</pubDate>
            <atom:updated>2025-06-23T22:57:07.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Web development is a constant battle against the scroll. We want to load content smoothly, trigger animations at the right moment, and generally make the user experience feel polished. One powerful tool in this fight is the Intersection Observer API, and today, we’ll explore how to wrap it in a reusable React component. This will empower you to build features like infinite scrolling, lazy loading images, and those slick “fade-in” animations you see on fancy websites.</p><h4>The problem: Scroll events are a MESS</h4><p>Before diving into the solution, let’s acknowledge the classic (and often clunky) approach: scroll event listeners. While seemingly straightforward, directly listening to the scroll event can quickly lead to performance bottlenecks. Every scroll event fires constantly, triggering your callback function repeatedly. This can bog down the browser, especially on mobile devices. Imagine a frantic dog chasing a squirrel, that’s your scroll event handler trying to keep up with the user’s scrolling. Not ideal.</p><h4>A solution: The Intersection Observer</h4><p>The Intersection Observer API provides a much more efficient way to track when an element intersects with the viewport (or another specified element). It’s like having a chill, observant cat watching the element. It only notifies you when the element’s visibility changes significantly, not on every tiny scroll movement.</p><h4>Browser Compatibility:</h4><p>The Intersection Observer API enjoys excellent browser support. It’s widely available in modern browsers, including Chrome, Firefox, Safari, and Edge. For older browsers, you might need a polyfill. Check out <a href="https://caniuse.com//#feat=intersectionobserver](https://www.google.com/url?sa=E&amp;source=gmail&amp;q=https://caniuse.com/#feat=intersectionobserver)">https://caniuse.com/#feat=intersectionobserver</a> for the most up-to-date compatibility information.</p><h4>Building a reusable React component</h4><p>Let’s break down the provided <strong>ViewportIntersection</strong> component:</p><pre>import React, { useEffect, useRef } from &#39;react&#39;<br><br>type Props = {<br>  scrollContainer?: Element<br>  threshold?: number | number[]<br>  rootMargin?: string<br>  debug?: boolean<br>  onIntersect: () =&gt; void<br>}<br><br>export const ViewportIntersection: React.FC&lt;Props&gt; = ({<br>  scrollContainer,<br>  threshold,<br>  rootMargin,<br>  debug,<br>  onIntersect,<br>}) =&gt; {<br>  const elementRef = useRef&lt;HTMLDivElement&gt;(null)<br><br>  useEffect(() =&gt; {<br>    const intersectionObserver = new IntersectionObserver(<br>      (entries) =&gt; {<br>        const [entry] = entries<br>        if (entry.isIntersecting) {<br>          onIntersect()<br>        }<br><br>        if (!elementRef!.current) {<br>          return<br>        }<br><br>        if (debug) {<br>          elementRef!.current!.style.border = &#39;2px solid red&#39;<br>        } else {<br>          elementRef!.current!.style.border = &#39;none&#39;<br>        }<br>      },<br>      {<br>        root: scrollContainer ? scrollContainer : null,<br>        rootMargin: rootMargin,<br>        threshold: threshold,<br>      },<br>    )<br><br>    if (elementRef.current) {<br>      intersectionObserver.observe(elementRef.current)<br>    }<br><br>    return () =&gt; {<br>      if (intersectionObserver) {<br>        intersectionObserver.disconnect()<br>      }<br>    }<br>  }, [elementRef.current, scrollContainer, threshold, rootMargin, debug, onIntersect])<br><br>  return &lt;div style={{ height: &#39;64px&#39; }} ref={elementRef} /&gt;<br>}</pre><h4>Explanation:</h4><p>1. <strong>elementRef</strong>: A ref is used to get a direct reference to the DOM element we want to observe. Think of it as giving the cat a specific object to watch.</p><p>2. <strong>useEffect</strong>: This hook is where the magic happens. It sets up the <strong>IntersectionObserver</strong> and observes the element. The dependency array ensures the effect runs only when necessary (e.g., when the element changes, or the <strong>threshold</strong> or <strong>rootMargin</strong> props change).</p><p>3. <strong>IntersectionObserver</strong>: This is the core of the solution. It takes two arguments:<br> — A callback function: This function is called whenever the observed element’s intersection status changes. The <strong>entries</strong> array contains information about the intersection.<br> — An options object: This object lets you customize the observer’s behavior.</p><p>4. <strong>Callback function</strong>: Inside the callback, we check <strong>entry.isIntersecting</strong>. If it’s true, the element is visible, and we call the <strong>onIntersect</strong> prop, this is where you’d put your logic (e.g., loading more data, triggering an animation). The debug code adds a red border to the observed element for visualization.</p><p>5. <strong>Options object</strong>:<br> — root: Specifies the element used as the “viewport” for intersection. If not provided, the browser viewport is used. This is useful for observing elements within a scrollable div.<br> — rootMargin: Adds a margin around the root element. This lets you trigger the callback before the element actually becomes visible. Think of it as giving the cat a heads-up.<br> — threshold: A number or array of numbers between 0 and 1. It represents the percentage of the target element that must be visible before the callback is triggered. A threshold of 1 means the entire element must be visible.</p><p>6. observer.observe(): Starts observing the element.</p><p>7. return () =&gt; observer.disconnect(): This cleanup function is crucial. It disconnects the observer when the component unmounts, preventing memory leaks.</p><p>8. return &lt;div ref={elementRef} /&gt;: This renders a simple div and attaches the elementRef to it. This div is the target element being observed. You can customize the styling as needed.</p><h4>Usage example:</h4><pre>import { useState } from &#39;react&#39;<br>import { ViewportIntersection } from &#39;./ViewportIntersection&#39;<br><br>const MyComponent = () =&gt; {<br>  const [isLoadingMore, setIsLoadingMore] = useState(false)<br>  const handleIntersect = () =&gt; {<br>    setIsLoadingMore(true)<br>    console.log(&#39;Element is intersecting!&#39;);<br>    // Load more data, trigger animation, etc.<br>    setIsLoadingMore(false)<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      {/* ... other content */}<br>      {!isLoadingMore &amp;&amp; &lt;ViewportIntersection onIntersect={handleIntersect} /&gt;}<br>      {/* ... more content */}<br>    &lt;/div&gt;<br>  )<br>}</pre><h4>Implementation in Angular:</h4><p>While the React example uses hooks, Angular relies on Directives and Services. Here’s a conceptual outline of how you might implement similar functionality in Angular:</p><p>1. <strong>Create a Directive:</strong> A directive can be placed on the element you want to observe.</p><p>2. <strong>Inject ElementRef and NgZone</strong>: ElementRef` provides access to the DOM element, and NgZone helps manage change detection within Angular’s zone.</p><p>3. <strong>Use IntersectionObserver</strong>: Inside the directive’s ngAfterViewInit, create an instance of IntersectionObserver.</p><p>4. <strong>Implement the Callback</strong>: The callback function will be similar to the React example, but you’ll likely use Angular’s mechanisms (like @Output emitters) to communicate changes to the parent component.</p><p>5. <strong>ngOnDestroy</strong>: Remember to disconnect the observer in ngOnDestroy to prevent memory leaks.</p><pre>import {<br>  AfterViewInit,<br>  Directive,<br>  ElementRef,<br>  EventEmitter,<br>  Input,<br>  OnDestroy,<br>  Output,<br>  booleanAttribute,<br>} from &#39;@angular/core&#39;<br><br>@Directive({<br>  selector: &#39;[viewportIntersection]&#39;,<br>  standalone: true,<br>})<br>export class ViewportIntersectionDirective implements AfterViewInit, OnDestroy {<br>  /**<br>   * An optional reference to a container element with its own scrollable area. If not provided, the viewport is used as the default container.<br>   */<br>  @Input() scrollContainer?: HTMLElement | null<br><br>  /**<br>   * A single number or an array of numbers indicating at what percentage of the target&#39;s<br>   * visibility the observer&#39;s callback should be executed.<br>   * For example, a threshold of 1.0 means the callback will trigger when 100% of the target is visible within the observed area.<br>   *<br>   * Please refers to the official documentation of Intersection API for more informations.<br>   */<br>  @Input() threshold?: number | number[]<br><br>  /**<br>   * A margin around the root element.<br>   * This margin works like the CSS margin property, setting how much of the root should be seen before the intersection is observed.<br>   * It&#39;s specified in pixels or percentages.<br>   *<br>   * Please refers to the official documentation of Intersection API for more informations.<br>   */<br>  @Input() rootMargin?: string<br>  @Input({ transform: booleanAttribute }) debug = false<br><br>  /**<br>   * This event is emitted whenever the observed element intersects with the viewport or the specified scrollContainer<br>   * according to the given threshold and rootMargin.<br>   */<br>  @Output() intersected: EventEmitter&lt;void&gt; = new EventEmitter()<br><br>  private intersectionObserver?: IntersectionObserver<br><br>  constructor(<br>     private readonly zone: NgZone,<br>     private readonly element: ElementRef&lt;HTMLElement&gt;<br>  ) {}<br><br>  ngAfterViewInit(): void {<br>    this.intersectionObserver = new IntersectionObserver(<br>      (entries) =&gt; {<br>        const entry = entries[0]<br>        if (entry.isIntersecting) {<br><br>          this.zone.run(() =&gt; this.intersect.emit()); // Run in Angular zone<br><br>          if (this.debug) {<br>            this.element.nativeElement.style.border = &#39;2px solid red&#39;<br>          }<br>        } else {<br>          if (this.debug) {<br>            this.element.nativeElement.style.border = &#39;2px solid transparent&#39;<br>          }<br>        }<br>      },<br>      {<br>        root: this.scrollContainer ? this.scrollContainer : null,<br>        rootMargin: this.rootMargin,<br>        threshold: this.threshold,<br>      }<br>    )<br><br>    this.intersectionObserver.observe(this.element.nativeElement)<br>  }<br><br>  ngOnDestroy(): void {<br>    if (this.intersectionObserver) {<br>      this.intersectionObserver.disconnect()<br>    }<br>  }<br>}</pre><p><strong>Usage in Angular template</strong>:</p><pre>/* ... other content */<br>&lt;div appViewportIntersection (intersect)=&quot;onIntersect()&quot;&gt;<br>/* ... other content */</pre><h4>Benefits:</h4><p><strong>Performance</strong>: Much more efficient than scroll event listeners.<br><strong>Declarative</strong>: Uses a declarative approach, making your code cleaner and easier to reason about.<br><strong>Flexible</strong>: Highly configurable with root, rootMargin, and threshold options.</p><h4>Conclusion:</h4><p>The Intersection Observer API is a tool for building performant and engaging web experiences. By wrapping it in a reusable component/directive, you can easily add features like infinite scrolling, lazy loading, and viewport-based animations to your applications without relying on any external lib.</p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d4989ffa27c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharging NestJS REST APIs: Get GraphQL’s data fetching power without leaving REST]]></title>
            <link>https://medium.com/@mciissee/supercharging-nestjs-rest-apis-get-graphqls-data-fetching-power-without-leaving-rest-08c06be4c2ba?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/08c06be4c2ba</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 09:10:42 GMT</pubDate>
            <atom:updated>2025-04-27T19:37:16.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Aqn7ee_1rNslqlTNUU5vA.png" /></figure><h4><strong>Fetching related data: a common REST API challenge</strong></h4><p>If you’ve built REST APIs, you’ve encountered this: your API logically exposes resources like /users/{id} or /posts/{id} (representing your backend <em>Models</em>), but your frontend needs a specific combination of data to render a particular page or component (its <strong>ViewModel</strong>). Getting the user’s profile, their recent orders, and item details often turns into a waterfall of client-side requests:</p><ol><li>GET /users/{id} (Get base user Model)</li><li>GET /users/{id}/profile (Get profile data)</li><li>GET /users/{id}/orders (Get order list)</li><li>GET /orders/{orderId1}/items (Get items for order 1)</li><li>GET /orders/{orderId2}/items (Get items for order 2)<br>…and so on.</li></ol><p>This client-side <strong>ViewModel assembly</strong> approach causes several issues:</p><ul><li><strong>Increased latency:</strong> Multiple network round trips slow down page rendering.</li><li><strong>Client complexity:</strong> The frontend bears the burden of orchestrating requests and stitching data together.</li><li><strong>Server inefficiency (N+1 Query Problem):</strong> Fetching related items naively on the server (e.g., fetching details for each order individually when asked) can hammer your database.</li><li><strong>Over/under-fetching:</strong> The API either returns too much data for simple views or not enough for complex ones, forcing extra calls.</li></ul><p>This fundamental friction between backend <em>Models</em> and frontend <em>ViewModels</em> is a major reason developers explore alternatives like GraphQL.</p><h4><strong>Why GraphQL is appealing for data fetching</strong></h4><p>GraphQL’s appeal lies significantly in its ability to let clients define the <em>exact shape of the ViewModel</em> they need in a single query. Clients can request a user, their orders, and nested item details, and the server responds with precisely that structure. This eliminates multiple requests, prevents over/under-fetching, and efficiently delivers the data needed for the view.</p><h4><strong>But what if you prefer REST?</strong></h4><p>GraphQL is powerful, but migrating isn’t always feasible or desirable. You might value REST’s architecture, ecosystem, or need to evolve an existing API. Can REST APIs be adapted to serve tailored <strong>ViewModels</strong> as efficiently as GraphQL?</p><h4><strong>Introducing </strong><strong>nestjs-expand: resource expansion for REST</strong></h4><p>The <strong>NestJS Expand Library (</strong><a href="https://www.npmjs.com/package/@cisstech/nestjs-expand"><strong>@cisstech/nestjs-expand</strong></a><strong>)</strong> offers a pragmatic solution. It implements a dynamic resource expansion pattern, enabling clients to request the specific data composition they need for their <strong>ViewModel</strong> within a single REST request.</p><p>Instead of the client making numerous calls to assemble the view, it simply specifies the required data layers using query parameters:</p><pre>// Request the ViewModel for a user profile page<br>GET /users/{id}?expands=profile,orders<br><br>// Request the ViewModel for a course list with instructor names<br>GET /courses?expands=instructor&amp;selects=*,instructor.name</pre><p>This tells your NestJS backend to fetch and include the profile and orders data directly within the /users/{id} response, effectively constructing the requested <strong>ViewModel</strong> on the server.</p><h4><strong>More than simple expansion: fine-grained control</strong></h4><p>nestjs-expand also offers more detailed control, echoing some of GraphQL&#39;s field selection features:</p><ul><li><strong>Deep expansion:</strong> Fetch relationships that are nested. For instance, get instructor details when requesting a course: GET /courses?expands=instructor</li><li><strong>Deep field selection:</strong> Be specific about which fields to include or exclude, not just for the main resource but for the expanded ones too. This helps keep responses lean.</li></ul><pre>// Request a ViewModel for courses including instructor and parent,<br>// BUT: exclude course &#39;description&#39;, instructor &#39;id&#39; &amp; &#39;bio&#39;,<br>// and only include parent &#39;title&#39;<br>&quot;GET /courses?expands=instructor,parent&amp;selects=*,-description,instructor.*,-instructor.id,-instructor.bio,parent.title&quot;<br><br>// This translates to the following ViewModel structure definition:<br>{<br>  &#39;*&#39;: true,          // include all root course fields<br>  description: false, // BUT exclude description<br>  instructor: {<br>    &#39;*&#39;: true,        // include all instructor fields<br>    id: false,        // BUT exclude id<br>    bio: false        // AND exclude bio<br>  },<br>  parent: {<br>    title: true       // ONLY include parent&#39;s title<br>  }<br>}</pre><h4><strong>How it works: decorators and expanders</strong></h4><p>Getting nestjs-expand working in your project is straightforward, leveraging NestJS&#39;s decorators and module system:</p><ol><li><strong>Mark your endpoints:</strong> Use the @Expandable(YourDTO) decorator on controller methods where you want to allow expansion. This tells the library that the response DTO can have additional fields included.</li></ol><pre>// course.controller.ts<br>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { CourseService } from &#39;./course.service&#39;;<br>import { CourseDTO } from &#39;./course.dto&#39;;<br>import { Expandable } from &#39;@cisstech/nestjs-expand&#39;; // Import<br><br>@Controller(&#39;courses&#39;)<br>export class CourseController {<br>  constructor(private readonly courseService: CourseService) {}<br><br>  @Get()<br>  @Expandable(CourseDTO) // Base DTO can be expanded into various ViewModels<br>  async getAllCourses(): Promise&lt;CourseDTO[]&gt; {<br>    // ... implementation ...<br>  }<br>}</pre><p><strong>2. Define the expansion logic:</strong> Create @Expander(YourDTO) services. Methods within these services (named after the expandable fields like instructor) contain the logic to fetch related data and contribute to the final <strong>ViewModel</strong>.</p><pre>// course.expander.ts<br>import { Injectable, NotFoundException } from &#39;@nestjs/common&#39;;<br>import { ExpandContext, Expander } from &#39;@cisstech/nestjs-expand&#39;; // Import<br>import { CourseDTO } from &#39;./course.dto&#39;;<br>import { InstructorDTO } from &#39;./instructor.dto&#39;;<br>import { InstructorService } from &#39;./instructor.service&#39;;<br><br>@Injectable()<br>@Expander(CourseDTO) // Define how CourseDTO can be expanded<br>export class CourseExpander {<br>  constructor(private readonly instructorService: InstructorService) {}<br><br>  // &#39;instructor&#39; method name matches the expandable field<br>  async instructor(context: ExpandContext&lt;Request, CourseDTO&gt;): Promise&lt;InstructorDTO&gt; {<br>    const course = context.parent; // Access the CourseDTO object<br>    // For better performance, you can use dataloader technique instead of direct db call<br>    const instructor = await this.instructorService.getInstructorById(course.instructorId);<br>    if (!instructor) {<br>      throw new NotFoundException(`Instructor not found: ${course.instructorId}`);<br>    }<br>    return instructor; // Return the related InstructorDTO<br>  }<br><br>  // Add other expandable fields here (e.g., async parent(...) { ... })<br>}</pre><p>With this setup, the library automatically handles the expands and selects query parameters, calling your expander methods as needed.</p><h4><strong>Crucial performance note: DataLoader for list endpoints</strong></h4><p>When expanding fields on list endpoints (like fetching the instructor for <em>every</em> course in GET /courses?expands=instructor), calling the database individually for each item inside the expander method creates the <strong>N+1 query problem</strong>. To solve this efficiently, use the <strong>DataLoader pattern</strong> within your expander method. DataLoader batches multiple individual requests (like fetching instructors by ID) into a single, optimized query, dramatically improving performance for list expansions.</p><h4><strong>Example: Delivering course ViewModels</strong></h4><p>Let’s look at fetching courses again.</p><ul><li><strong>Without expansion (basic model):</strong> GET /courses returns just base course data. The client needs more calls to build a useful view.</li></ul><pre>[<br>  { &quot;id&quot;: 1, &quot;title&quot;: &quot;Intro to Programming&quot;, &quot;instructorId&quot;: 101 },<br>  { &quot;id&quot;: 2, &quot;title&quot;: &quot;Web Dev Fundamentals&quot;, &quot;instructorId&quot;: 102 }<br>]<br>// Client now needs: GET /instructors/101, GET /instructors/102 ...</pre><ul><li><strong>With expansion (tailored ViewModel):</strong> GET /courses?expands=instructor delivers the complete <strong>ViewModel</strong> needed for a course list <em>with</em> instructor details in one shot. The backend uses DataLoader internally to fetch instructors efficiently.</li></ul><pre>[<br>  {<br>    &quot;id&quot;: 1,<br>    &quot;title&quot;: &quot;Intro to Programming&quot;,<br>    &quot;instructorId&quot;: 101,<br>    &quot;instructor&quot;: { &quot;id&quot;: 101, &quot;name&quot;: &quot;John Doe&quot;, &quot;bio&quot;: &quot;...&quot; }<br>  },<br>  {<br>    &quot;id&quot;: 2,<br>    &quot;title&quot;: &quot;Web Dev Fundamentals&quot;,<br>    &quot;instructorId&quot;: 102,<br>    &quot;instructor&quot;: { &quot;id&quot;: 102, &quot;name&quot;: &quot;Jane Smith&quot;, &quot;bio&quot;: &quot;...&quot; }<br>  }<br>]<br>// Single request, much quicker!</pre><h4><strong>Benefits: Shifting to Page-Driven REST APIs</strong></h4><ul><li><strong>Deliver complete ViewModels:</strong> Eliminate client-side fetching waterfalls and assembly logic.</li><li><strong>Improve performance:</strong> Fewer network requests and optimized backend fetching (via DataLoader for N+1) mean faster responses.</li><li><strong>Solve the N+1 Query Problem:</strong> Efficiently handle expansions on list endpoints using techniques like DataLoader within expanders.</li><li><strong>GraphQL-like flexibility in REST:</strong> Clients define their required <strong>ViewModel</strong> structure through expandsand selects.</li><li><strong>Enhanced developer experience:</strong> Backend defines reusable expansion logic. Frontend requests the exact <strong>ViewModel</strong> needed.</li><li><strong>Clean &amp; Consistent API Design:</strong> The API evolves from serving static <em>Models</em> to dynamically constructing <em>ViewModels</em>.</li><li><strong>Easy Integration:</strong> Plugs into NestJS naturally.</li></ul><h4><strong>Conclusion</strong></h4><p>You don’t need to abandon REST to address the challenge of efficiently delivering data tailored for frontend views. The NestJS Expand Library empowers you to build <strong>Page-Driven APIs</strong> within the REST paradigm. By allowing clients to request specific <strong>ViewModels</strong> through dynamic expansion and selection, and by enabling efficient backend fetching patterns like DataLoader, you can create faster, more flexible, and developer-friendly APIs that effectively bridge the gap between backend Models and frontend needs.</p><p>Ready to supercharge your NestJS APIs? Find the library here: <a href="https://github.com/cisstech/nestkit/tree/main/libs/expand">https://github.com/cisstech/nestkit</a></p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08c06be4c2ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Real-time Applications with PostgreSQL and NestJS Using nestjs-pg-pubsub]]></title>
            <link>https://medium.com/@mciissee/building-real-time-applications-with-postgresql-and-nestjs-using-nestjs-pg-pubsub-db724187df3f?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/db724187df3f</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[nest]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 23:50:15 GMT</pubDate>
            <atom:updated>2025-03-23T21:26:31.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*HcsnRvBBY8hivsNvoMBjhQ.png" /><figcaption>Sequence diagram of the lib architecture</figcaption></figure><p>Real-time data synchronization is becoming increasingly important in modern web applications. Users expect instant updates when data changes, whether it’s notifications, dashboard updates, or collaborative features. While WebSockets provide the client-side solution, efficiently detecting and propagating database changes remains a challenge for many developers.</p><p>Today I’m excited to introduce <a href="https://github.com/cisstech/nestkit/tree/main/libs/pg-pubsub">nestjs-pg-pubsub</a>, an open-source library that bridges the gap between PostgreSQL’s powerful notification system and NestJS applications.</p><h4>The Problem: Database Change Detection</h4><p>Traditionally, applications detect database changes through:</p><p>1. <strong>Polling</strong>: Regularly querying the database, which is inefficient and creates unnecessary load<br>2. <strong>Application-level events</strong>: Emitting events after every write operation, which often leads to scattered and duplicated code<br>3. <strong>Change data capture (CDC)</strong>: Complex infrastructure that might be overkill for many applications</p><p>Each approach has significant drawbacks in terms of performance, code maintainability, or complexity.</p><h4>Enter nestjs-pg-pubsub</h4><p>This library leverages PostgreSQL’s native NOTIFY/LISTEN mechanism to provide real-time notifications directly from the database. It automatically creates and manages database triggers that notify your application when data changes, with minimal configuration.</p><p>Key Features</p><ul><li><strong>Decorator-based configuration</strong>: Simply add a decorator to your listener class</li><li><strong>TypeORM integration</strong>: Works seamlessly with your existing TypeORM entities</li><li><strong>Efficient batching</strong>: Groups notifications for optimal processing</li><li><strong>Smart entity mapping</strong>: Maps database columns to entity properties automatically</li><li><strong>Configurable locking</strong>: Prevents duplicate processing of the same event when multiple instances of your application are running.</li><li><strong>Customizable filtering</strong>: Subscribe only to the events and fields you need</li></ul><h4>How It Works</h4><p>The library creates PostgreSQL triggers that send notifications when table data changes. Your NestJS application listens for these notifications and processes them according to your defined listeners. This approach is both efficient and reliable, as it leverages the database’s native capabilities.</p><h4>Getting Started</h4><p>First, install the package:</p><pre>npm install @cisstech/nestjs-pg-pubsub</pre><p>Register the module in your application:</p><pre>@Module({<br>  imports: [<br>    TypeOrmModule.forRoot({...}),<br>    PgPubSubModule.forRoot({<br>      databaseUrl: &#39;postgresql://user:password@localhost:5432/dbname&#39;,<br>      // Optional queue configuration<br>      queue: {<br>        maxRetries: 5, // Default: 5<br>        messageTTL: 24 * 60 * 60 * 1000, // Default: 24 hours<br>        cleanupInterval: 60 * 60 * 1000, // Default: 1 hour<br>      },<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><p>Create a listener for your entity:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import {<br>  RegisterPgTableChangeListener,<br>  PgTableChangeListener,<br>  PgTableChanges,<br>  PgTableChangeErrorHandler,<br>} from &#39;@cisstech/nestjs-pg-pubsub&#39;;<br>import { User } from &#39;./entities/user.entity&#39;;<br><br>@Injectable()<br>@RegisterPgTableChangeListener(User)<br>export class UserChangeListener implements PgTableChangeListener&lt;User&gt; {<br>  async process(changes: PgTableChanges&lt;User&gt;, onError?: PgTableChangeErrorHandler): Promise&lt;void&gt; {<br>    try {<br>      // Process inserts<br>      changes.INSERT.forEach((insert) =&gt; {<br>        console.log(`New user created: ${insert.data.name}`);<br>      });<br><br>      // Process updates<br>      changes.UPDATE.forEach((update) =&gt; {<br>        console.log(`User updated: ${update.data.new.name}`);<br>        console.log(`Updated fields: ${update.data.updatedFields.join(&#39;, &#39;)}`);<br>      });<br><br>      // Process deletes<br>      changes.DELETE.forEach((deletion) =&gt; {<br>        console.log(`User deleted: ${deletion.data.id}`);<br>      });<br>    } catch (error) {<br>      // Mark messages as failed for retry<br>      if (onError) {<br>        onError(changes.all.map(change =&gt; change.id));<br>      }<br>      throw error;<br>    }<br>  }<br>}</pre><h4>Register your listener in your module</h4><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { User } from &#39;./entities/user.entity&#39;;<br>import { UserChangeListener } from &#39;./listeners/user-change.listener&#39;;<br><br>@Module({<br>  imports: [TypeOrmModule.forFeature([User])],<br>  providers: [UserChangeListener],<br>})<br>export class UserModule {}</pre><p>That’s it! Your application will now receive real-time notifications when user data changes.</p><h4>Advanced Features</h4><p><strong>Selective Payload Fields</strong>: You can specify which fields to include in the change payload</p><pre>@RegisterPgTableChangeListener(User, {<br>  payloadFields: [&#39;id&#39;, &#39;email&#39;, &#39;name&#39;] // Only include these fields<br>})</pre><p><strong>Specific Events: </strong>Listen only for specific types of changes:</p><pre>@RegisterPgTableChangeListener(User, {<br>  events: [&#39;INSERT&#39;, &#39;UPDATE&#39;] // Ignore DELETE events<br>})</pre><p><strong>Error Handling &amp; Retries</strong>: The library provides sophisticated error handling:</p><pre>async process(changes: PgTableChanges&lt;User&gt;, onError?: PgTableChangeErrorHandler): Promise&lt;void&gt; {<br>  // Process each change individually<br>  for (const change of changes.all) {<br>    try {<br>      await this.processChange(change);<br>    } catch (error) {<br>      // Mark only this specific message as failed for retry<br>      onError?.([change.id]);<br>      // Continue processing other changes<br>    }<br>  }<br>}</pre><p><strong>Pause and Resume</strong>: Control the listener at runtime</p><pre>// Pause listener temporarily<br>await pgPubSubService.pause();<br><br>// Resume listener<br>await pgPubSubService.resume();<br><br>// Suspend for a specific operation<br>await pgPubSubService.suspendAndRun(async () =&gt; {<br>  // Do something without triggering listeners<br>});</pre><h4>Real-world Example: Notification System</h4><p>I’ve included a complete sample application in the repository that demonstrates a real-time notification system. Users receive immediate alerts when new notifications are created, marked as read, or deleted.</p><p>The sample includes:</p><ul><li>User and notification entities</li><li>REST API endpoints for managing notifications</li><li>WebSocket gateway for pushing updates to clients</li><li>Redis-based distributed locking for high-availability setups</li></ul><h4>Performance and Scalability</h4><ul><li><strong>Multiple Instances:</strong> The library uses PostgreSQL advisory locks to ensure that in distributed environments with multiple instances, each message is processed exactly once. The queue-based architecture allows multiple service instances to share the workload.</li><li><strong>Batch Processing: </strong>Changes are processed in batches for efficiency, while still maintaining the correct order of operations.</li><li><strong>Automatic Cleanup : </strong>Old processed messages are automatically cleaned up to keep the queue table size manageable.</li></ul><h4>Key benefits:</h4><ul><li><strong>Zero infrastructure overhead</strong>: Uses your existing PostgreSQL database</li><li><strong>Reliability</strong>: Queue-based architecture ensures no events are lost</li><li><strong>Performance</strong>: Efficient batch processing and notification system</li><li><strong>Developer experience</strong>: Simple decorator-based API</li><li><strong>Flexibility</strong>: Fine-grained control over what changes to listen for</li><li><strong>Scalability</strong>: Works seamlessly in distributed environments</li></ul><p>Give it a try in your next project! The library is open-source and available on GitHub and npm.</p><ul><li>GitHub: <a href="https://github.com/cisstech/nestkit/tree/main/libs/pg-pubsub">https://github.com/cisstech/nestkit/tree/main/libs/pg-pubsub</a></li><li>npm: <a href="https://www.npmjs.org/package/@cisstech/nestjs-pg-pubsub">https://www.npmjs.org/package/@cisstech/nestjs-pg-pubsub</a></li></ul><h4>Conclusion</h4><p>Building real-time features doesn’t have to be difficult. With <a href="https://github.com/cisstech/nestkit/tree/main/libs/pg-pubsub">nestjs-pg-pubsub</a>, you can leverage PostgreSQL’s powerful notification system with a clean, decorator-based API that integrates seamlessly with your NestJS application.</p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db724187df3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Declarative Angular authentication with structural directives]]></title>
            <link>https://medium.com/@mciissee/declarative-angular-authentication-with-authif-clean-templates-and-simpler-components-c1fdea95b141?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1fdea95b141</guid>
            <category><![CDATA[structural-directive]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 08:07:45 GMT</pubDate>
            <atom:updated>2025-03-21T23:57:16.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kR95BxTMdddi_d5EIkBKkw.png" /></figure><p>Authentication and authorization are fundamental aspects of modern web applications. However, managing these concerns in Angular can often lead to cluttered templates and components burdened with boilerplate logic. Traditional approaches using <strong>ngIf </strong>and manual state management can quickly become complex and difficult to maintain.</p><p>In this article, we’ll explore a more elegant and declarative solution using a custom structural directive called <strong>authIf</strong>. This directive, along with supporting components, allows you to express your authorization requirements directly in your Angular templates, resulting in cleaner code, improved developer experience, and enhanced application maintainability.</p><h4>The problem: Authentication complexity in Angular</h4><p>Before diving into the solution, let’s revisit the common problems developers face when handling authentication in Angular applications:</p><p><strong>Template clutter:</strong> Nested <strong>*ngIf</strong> directives (or the new <strong>@if</strong> syntax) for authorization checks can make templates hard to read and understand.<br><strong>Component bloat:</strong> Components often become responsible for managing authentication state (<strong>isLoading</strong>, <strong>isAuthenticated</strong>, <strong>user roles</strong>), fetching user data, and handling error scenarios, blurring their core purpose.<br><strong>Code duplication:</strong> Authentication checks are often repeated across multiple components, leading to code duplication and increased maintenance effort.<br><strong>Testing challenges:</strong> Components tightly coupled with authentication logic become harder to test in isolation.<br><strong>Reduced developer experience:</strong> Dealing with complex authentication logic can be time-consuming and error-prone.</p><h4>The solution: Declarative authentication with *authIf</h4><p>The <strong>authIf</strong> directive offers a declarative approach to authentication in Angular. It allows you to specify authorization conditions directly within your templates, delegating the underlying logic to the directive itself. This approach leads to several key benefits:</p><ul><li><strong>Cleaner templates:</strong> Authorization logic is moved out of template <strong>*ngIf</strong> chains and into a dedicated directive attribute.</li><li><strong>Simpler components:</strong> Components are freed from managing authentication state and boilerplate logic, allowing them to focus on their core responsibilities.</li><li><strong>Improved readability:</strong> Both templates and components become easier to read and understand.</li><li><strong>Enhanced maintainability:</strong> Changes to authentication rules are localized in the <strong>authIf</strong> directive, simplifying updates and reducing the risk of errors.</li><li><strong>Flexibility with hooks:</strong> <strong>authIf</strong> provides powerful hooks (<strong>authIfAuthorized</strong>, <strong>authIfDenied</strong>) to execute custom logic based on authorization outcomes.</li></ul><h4>Implementation details</h4><p>Let’s examine the code for the <strong>AuthIfDirective.</strong></p><pre>import { ... } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;../api/user.service&#39;; // Hypothetical API<br>import { User } from &#39;../models/user&#39;;         // Hypothetical Model<br><br>interface AuthContext {<br>  user: User;<br>}<br><br>@Directive({<br>  selector: &#39;[authIf]&#39;,<br>  exportAs: &#39;authIf&#39;,<br>  standalone: true<br>})<br>export class AuthIfDirective implements OnChanges {<br>  @Input() authIf: string | string[] = [];<br>  @Input() authIfElse?: TemplateRef&lt;any&gt;;<br>  @Input() authIfPending?: TemplateRef&lt;any&gt;;<br>  @Input() authIfDenied?: (error: any) =&gt; void | Promise&lt;void&gt;;<br>  @Input() authIfAuthorized?: (user: User) =&gt; void | Promise&lt;void&gt;;<br><br>  private readonly userService = inject(UserService)<br>  private readonly templateRef = inject(TemplateRef) as TemplateRef&lt;AuthContext&gt;<br>  private readonly viewContainerRef = inject(ViewContainerRef)<br>  private readonly changeDetectorRef = inject(ChangeDetectorRef)<br><br>  static ngTemplateContextGuard(dir: AuthIfDirective, ctx: unknown): ctx is AuthContext {<br>    return true;<br>  }<br><br><br>  ngOnChanges(changes: SimpleChanges): void {<br>    if (!changes[&#39;authIf&#39;]) {<br>      return;<br>    }<br><br>    this.viewContainerRef.clear();<br>    if (this.authIfPending) {<br>      this.viewContainerRef.createEmbeddedView(this.authIfPending);<br>      this.changeDetectorRef.detectChanges();<br>    }<br><br>    // Hypothetical user service API call<br>    // This api should handle concurrent calls to the directive by using rxjs operators<br>    this.userService.current().then((user) =&gt; {<br>      if (!user) {<br>        this.denied();<br>        return;<br>      }<br><br>      const conditions: string[] = [];<br>      if (!Array.isArray(this.authIf)) {<br>        if (this.authIf.trim()) {<br>          conditions.push(this.authIf.trim().toLowerCase());<br>        } else {<br>          conditions.push(&#39;connected&#39;)<br>        }<br>      } else {<br>        conditions.push(<br>          ...(this.authIf?.map(e =&gt; e.trim().toLowerCase()) || [])<br>        );<br>      }<br>        <br>      const meetAnyCondition = conditions.some((condition) =&gt; {<br>        return condition === user.status || condition === &#39;connected&#39;<br>      })<br><br>      if (!conditions.length || meetAnyCondition) {<br>        this.accepted(user);<br>      } else {<br>        this.denied();<br>      }<br>    }).catch(error =&gt; {<br>      this.denied(error);<br>    })<br>  }<br><br>  private async denied(error?: any): Promise&lt;void&gt; {<br>    try {<br>      if (this.authIfDenied) {<br>        await this.authIfDenied(error);<br>      }<br><br>      this.viewContainerRef.clear();<br>      if (this.authIfElse) {<br>        this.viewContainerRef.createEmbeddedView(this.authIfElse);<br>      }<br>    } finally {<br>      this.changeDetectorRef.detectChanges();<br>    }<br>  }<br><br>  private async accepted(user: User): Promise&lt;void&gt; {<br>    try {<br>      if (this.authIfAuthorized) {<br>        await this.authIfAuthorized(user);<br>      }<br>      this.viewContainerRef.clear();<br>      this.viewContainerRef.createEmbeddedView(<br>        this.templateRef, { user: user }<br>      );<br>    } catch (error) {<br>      this.denied(error);<br>    } finally {<br>      this.changeDetectorRef.detectChanges();<br>    }<br>  }<br>}</pre><h4>How AuthIfDirective works: A deep dive</h4><p>The <strong>AuthIfDirective</strong> is a structural directive that leverages Angular’s template manipulation capabilities to control the rendering of content based on authorization conditions. Let’s break down its key aspects:</p><p>1. <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() authIf:</strong> This input defines the authorization conditions. It can be a single string (e.g., “admin”, “connected”) or an array of strings (e.g., [“editor”, “publisher”]). These conditions are compared against the user’s status or roles retrieved from your authentication service.</p><p>2. <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() authIfElse?:</strong> This input allows you to provide a template to render when authorization is denied. This is the “else” branch of your authorization logic.</p><p>3. <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() authIfPending?:</strong> This input defines a template to display while the authentication check is in progress. This is crucial for providing a smooth user experience during asynchronous authentication operations.</p><p>4. <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() authIfDenied?: </strong>This is the first powerful hook. It allows you to provide a callback function that will be executed when authorization is denied. This function can handle errors, redirect users, log events, or perform other custom actions.</p><p>5. <a href="http://twitter.com/Input"><strong>@Input</strong></a><strong>() authIfAuthorized?:</strong> This is the second hook. It allows you to provide a callback function that is executed when authorization is successful. You can use this to perform actions like updating user state, logging successful access, or triggering other application logic.</p><p>6. <strong>ngOnChanges:</strong> A lifecycle hook triggered by Angular whenever the directive inputs value changes. Inside this hook:</p><p>— <strong>this.viewContainerRef.clear():</strong> Clears any previously rendered content in the view container.<br> — <strong>Pending State Handling:</strong> If <strong>authIfPending</strong> template is provided, it’s rendered to indicate loading.<br> — <strong>Asynchronous Authentication Check:</strong> <strong>this.userService.current().then(…) </strong>initiates an asynchronous call (using a hypothetical <strong>UserService</strong>) to check the user’s session and retrieve user data.<br> — <strong>Condition Evaluation:</strong> The directive evaluates the <strong>authIf</strong> conditions against the retrieved user data.<br> — <strong>accepted() and denied() methods:</strong> Based on the evaluation, either accepted() or denied() methods are called to handle authorized and unauthorized scenarios respectively.</p><p>7. <strong>accepted(user: User) and denied(error?: any) methods:</strong> These private methods handle the rendering of content based on the authorization result. They utilize <strong>this.viewContainerRef.createEmbeddedView()</strong> to render the appropriate template (<strong>this.templateRef</strong> for authorized content, <strong>this.authIfElse</strong> for denied content) and trigger the hook callbacks (<strong>authIfAuthorized</strong>, <strong>authIfDenied</strong>).</p><h4>Usage examples</h4><p>Let’s illustrate how to use the <strong>authIf</strong> directive in various scenarios:</p><p>Example 1 — Basic role-based authorization</p><pre>&lt;div *authIf=&quot;&#39;admin&#39;&quot;&gt;<br>  &lt;!-- Content visible only to admins --&gt;<br>  &lt;h1&gt;Admin Dashboard&lt;/h1&gt;<br>  &lt;p&gt;Welcome, Administrator!&lt;/p&gt;<br>&lt;/div&gt;<br><br>&lt;div *authIf=&quot;&#39;editor&#39;&quot;&gt;<br>  &lt;!-- Content visible only to editors --&gt;<br>  &lt;h2&gt;Editor Panel&lt;/h2&gt;<br>  &lt;p&gt;Edit content here.&lt;/p&gt;<br>&lt;/div&gt;<br><br>&lt;div *authIf=&quot;&#39;connected&#39;; else: notConnectedTemplate&quot;&gt;<br>  &lt;!-- Content visible to connected users --&gt;<br>  &lt;p&gt;Welcome, user!&lt;/p&gt;<br>&lt;/div&gt;<br><br>&lt;ng-template #notConnectedTemplate&gt;<br>  &lt;p&gt;Please connect to access this content.&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><p>Example 2 — Multi-role authorization with pending and denied templates</p><pre>&lt;ng-container<br>  *authIf=&quot;[&#39;admin&#39;, &#39;editor&#39;]; else: deniedTemplate; pending: loadingTemplate&quot;&gt;<br>  &lt;!-- Content visible to admins and editors --&gt;<br>  &lt;h2&gt;Admin &amp; Editor Section&lt;/h2&gt;<br>  &lt;p&gt;Content for privileged users.&lt;/p&gt;<br>&lt;/ng-container&gt;<br><br>&lt;ng-template #loadingTemplate&gt;<br>  &lt;p&gt;Checking authorization...&lt;/p&gt;<br>&lt;/ng-template&gt;<br><br>&lt;ng-template #deniedTemplate&gt;<br>  &lt;ui-error-403&gt;&lt;/ui-error-403&gt;<br>&lt;/ng-template&gt;</pre><p>Example 3 — Using hooks for redirection and analytics and page data fetching</p><pre>&lt;ng-container<br>  *authIf=&quot;[&#39;premium&#39;]; else: basicContent; pending: loadingTemplate;<br>         authorized: onPremiumAuthorized; denied: onPremiumDenied&quot;&gt;<br>  &lt;!-- Premium Content --&gt;<br>  &lt;h2&gt;Premium Features&lt;/h2&gt;<br>  &lt;p&gt;Enjoy exclusive content!&lt;/p&gt;<br>&lt;/ng-container&gt;<br><br>&lt;ng-template #basicContent&gt;<br>  &lt;p&gt;Upgrade to premium to access this content!&lt;/p&gt;<br>  &lt;a routerLink=&quot;/pricing&quot;&gt;Learn More&lt;/a&gt;<br>&lt;/ng-template&gt;<br><br>&lt;ng-template #loadingTemplate&gt;<br>  &lt;p&gt;Checking premium status...&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><p>TypeScript Component for Example 3 — Showing hook handlers</p><pre>import { Component } from &#39;@angular/core&#39;;<br>// User import<br><br>@Component({ /* ... component metadata ... */ })<br>export class MyComponent {<br><br>  onPremiumAuthorized(user: User): void {<br>    console.log(&#39;Premium user accessed premium content.&#39;, user);<br>  }<br><br>  onPremiumDenied(error: User): void {<br>    console.warn(&#39;Non-premium user tried to access premium content.&#39;, error);<br>  }<br>}</pre><h4>Benefits in detail</h4><p>Let’s revisit the key benefits of using <strong>authIf</strong> and elaborate on each:</p><p><strong>Cleaner templates:</strong> <strong>authIf</strong> significantly reduces template clutter by replacing verbose <strong>*ngIf</strong> chains with a concise and declarative syntax. This makes templates easier to read, understand, and maintain.</p><p><strong>Simpler components:</strong> Components become more focused and less burdened with authentication management. The directive handles the authentication logic, allowing components to concentrate on their core responsibilities, presentation and user interaction. This leads to leaner, more testable, and more maintainable components.</p><p><strong>Improved readability:</strong> The declarative nature of <strong>authIf</strong> enhances the readability of both templates and components. It’s immediately clear from the template which sections are protected and under what conditions. Component code becomes more focused and easier to follow.</p><p><strong>Enhanced maintainability:</strong> Centralizing authentication logic within the <strong>authIf</strong> directive improves maintainability. Changes to authentication rules or logic need to be made in one place, reducing the risk of errors and simplifying updates.</p><p><strong>Flexibility and Customization:</strong> The <strong>authIfElse</strong>, <strong>authIfPending</strong>, <strong>authIfAuthorized</strong>, and <strong>authIfDenied</strong> inputs provide significant flexibility. You can customize the user experience for different authorization states and implement complex authorization flows using the hook callbacks.</p><p><strong>Improved user experience:</strong> Using <strong>authIfPending</strong> for loading states and <strong>authIfElse</strong> for denied states allows you to create a smoother and more user-friendly authentication experience. Hooks further enhance UX by enabling actions like redirects and custom error handling.</p><p><strong>Declarative approach aligns with Angular principles:</strong> <strong>authIf</strong> embraces Angular’s declarative nature and component-based architecture. It promotes separation of concerns and encourages a more maintainable and scalable application structure.</p><h4>Conclusion</h4><p>The <strong>authIf</strong> directive, provides a powerful and elegant solution for declarative authentication in Angular applications. By shifting authentication logic from templates and components into a dedicated directive, you can achieve cleaner code, improved maintainability, enhanced developer experience, and a more user-friendly application.</p><p><strong>Connect with me</strong></p><p><a href="https://github.com/mciissee">Github</a>, <a href="https://www.linkedin.com/in/mciissee/">LinkedIn</a>, <a href="https://cisstech.com/">Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1fdea95b141" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Facade Design Pattern: Shielding Your App from Vendor Lock-In]]></title>
            <link>https://medium.com/@mciissee/the-facade-design-pattern-shielding-your-app-from-vendor-lock-in-d572e207367c?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d572e207367c</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[baas]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 12:08:09 GMT</pubDate>
            <atom:updated>2025-02-03T12:08:09.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*87YXoSZ3sXoHu_7wCkZYvQ.png" /><figcaption>Facade pattern illustration</figcaption></figure><p>Starting a company is like building a rocket while it’s already launching. You need to move fast, iterate quickly, and often rely on readily available tools to propel you forward. Backend-as-a-Service (BaaS) platforms like Firebase or AWS Amplify are incredibly tempting in these early days. They offer a buffet of pre-built backend functionalities such as databases, authentication, storage, and more. Letting you focus on your app’s core features.</p><p>It’s like finding a shortcut through a dense forest. BaaS <em>are</em> shortcuts. They can drastically reduce development time and complexity, especially when you’re a small team with limited resources. You can get your app off the ground faster, validate your idea, and start gathering user feedback.</p><p><strong>The Shiny Lure of “Easy Backend”</strong></p><p>Imagine building a course platform. With Firebase, you can quickly set up user authentication, store course data in their Firestore database, manage user enrollments, and even handle push notifications for new content. It’s all neatly packaged, seemingly magical, and <em>fast</em>. You’re thinking: “This is amazing! We’re building features, not infrastructure!”</p><p>And you’re right, to a point. In the beginning, this speed is a huge advantage. You can launch your Minimum Viable Product (MVP) and test the waters. But here’s the thing about shortcuts in dense forests: sometimes they lead you down a path that’s hard to turn back from.</p><p><strong>The Vendor Lock-in Trap</strong></p><p>As your startup gains traction and your app becomes more complex, you might start to feel the constraints of your chosen BaaS. Maybe Firebase’s specific database structure isn’t ideal anymore. Perhaps you need more granular control over your data or want to integrate with a service Firebase doesn’t directly support. Or, maybe, just maybe, you realize the pricing structure isn’t scalable as you grow.</p><p>Suddenly, you’re facing vendor lock-in. Your entire backend is deeply intertwined with Firebase’s APIs, SDKs, and specific ways of doing things. Migrating away feels like untangling a giant, spaghetti-like code mess. It’s costly, time-consuming, and risky. That shortcut you took in the beginning? It’s now a gilded cage.</p><p><strong>Building an “Escape Hatch” with the Facade Pattern</strong></p><p>This is where the Facade design pattern comes to the rescue. Think of a “facade” in architecture. It’s the front of a building, presenting a clean and unified appearance while hiding the complex inner workings. In software, the Facade pattern does the same thing: it provides a simplified interface to a complex subsystem.</p><p>In our startup app context, the “complex subsystem” is the BaaS you’re using (like Firebase). The Facade pattern allows us to create a layer of abstraction between your application code and the BaaS, shielding you from the BaaS’s specific details. This “shield” is your own custom-built interface, your “escape hatch” from vendor lock-in.</p><p><strong>Let’s Get Concrete: The Angular Course Platform Example</strong></p><p>Let’s solidify the Facade pattern with a practical example: our Angular course platform. We’ll build a CourseDetailPageComponent that displays course information. Instead of directly hitting Firebase, we’ll introduce the CourseService as our Facade, which in turn will use Providers to interact with the backend.</p><p><strong>1. The Angular Component: CourseDetailPageComponent (Standalone &amp; Reactive)</strong></p><p>Our CourseDetailPage is a standalone component, focusing solely on displaying course data. It’s completely unaware of <em>where</em> the data comes from. It relies on the CourseService to handle data retrieval as an Observable stream.</p><pre>// Angular Component - course-detail.page.ts<br><br>import { Component, OnInit, inject } from &#39;@angular/core&#39;;<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br>import { CourseService } from &#39;../course.service&#39;; // Import the Facade Service<br>import { Course } from &#39;../course.model&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Component({<br>  selector: &#39;app-course-detail&#39;,<br>  standalone: true,<br>  imports: [CommonModule],<br>  template: `<br>    @if (course$ | async; as course) {<br>      &lt;h2&gt;{{ course.title }}&lt;/h2&gt;<br>      &lt;p&gt;{{ course.description }}&lt;/p&gt;<br>      &lt;!-- ... display other course details ... --&gt;<br>    } @else {<br>      &lt;p&gt;Loading course details...&lt;/p&gt;<br>    }<br>  `,<br>  styleUrl: &#39;./course-detail.page.scss&#39;<br>})<br>export class CourseDetailPage implements OnInit {<br>  course$: Observable&lt;Course | null&gt;;<br>  courseId: string = &#39;&#39;;<br>  <br>  private readonly route = inject(ActivatedRoute);<br>  private readonly courseService = inject(CourseService);<br><br>  ngOnInit(): void {<br>    this.courseId = this.route.snapshot.paramMap.get(&#39;id&#39;) || &#39;&#39;;<br>    if (this.courseId) {<br>      this.loadCourseDetails(this.courseId);<br>    }<br>  }<br><br>  loadCourseDetails(courseId: string): void {<br>    this.course$ = this.courseService.getCourseDetails(courseId);<br>  }<br>}</pre><p><strong>Key points about the component:</strong></p><ul><li><strong>Standalone and Modern:</strong> It’s a standalone component (standalone: true), simplifying module structure.</li><li><strong>Reactive with Observables:</strong> It works with Observables (course$: Observable&lt;Course | null&gt;), embracing Angular’s reactive nature.</li><li><strong>async Pipe for Data Handling:</strong> The template uses (course$ | async; as course) to subscribe to the course$ Observable and elegantly unwrap the emitted Course object for display. The async pipe handles subscription management automatically, preventing memory leaks.</li><li><strong>Facade Service Injection:</strong> It injects the CourseService (our Facade) using the inject() function, decoupling it from backend details.</li><li><strong>Clean Template with @if:</strong> The new @if control flow syntax enhances template readability.</li></ul><p><strong>2. The Service Layer: CourseService (The Facade)</strong></p><p>The CourseService acts as the <strong>Facade</strong>. It provides a simplified, high-level interface for course-related operations, like fetching course details. Critically, it doesn’t know <em>how</em> the data is fetched. It delegates that responsibility to Providers. It also returns Observables, maintaining the reactive stream.</p><pre>// Angular Service - CourseService (Facade)<br><br>import { Injectable, inject } from &#39;@angular/core&#39;;<br>import { Course } from &#39;./course.model&#39;;<br>import { Observable } from &#39;rxjs&#39;<br>import { CourseProvider } from &#39;./course.provider&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class CourseService {<br>  private readonly courseProvider = inject(CourseProvider)<br><br>  getCourseDetails(courseId: string): Observable&lt;Course&gt; {<br>    return this.courseProvider.getCourse(courseId);<br>  }<br><br>  // ... other course-related operations<br>}</pre><p><strong>Why CourseService is the Facade:</strong></p><ul><li><strong>Simplified Interface:</strong> It offers clean, intent-revealing methods like getCourseDetails.</li><li><strong>Abstraction:</strong> It hides the complexity of data retrieval and the specific backend being used. Components interact with the CourseService without needing to know about Firebase or any other data source.</li><li><strong>BaaS Agnostic:</strong> It’s designed to work with an abstract CourseProvider abstract class, making it independent of any specific BaaS.</li></ul><p><strong>3. The Provider Layer: CourseProvider Abstract Class and Implementations</strong></p><p>The CourseProvider is an <strong>abstract class </strong>that defines the contract for data access. It specifies <em>what</em> operations are supported (e.g., getCourse), but not <em>how</em> they are implemented.</p><pre>// Abstract Provider - course.provider.ts<br>import { Observable } from &#39;rxjs&#39;<br><br>// It may be better to use interface, but Angular injection dependency does not<br>// works with interface (without using InjectionToken)<br><br>export abstract class CourseProvider {<br> abstract getCourse(courseId: string): Observable&lt;Course&gt;;<br>  // ... other provider methods<br>}</pre><p>Now, we create concrete <strong>implementations</strong> of the CourseProvider interface. In our early stage, we&#39;ll use FirebaseCourseProvider to interact with Firebase.</p><pre>// Firebase Course Provider - firebase-course.provider.ts<br>import { Injectable, inject } from &#39;@angular/core&#39;;<br>import { CourseProvider } from &#39;./course.provider&#39;;<br>import { Course } from &#39;./course.model&#39;;<br>import { Observable } from &#39;rxjs&#39;<br>import { AngularFirestore } from &#39;@angular/fire/firestore&#39;; // Firebase Specific<br><br>@Injectable()<br>export class FirebaseCourseProvider extends CourseProvider {<br>  private readonly firestore = inject(AngularFirestore)<br>  <br>  getCourse(courseId: string): Observable&lt;Course&gt; {<br>    // Firebase specific course retrieving logic<br>  }<br><br>  // ... other Firebase specific implementations<br>}</pre><p><strong>Providers: The Backend-Specific Logic</strong></p><ul><li><strong>Implement CourseProvider Interface:</strong> FirebaseCourseProvider (and any future providers) must implement the CourseProvider interface, ensuring they provide the required methods.</li><li><strong>BaaS Specific Logic:</strong> Providers contain the code that directly interacts with a specific backend (like Firebase, a custom API, or a different database). FirebaseCourseProvider uses AngularFirestore to interact with Firebase.</li><li><strong>Observable Return Values:</strong> Providers are responsible for returning Observables, ensuring a consistent reactive data flow throughout the application.</li></ul><p><strong>Dependency Injection Configuration (Illustrative)</strong></p><p>To wire everything up, you would configure Angular’s Dependency Injection in your module or component providers (depending on scope). Here’s a simplified example of how you might configure it in a module:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CourseService } from &#39;./course.service&#39;<br>import { CourseProvider } from &#39;./course.provider&#39;;<br>import { FirebaseCourseProvider } from &#39;./firebase-course.provider&#39;;<br><br>@NgModule({<br>  providers: [<br>    CourseService,<br>    { provide: CourseProvider, useClass: FirebaseCourseProvider },<br>  ]<br>})<br>export class CourseModule { }</pre><p><strong>Component -&gt; Service -&gt; Provider: The Facade Pattern in Action</strong></p><p>This layered architecture clearly demonstrates the Facade pattern:</p><ul><li><strong>CourseDetailPageComponent (Component):</strong> Completely decoupled from backend details. It interacts with the CourseService.</li><li><strong>CourseService (Service — Facade):</strong> Provides a simplified interface and delegates to providers. It’s BaaS-agnostic.</li><li><strong>FirebaseCourseProvider (Provider):</strong> Handles the Firebase-specific logic, implementing the CourseProvider interface.</li></ul><p>This separation of concerns is what gives us the “escape hatch” from vendor lock-in. If we decide to move away from Firebase, we simply need to create a new provider (e.g., CustomAPICourseProvider) that implements the CourseProvider interface and interacts with our new backend. Then, in our dependency injection configuration, we would switch to using CustomAPICourseProvider instead of FirebaseCourseProvider. The rest of our application (components and the CourseService Facade) remains largely unchanged!</p><p>This example showcases how the Facade pattern, combined with dependency injection and a layered architecture, empowers you to build startup applications that are fast to develop initially (using BaaS) but also flexible and resilient to future changes and backend migrations.</p><p><strong>The “Escape Hatch” Scenario</strong></p><p>Now, imagine your startup outgrows Firebase. You decide to migrate to a different backend solution, maybe a custom-built API and a different database. Because you used the Facade pattern:</p><ol><li><strong>Your Components are Untouched:</strong> CourseDetailPage and other components remain blissfully ignorant of the backend switch.</li><li><strong>Your Service (CourseService) Remains Largely Intact:</strong> The core logic and interface of CourseService likely stay the same. You might need minor adjustments, but the fundamental structure is preserved.</li><li><strong>You Replace Providers:</strong> This is where the magic happens. You create new providers — let’s say CustomAPICourseProvider — that implement the CourseProvider interface but interact with your <em>new</em> backend API instead of Firebase.</li></ol><pre>// Custom API Course Provider - custom-api-course.provider.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { CourseProvider } from &#39;./course.provider&#39;;<br>import { Course } from &#39;./course.model&#39;;<br>import { Observable } from &#39;rxjs&#39;<br>import { HttpClient } from &#39;@angular/common/http&#39;; // Example API client<br><br>@Injectable()<br>export class CustomAPICourseProvider implements CourseProvider {<br><br>  constructor(private http: HttpClient) { }<br><br>  getCourse(courseId: string): Observable&lt;Course&gt; {<br>     return this.http.get&lt;Course&gt;(`/api/courses/${courseId}`)<br>  }<br><br>  // ... other API specific implementations<br>}</pre><p><strong>Switching Providers is (Relatively) Easy</strong></p><p>In your Angular module’s provider configuration, you simply switch from FirebaseCourseProvider to CustomAPICourseProvider (or configure it based on environment variables!). Your application, built on the Facade principle, seamlessly adapts to the new backend without massive code rewrites.</p><p><strong>Beyond BaaS: Flexibility for the Future</strong></p><p>The beauty of the Facade pattern extends beyond just escaping BaaS lock-in. It provides:</p><ul><li><strong>Testability:</strong> You can easily mock and test your CourseService and components in isolation, without needing to spin up Firebase emulators or interact with a real BaaS.</li><li><strong>Maintainability:</strong> Changes to the backend (Firebase upgrades, API modifications) are isolated within the providers, minimizing the impact on your application’s core logic.</li><li><strong>Flexibility for Future Changes:</strong> Imagine you want to add caching, use a different database for specific features, or even switch to a completely different data source. The Facade pattern makes these transitions much smoother.</li></ul><p><strong>Early Investment, Long-Term Freedom</strong></p><p>While it might seem like extra work to implement the Facade pattern in the early stages of your app, it’s an investment in your future flexibility and freedom. It’s like building a bridge across a river instead of just wading through it. It takes a bit more upfront effort, but it provides a much more stable and adaptable path forward.</p><p>Don’t let the initial allure of “easy backend” trap you in vendor lock-in. Embrace the Facade pattern. Build bridges, not walls. Your future self (and your team) will thank you for it. You’ll be building an app that’s not just fast to launch, but also resilient, adaptable, and truly your own.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d572e207367c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Form Manager Pattern: Simplifying Heterogeneous Form Management in React Applications]]></title>
            <link>https://medium.com/@mciissee/form-manager-pattern-simplifying-heterogeneous-form-management-in-react-applications-11207930d289?source=rss-aba318037b1d------2</link>
            <guid isPermaLink="false">https://medium.com/p/11207930d289</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-forms]]></category>
            <dc:creator><![CDATA[Mamadou CISSE]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 23:23:55 GMT</pubDate>
            <atom:updated>2025-05-04T09:10:03.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XIL-hkv5gUbHMZuH" /><figcaption>Photo by <a href="https://unsplash.com/@halacious?utm_source=medium&amp;utm_medium=referral">Hal Gatewood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Managing forms in React applications is a common yet challenging task for developers. As our applications grow in complexity, we often encounter scenarios where we need to handle forms for different object types, each with its own set of attributes and requirements with some shared ui elements. In this article, we’ll explore a solution to this challenge by introducing a pattern I would like to call Form Manager Pattern. This pattern introduces a clear distinction between managing form data/validation and displaying form elements, enabling efficient management of forms across various object types.</p><h3>Importance of a unified approach</h3><p>When dealing with diverse object types in a React application, it’s crucial to establish a unified approach to form management. Without a standardized solution, developers may find themselves duplicating code, managing complex conditional rendering logic, and struggling to maintain a cohesive user interface. A unified approach streamlines the development process, making it easier to maintain, update, and scale our applications.</p><p>Now, let’s dive into the analogy that will guide us through this exploration: the Task Management System.</p><h3>Understanding the challenge</h3><h3>Analogy: The task management system</h3><p>Imagine a Task Management System where users can create various types of tasks, each with its unique attributes and complexities. Tasks range from simple to complex projects, and managing the forms for these tasks becomes a significant challenge. This analogy mirrors the real-world scenario of managing forms for different object types in a React application.</p><h3>Illustrative challenges</h3><ul><li>Diverse Task Types: Tasks can vary widely, from straightforward to intricate. Handling forms for these different task types introduces complexity in managing state, handling user input, and rendering the appropriate UI elements.</li><li>Attribute Variations: Each task type may have specific attributes. For example, a simple task may only require a name and description, while a project task might include additional fields like start date, end date, and collaborators. The challenge lies in creating a flexible yet consistent approach to form management that accommodates these variations without duplicating code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOmF9zS1RiprT3eNCqkVTQ.png" /></figure><p>Now, let’s explore how to addresses these challenges.</p><h3>A solution : Form manager pattern</h3><h3>The FormManager</h3><p>The FormManager serves as the orchestrator, responsible for handling the form’s state, actions, and interactions. In our example, the useFormManager hook embodies this role. It encapsulates common form functionalities such as editing, canceling, patching changes, and submitting.</p><pre>// hooks/useFormManager.tsx<br><br>import { FormInstance } from &#39;antd&#39;<br>import { useForm } from &#39;antd/es/form/Form&#39;<br>import { useEffect, useMemo, useState } from &#39;react&#39;<br><br>/**<br> * Interface representing the configuration for the Form Manager.<br> *<br> * @template TEntity - The type of the entity being managed by the form.<br> * @template TModel - The type of the data model for the form.<br> * @template TProps - Additional props for the form.<br> */<br>export type FormManagerConfig&lt;TEntity, TModel, TProps extends object&gt; = {<br>  /**<br>   * The entity being managed by the form.<br>   */<br>  entity?: TEntity;<br>  /**<br>   * Adapter function to convert the entity to the form data model.<br>   *<br>   * @param entity - The entity to be adapted.<br>   * @returns The adapted data model.<br>   */<br>  adapter: (entity: TEntity) =&gt; TModel;<br>  /**<br>   * Additional props for the form.<br>   */<br>  props?: TProps;<br>}<br><br>/**<br> * Interface representing the common properties of the Form Manager.<br> *<br> * @template TModel - The type of the data model for the form.<br> * @template TProps - Additional props for the form.<br> */<br>export type FormModel&lt;TModel, TProps extends object&gt; = TProps &amp; {<br>  /**<br>   * The current value of the form.<br>   */<br>  value: TModel;<br>  /**<br>   * Indicates whether the form is in editing mode.<br>   */<br>  editing: boolean;<br>  /**<br>   * Form Instance from Ant Design&#39;s useForm hook.<br>   */<br>  instance: FormInstance&lt;TModel&gt;;<br>  /**<br>   * Sets the editing status and synchronizes the form fields when entering editing mode.<br>   *<br>   * @param editing - The new editing status.<br>   */<br>  setEditing: (editing: boolean) =&gt; void;<br>  /**<br>   * Cancels the editing mode, reverts changes, and resets the form fields.<br>   */<br>  cancelEditing: () =&gt; void;<br>  /**<br>   * Patches changes to the form value and updates the form fields.<br>   *<br>   * @param changes - The changes to apply to the form value.<br>   */<br>  patch: (changes: TModel) =&gt; void;<br>  /**<br>   * Submits the form using Ant Design&#39;s submit function.<br>   */<br>  submit: () =&gt; void;<br>}<br><br>/**<br> * useFormManager Hook<br> *<br> * This hook provides a Form Manager for handling form state, actions, and interactions.<br> * It is designed to streamline form management for diverse data objects in React applications.<br> *<br> * @param config - Configuration for the Form Manager.<br> * @returns FormManager object containing form state and actions.<br> * @template TEntity - The type of the entity being managed by the form.<br> * @template TModel - The type of the data model for the form.<br> * @template TProps - Additional props for the form.<br> */<br> export const useFormManager = &lt;TEntity, TModel, TProps extends object&gt;(<br>   config: FormManagerConfig&lt;TEntity, TModel, TProps&gt;,<br> ) =&gt; {<br>   const { entity, adapter, props } = config<br><br>   const [value, setValue] = useState&lt;TModel&gt;(entity ? adapter(entity) : ({} as TModel));<br>   const [oldValue, setOldValue] = useState&lt;TModel&gt;(entity ? adapter(entity) : ({} as TModel));<br>   const [editing, setEditing] = useState(false);<br><br>   const [instance] = useForm&lt;TModel&gt;()<br><br>   <br>   // Effect to update form value when the entity changes.<br>   // We assume that the entity is not re-fetched from the backend on each render<br>   useEffect(() =&gt; {<br>     setValue(entity ? adapter(entity) : ({} as TModel))<br>   }, [entity])<br><br>   return useMemo(<br>     () =&gt; ({<br>       ...props,<br>       value,<br>       editing,<br>       instance,<br>       setEditing: (editing: boolean) =&gt; {<br>         setEditing(editing)<br>         if (editing) {<br>           instance.setFieldsValue(value as any)<br>           setOldValue({ ...value })<br>         }<br>       },<br>       cancelEditing: () =&gt; {<br>         setEditing(false)<br>         setValue({ ...oldValue })<br>         instance.resetFields()<br>       },<br>       patch: (changes: TModel) =&gt; {<br>         const newValue = { ...value, ...changes }<br>         setValue(newValue)<br>         instance.setFieldsValue(newValue as any)<br>       },<br>       submit: () =&gt; {<br>         instance.submit()<br>       },<br>     }),<br>     [value, editing, entity],<br>   ) as FormModel&lt;TModel, TProps&gt;<br> }</pre><p>Here’s a breakdown of key features within the FormManager:</p><ul><li><strong>value</strong>: Represents the current state of the form data.</li><li><strong>editing</strong>: Indicates whether the form is in editing mode.</li><li><strong>instance</strong>: A AntDesign FormInstance for managing form fields.</li><li><strong>setEditing</strong>: Controls the editing state and synchronizes the form fields.</li><li><strong>cancelEditing</strong>: Reverts changes and resets the form to its initial state.</li><li><strong>patch</strong>: Updates specific attributes within the form data.</li><li><strong>submit</strong>: Initiates the form submission.</li></ul><h3>The FormElements</h3><p>On the other side, we have FormElements representing the individual building blocks of the form. These elements are customized based on the specific data object being managed. In our scenario, useTaskFormElements is a utility hook that tailors the form elements for different task types.</p><pre>// models/elements.tsx<br><br>/**<br> * Interface representing the form elements for a specific set of keys.<br> *<br> * @template Keys - The keys for the form elements.<br> */<br>export type FormElements&lt;Keys extends string&gt; = Record&lt;Keys, React.ReactNode | string | number | undefined&gt;</pre><h3>Code walkthrough: Task form management</h3><h3>Use case: Task management system</h3><p>Let’s apply the pattern to our Task Management System analogy. Consider a scenario where tasks can be of different types: simple tasks and complex projects. We want a unified form management approach to handle both cases seamlessly.</p><pre>// models/task.tsx<br><br>export type SimpleTaskModel = {<br>  id: number<br>  type: &#39;simple&#39;<br><br>  name: string<br>  description: string<br>  priority: number<br><br>  assignedToUser?: string<br><br>  permissions: {<br>    edit: boolean<br>  }<br>}<br><br>export type ComplexTaskModel = {<br>  id: number<br>  type: &#39;complex&#39;<br><br>  name: string<br>  description: string<br>  priority: number<br><br>  assignedToTeam?: string[]<br>  projectManager?: string<br>  estimatedAt?: Date<br>  teamMembers?: string[]<br><br>  permissions: {<br>    edit: boolean<br>  }<br>}<br><br><br>export type TaskModel = SimpleTaskModel | ComplexTaskModel</pre><pre>// hooks/useTaskFormManager.tsx<br><br>import moment, { Moment } from &#39;moment&#39;<br>import { TaskModel } from &#39;../models/task&#39;<br>import { useFormManager } from &#39;./useFormManager&#39;<br><br>// Mixing of all field in simple tasks and/or complex tasks<br>export type TaskFormModel = {<br>  // COMMON<br>  name: string<br>  description: string<br>  priority: number<br><br>  // SIMPLE TASK SPECIFIC<br>  assignedToUser?: string<br><br>  // COMPLEX TASK SPECIFIC<br>  assignedToTeam?: string[]<br>  projectManager?: string<br>  estimatedAt?: Moment | null<br>  teamMembers?: string[]<br>}<br><br>export type TaskFormManager = ReturnType&lt;typeof useTaskFormManager&gt;<br><br>export const useTaskFormManager = (task: TaskModel) =&gt; {<br>  return useFormManager({<br>    entity: task,<br>    props: {<br>      canEdit: task.permissions.edit,<br>    },<br>    adapter: (task) =&gt; {<br>      const formModel: TaskFormModel = {<br>        // COMMON<br>        name: task.name,<br>        description: task.description,<br>        priority: task.priority,<br><br>        // SIMPLE SPECIFIC<br>        ...(task.type === &#39;simple&#39;<br>          ? {<br>              assignedToUser: task.assignedToUser,<br>            }<br>          : {}),<br><br>        // COMPLEX SPECIFIC<br>        ...(task.type === &#39;complex&#39;<br>          ? {<br>              assignedToTeam: task.assignedToTeam,<br>              projectManager: task.projectManager,<br>              estimatedAt: task.estimatedAt ? moment(task.estimatedAt) : null,<br>              teamMembers: task.teamMembers,<br>            }<br>          : {}),<br>      }<br>      return formModel<br>    },<br>  })<br>}</pre><p>Explanation :</p><ul><li>Task Models: We define two task models, SimpleTaskModel and ComplexTaskModel, each representing a different type of task with specific properties.</li><li>Form Manager for Tasks: The useTaskForm hook uses the useFormManager pattern to create a form manager for tasks. It abstracts away the complexities of managing different task types by adapting them to a common TaskFormModel. The form manager handles form state, actions, and interactions, providing a unified interface for working with tasks.</li></ul><p>This example demonstrates how the pattern simplifies form management for heterogeneous data structures, making it easy to handle various task types within a React application.</p><h3>FormElements customization</h3><p>To accommodate the variations in attributes for different task types, we can employ the useTaskFormElements utility. This utility customizes form elements based on the type of task being managed.</p><pre>// hooks/useTaskFormElements.js<br><br>import { DatePicker, Form, Input, InputNumber, Select } from &#39;antd&#39;<br>import { TaskModel } from &#39;../models/task&#39;<br>import { TaskFormManager } from &#39;./useTaskForm&#39;<br>import { FormElements } from &#39;../models/elements&#39;<br><br>const FormItem = Form.Item<br><br>type CommonElements = FormElements&lt;<br>  | &#39;name&#39;<br>  | &#39;description&#39;<br>  | &#39;priority&#39;<br>&gt;<br><br>type SimpleElements = FormElements&lt;&#39;assignedToUser&#39;&gt;<br><br>type ComplexElements = FormElements&lt;<br>  | &#39;assignedToTeam&#39;<br>  | &#39;projectManager&#39;<br>  | &#39;estimatedAt&#39;<br>  | &#39;teamMembers&#39;<br>&gt;<br><br>export type TaskFormElements = CommonElements &amp; SimpleElements &amp; ComplexElements<br><br>export const useTaskFormElements = (form: TaskFormManager, task: TaskModel): TaskFormElements =&gt; {<br>  const commonElements: CommonElements = {<br>    name: form.editing ? (<br>      &lt;FormItem name=&quot;name&quot; rules={[{ required: true, type: &#39;string&#39;, min: 3 }]}&gt;<br>        &lt;Input /&gt;<br>      &lt;/FormItem&gt;<br>    ) : (<br>      task.name<br>    ),<br>    description: form.editing ? (<br>      &lt;FormItem name=&quot;description&quot; rules={[{ required: true, type: &#39;string&#39;, min: 3 }]}&gt;<br>        &lt;Input.TextArea /&gt;<br>      &lt;/FormItem&gt;<br>    ) : (<br>      task.description<br>    ),<br>    priority: form.editing ? (<br>      &lt;FormItem name=&quot;priority&quot; rules={[{ required: true, type: &#39;number&#39; }]}&gt;<br>        &lt;InputNumber /&gt;<br>      &lt;/FormItem&gt;<br>    ) : (<br>      task.priority<br>    ),<br>  }<br><br>  let simpleElements = {} as SimpleElements<br>  if (task.type === &#39;simple&#39;) {<br>    simpleElements = {<br>      assignedToUser: form.editing ? (<br>        &lt;FormItem name=&quot;assignedToUser&quot;&gt;<br>          &lt;Input /&gt;<br>        &lt;/FormItem&gt;<br>      ) : (<br>        task.assignedToUser<br>      ),<br>    }<br>  }<br><br>  let complexElements = {} as ComplexElements<br>  if (task.type === &#39;complex&#39;) {<br>    complexElements = {<br>      assignedToTeam: form.editing ? (<br>        &lt;FormItem name=&quot;assignedToTeam&quot;&gt;<br>          &lt;Select mode=&quot;multiple&quot; placeholder=&quot;Please select users...&quot;&gt;<br>            {/* Options for team members */}<br>          &lt;/Select&gt;<br>        &lt;/FormItem&gt;<br>      ) : (<br>        task.assignedToTeam?.join(&#39;, &#39;)<br>      ),<br>      projectManager: form.editing ? (<br>        &lt;FormItem name=&quot;projectManager&quot;&gt;<br>          &lt;Select placeholder=&quot;Please select an user...&quot;&gt;{/* Options for project managers */}&lt;/Select&gt;<br>        &lt;/FormItem&gt;<br>      ) : (<br>        task.projectManager<br>      ),<br>      estimatedAt: form.editing ? (<br>        &lt;FormItem name=&quot;estimatedAt&quot;&gt;<br>          &lt;DatePicker /&gt;<br>        &lt;/FormItem&gt;<br>      ) : (<br>        task.estimatedAt?.toString()<br>      ),<br>      teamMembers: form.editing ? (<br>        &lt;FormItem name=&quot;teamMembers&quot;&gt;<br>          &lt;Select mode=&quot;multiple&quot; placeholder={&#39;&#39;}&gt;<br>            {/* Options for team members */}<br>          &lt;/Select&gt;<br>        &lt;/FormItem&gt;<br>      ) : (<br>        task.teamMembers?.join(&#39;, &#39;)<br>      ),<br>    }<br>  }<br><br>  return {<br>    ...commonElements,<br>    ...simpleElements,<br>    ...complexElements,<br>  }<br>}</pre><p>Now, we can use useTaskFormElements to render form elements specific to task types, maintaining a clean and modular structure.</p><p>In the next section, we’ll explore the concept of reusable components, focusing on the creation of forms using these hooks.</p><h3>Combine manager and elements</h3><p>The TaskUpdateForm component serves as a container for displaying a form for updating task.</p><pre>// task-update-form.tsx<br><br>import { Button, Col, Descriptions, Form, Row, Space, message } from &#39;antd&#39;<br>import { TaskFormModel, useTaskFormManager } from &#39;../hooks/useTaskForm&#39;<br>import { TaskFormElements, useTaskFormElements } from &#39;../hooks/useTaskFormElements&#39;<br>import { TaskModel } from &#39;../models/task&#39;<br><br>// These layout are just for demo purposes and not following any design guidelines<br><br>const SimpleLayout = (elements: TaskFormElements) =&gt; {<br>  return (<br>    &lt;Row gutter={[16, 16]}&gt;<br>      &lt;Col span={24}&gt;<br>        &lt;Space direction=&quot;vertical&quot; style={{ width: &#39;100%&#39; }}&gt;<br>          &lt;div&gt;<br>            &lt;strong&gt;Name:&lt;/strong&gt; {elements.name}<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;strong&gt;Description:&lt;/strong&gt; {elements.description}<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;strong&gt;Priority:&lt;/strong&gt; {elements.priority}<br>          &lt;/div&gt;<br>          &lt;div&gt;<br>            &lt;strong&gt;Assigned To User:&lt;/strong&gt; {elements.assignedToUser}<br>          &lt;/div&gt;<br>        &lt;/Space&gt;<br>      &lt;/Col&gt;<br>    &lt;/Row&gt;<br>  )<br>}<br><br>const ComplexLayout = (elements: TaskFormElements) =&gt; {<br>  return (<br>    &lt;Descriptions column={2} bordered&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Name&quot;&gt;<br>        {elements.name}<br>      &lt;/Descriptions.Item&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Description&quot;&gt;<br>        {elements.description}<br>      &lt;/Descriptions.Item&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Priority&quot;&gt;<br>        {elements.priority}<br>      &lt;/Descriptions.Item&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Assigned To Team&quot;&gt;<br>        {elements.assignedToTeam}<br>      &lt;/Descriptions.Item&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Project Manager&quot;&gt;<br>        {elements.projectManager}<br>      &lt;/Descriptions.Item&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Estimated At&quot;&gt;<br>        {elements.estimatedAt}<br>      &lt;/Descriptions.Item&gt;<br>      &lt;Descriptions.Item span={2} label=&quot;Team Members&quot;&gt;<br>        {elements.teamMembers}<br>      &lt;/Descriptions.Item&gt;<br>    &lt;/Descriptions&gt;<br>  )<br>}<br><br>type Props = {<br>  task: TaskModel<br>  onSubmit: (form: TaskFormModel) =&gt; Promise&lt;void&gt;<br>}<br><br>export const TaskUpdateForm: React.FC&lt;Props&gt; = ({ task, onSubmit }) =&gt; {<br>  const form = useTaskFormManager(task)<br>  const elements = useTaskFormElements(form, task)<br><br>  return (<br>    &lt;Form&lt;TaskFormModel&gt;<br>      form={form.instance}<br>      initialValues={form.value}<br>      onFinish={(values) =&gt; {<br>        onSubmit(values)<br>          .then(() =&gt; {<br>            form.setEditing(false)<br>            message.success(&#39;Task updated successfully&#39;)<br>          })<br>          .catch(() =&gt; {<br>            message.error(&#39;Error updating task&#39;)<br>          })<br>      }}<br>      onValuesChange={(_, values) =&gt; form.patch(values)}<br>    &gt;<br>      &lt;Space direction=&quot;vertical&quot; style={{ width: &#39;100%&#39; }}&gt;<br>        {task.type === &#39;simple&#39; &amp;&amp; SimpleLayout(elements)}<br>        {task.type === &#39;complex&#39; &amp;&amp; ComplexLayout(elements)}<br>        &lt;Space&gt;<br>          {!form.editing &amp;&amp; form.canEdit &amp;&amp; (<br>            &lt;Button type=&quot;primary&quot; onClick={() =&gt; form.setEditing(true)}&gt;<br>              Edit<br>            &lt;/Button&gt;<br>          )}<br>          {form.editing &amp;&amp; &lt;Button onClick={() =&gt; form.cancelEditing()}&gt;Cancel&lt;/Button&gt;}<br><br>          {form.editing &amp;&amp; (<br>            &lt;Button type=&quot;primary&quot; onClick={() =&gt; form.submit()}&gt;<br>              Save<br>            &lt;/Button&gt;<br>          )}<br>        &lt;/Space&gt;<br>      &lt;/Space&gt;<br>    &lt;/Form&gt;<br>  )<br>}</pre><p>Now, the TaskUpdateForm component can seamlessly handle the update of different types of tasks. Through the combination of the useTaskFormManager hook and useTaskFormElements, we&#39;ve established a modular and adaptable solution for managing heterogeneous forms within our Task Management System. If there&#39;s a need to reuse the logic for creating a task, creating a new TaskCreateForm component with a distinct layout becomes a straightforward process.</p><p>In the final section, we’ll explore the benefits and best practices of this approach, highlighting the consistency in UI, code reusability, and maintainability it offers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gq9s0r8PMlYwB_4_LVWb4w.png" /><figcaption>Simple task form edit mode layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7l29obOr9WFbRF-Ki437Q.png" /><figcaption>Complex task form edit mode layout</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUOhSt4kYlMb3WYTjrpr5A.png" /><figcaption>Complex task form preview mode layout</figcaption></figure><h3>Benefits and best practices</h3><h3>Consistency in user interface</h3><p>The use of useTaskFormManager and useTaskForElements hooks ensures a consistent user interface across different types of tasks. Users interacting with the Task Management System will experience a standardized form layout and behavior, regardless of the task&#39;s complexity.</p><h3>Code reusability</h3><p>The modular structure of the pattern, promotes code reusability. Developers can easily integrate the new form variants into different parts of the application without duplicating form-related logic. This reusability simplifies development, reduces code redundancy, and accelerates the creation of new features.</p><h3>Adaptability to future changes</h3><p>As the Task Management System evolves, new task types with unique attributes may be introduced. The pattern provides flexibility to adapt to future changes. Adding support for a new task type involves extending the form elements and model, rather than modifying existing code extensively.</p><h3>Maintaining a clean and readable codebase</h3><p>The separation of concerns achieved by using the hooks contributes to a clean and readable codebase. Form-related logic is isolated and organized, making it easier for developers to understand, maintain, and troubleshoot the application.</p><h3>Conclusion</h3><p>In this article, we’ve explored a practical solution for simplifying the management of heterogeneous forms in React applications. By leveraging the a manager and elements builder hooks, we’ve demonstrated how to achieve consistency, reusability, and adaptability in the context of a Task Management System.</p><p>As you apply these concepts to your own projects, consider the unique requirements of your application and how the presented approach can be tailored to suit your needs. With a thoughtful application of these principles, you can streamline form management and enhance the overall development experience.</p><p>Links :</p><ul><li>Live demo : <a href="https://cisstech.github.io/react-playground/form-manager">https://cisstech.github.io/react-playground/form-manager</a></li><li>Source code : <a href="https://github.com/cisstech/react-playground/tree/main/libs/form-manager">https://github.com/cisstech/react-playground/tree/main/libs/form-manager</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11207930d289" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>