<?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 Amit Gal on Medium]]></title>
        <description><![CDATA[Stories by Amit Gal on Medium]]></description>
        <link>https://medium.com/@amitgal45?source=rss-492b643c087e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HknRYBUWGPgUgI4_</url>
            <title>Stories by Amit Gal on Medium</title>
            <link>https://medium.com/@amitgal45?source=rss-492b643c087e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 07:19:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitgal45/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[Your AI coding agent leaves zombies behind. I built a Mac app to reap them.]]></title>
            <link>https://medium.com/@amitgal45/your-ai-coding-agent-leaves-zombies-behind-i-built-a-mac-app-to-reap-them-9e5036455c8b?source=rss-492b643c087e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5036455c8b</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[productivity-tools]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[utilities]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Amit Gal]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 15:26:29 GMT</pubDate>
            <atom:updated>2026-11-17T15:28:06.319Z</atom:updated>
            <content:encoded><![CDATA[<p>PortReaper is a free, open-source macOS app that shows the project and git branch behind every port on your machine, finds the processes your agents left running, and stops them in one keystroke.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwPpLMT_su5gOtJUiKO06g.jpeg" /><figcaption>PortReaper: your AI agents leave zombies behind</figcaption></figure><p>You know this message:</p><pre>Error: listen EADDRINUSE: address already in use :::3000</pre><p>And you know the ritual that follows: you run lsof -i :3000, squint at a PID, run kill -9 48213 and hope it was the right one.</p><p>For years I did that a few times a day and didn’t think much of it. Then the way I write code changed, and the ritual stopped being enough.</p><h3>Why lsof stopped being enough once agents took over my terminal</h3><p>I work with a lot of agents at once now, usually several Claude Code sessions, often on different git worktrees of the same project. Every one of those sessions starts its own helpers: MCP servers, a Playwright browser, Vitest workers, esbuild, rust-analyzer, and of course the dev servers.</p><p>Sessions get stuck, terminals get closed, and the helpers stay behind. macOS re-parents them to launchd (PID 1) and they just sit there. More than once I ended the day with a Mac whose fans were roaring over a pile of node processes nobody was using anymore.</p><p>Many of them don’t even hold a port. MCP servers talk over stdio, so lsof -i will never show them. I&#39;d notice only when Activity Monitor showed a row of identical node processes and no way to tell which project any of them belonged to.</p><p>And when it was a port, the PID told me nothing. Three worktrees of the same app all run node, on 3000, 3001 and 5173. Which one is the stale one?</p><p>I wanted a tool that answers one question fast: <strong>what is this, which project is it from, and is it safe to kill?</strong> Nothing I tried did all three, so I built PortReaper. (Later I found LeftOpen, which goes after the same problem; there’s a comparison below.)</p><h3>Every port, with the project and branch behind it</h3><p>PortReaper lists every listening port on your Mac, TCP and UDP, IPv4 and IPv6, and tells you in plain words what’s behind it. Instead of node 48213 you see the line I always wanted from lsof:</p><p>shop-api · feature/cart · vite</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2IQhh6gxg0iKyF9u.png" /><figcaption>Every port, grouped by project and branch, with zombies flagged.</figcaption></figure><ul><li><strong>The project and branch.</strong> The name comes from package.json, Cargo.toml, pyproject.toml or go.mod. The branch is read from .git/HEAD, worktrees included. The tool comes from the command line: Next.js, Vite, NestJS, PostgreSQL, Ollama, MCP, Playwright, Vitest. When it isn&#39;t sure, it shows nothing rather than a guess.</li><li><strong>A category for every port:</strong> web, api, db, local AI, system. A port bound to every interface gets a “public on your Wi-Fi” badge.</li><li><strong>The Zombie Reaper.</strong> It finds dev servers whose terminal is gone, and portless stdio orphans like mcp-server-*, chrome-headless-shell, vitest and jest workers, esbuild and rust-analyzer hanging under PID 1. It badges them, shows how much RAM they hold, and reaps them all in one click. Strictly speaking these are orphans, not zombies: they&#39;re alive, and launchd adopted them. But &#39;zombie&#39; is what they feel like, and it&#39;s what the app calls them.</li><li><strong>Hidden ports.</strong> Hide the ports you never want to see, like AirPlay on 5000 and 7000, and they drop out of the list, the menu-bar count and the ⌘⇧K strip.</li><li><strong>The drawer.</strong> Open a row and you see the process tree, working directory, branch, bind address and full command, with Kill and Restart buttons.</li><li><strong>The Taskline.</strong> Everything it did this session: when, how long the kill took, how much memory came back. If you killed the wrong thing, Relaunch starts the same command in the same directory.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ly_qzKcC-QmDaC11.png" /><figcaption>The drawer: process tree, project, branch and the full command behind :3000.</figcaption></figure><h3>Freeing port 3000 in two seconds from any app</h3><p>This is the part I use most. Port 3000 is taken. From any app I press <strong>⌘⇧K</strong> (VS Code and Cursor use it for Delete Line and Xcode for Clean Build Folder, so you can change it in Preferences). A thin strip appears over whatever I’m doing, and the port most likely in my way is already selected: a dev server that lost its terminal, or the one I started most recently. I type 3 to narrow it to :3000 and press Enter.</p><p>The process gets SIGTERM, up to three seconds to close its sockets, then SIGKILL. The strip says Freed :3000 · node (48213), disappears, and focus is back in my terminal without me ever opening a window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*OwmqzbH8-LLSna25.gif" /><figcaption>EADDRINUSE, ⌘⇧K, type 3000, Enter. The dev server starts.</figcaption></figure><h3>What lsof, Activity Monitor and kill-port each miss</h3><p>I tried the usual options first. Each one solves part of the problem.</p><ul><li>lsof -i<strong> + </strong>kill<strong>.</strong> Always there, and precise. But it gives you a PID and a process name, not a project, and it can&#39;t see processes that hold no port, which is exactly where agent leftovers hide.</li><li><strong>Activity Monitor.</strong> Shows memory, but doesn’t show which port a process listens on unless you open it and read its Open Files and Ports tab, and has no idea which project a node belongs to.</li><li><strong>CLI killers like </strong>npx kill-port<strong> or </strong>fkill<strong>.</strong> Fast when you already know the port. They show a process name, not the project it belongs to, and they don&#39;t look for orphans.</li><li><strong>LeftOpen.</strong> The closest one, and a good open-source app: it lists TCP listeners by project, can hide ports, and warns you when a brew services job will come back. It doesn&#39;t show the git branch, and since it only sees TCP listeners, the portless MCP and test-runner orphans never show up. It has no global shortcut either.</li></ul><p>What PortReaper adds is the context and the safety:</p><ol><li><strong>It names the project and branch</strong>, so with three worktrees running I kill the right one.</li><li><strong>It finds what holds no port:</strong> the MCP and test-runner orphans agents leave behind.</li><li><strong>It’s built to be trusted with </strong>kill<strong>.</strong> It never signals PID 0, PID 1 or itself. Databases, Docker and system daemons ask a second time. A Docker-published port shows the container, and Kill runs docker stop on it instead of taking Docker Desktop down. Every kill is logged and can be relaunched. And it knows about launchd: kill an ollama that runs under brew services and launchd starts it again about ten seconds later, so a brew services job is never flagged as a zombie, and a kill that launchd would undo asks first and offers brew services stop instead.</li><li><strong>It’s one keystroke from anywhere</strong>, not a terminal command or a window you have to find.</li></ol><h3>A Rust core, a Vue window, and nothing leaving your Mac</h3><p>PortReaper is a Tauri 2 app: a Rust core and a Vue 3 window.</p><p>I picked Tauri for one reason: size. A tool that sits in your menu bar all day shouldn’t be heavier than the dev servers it’s cleaning up after. An Electron app ships its own copy of Chromium, so even a small one is usually well over 100 MB. Tauri uses the WebKit that macOS already has, and the whole universal build, for Apple Silicon and Intel, is a 7.7 MB download.</p><p>The core reads listening sockets and process details (pid, command line, working directory, user, memory, parent), walks up from each working directory to find the project manifest and .git/HEAD, and classifies each port by its number and command line. The window, the ⌘⇧K strip and the menu bar all talk to the same core, so they share one history.</p><p>A few choices I care about:</p><ul><li><strong>Nothing leaves the machine.</strong> No analytics, no crash reporting. The only network request is the update check: one GET of a file on GitHub Releases that carries nothing about you.</li><li><strong>No sudo, no privileged helper.</strong> A dev server is your own process, so your own user can see it and stop it.</li><li><strong>Signed and verified.</strong> Developer ID signed, notarized by Apple, one universal build for Apple Silicon and Intel. Updates are signed and checked against a key built into the app before anything installs.</li><li><strong>Open source, MIT.</strong></li></ul><h3>What it doesn’t do (yet)</h3><ul><li>It’s macOS only.</li><li>It can’t stop other users’ processes. That’s on purpose, since there’s no sudo and no privileged helper.</li><li>Orphan detection works from a list of known process names. If an agent leaves something it doesn’t recognize, it won’t flag it until that name is added, which is why issues with process names help.</li></ul><h3>Why I keep it open all day</h3><p>It replaced a habit. Before a session I glance at the port count in the menu bar; this morning it said 58, on a Mac where I’d have guessed ten. After closing a few agent sessions I open the Zombies filter and reap whatever they left, and the RAM column tells me what I’m getting back. When something grabs 3000, ⌘⇧K and it’s gone before I’ve finished being annoyed. And because it shows the branch, I’ve stopped killing the dev server of the worktree I was actually working in.</p><p>PortReaper removes one bit of friction I used to hit many times a day, and that turned out to matter more than I expected once agents started multiplying the processes on my machine.</p><h3>FAQ</h3><h3>How do I see what’s using port 3000 on a Mac?</h3><p>In the terminal, lsof -nP -iTCP:3000 -sTCP:LISTEN shows the PID listening on the port, and kill &lt;pid&gt; stops it. PortReaper shows the same thing with the project and git branch next to it, and frees the port with ⌘⇧K.</p><h3>Why are node processes still running after I close Claude Code?</h3><p>When the terminal or agent session that started a helper (an MCP server, a test runner, a dev server) goes away, macOS re-parents the helper to launchd, PID 1, and it keeps running. ps -axo pid,ppid,rss,command lists them with their parent PID; PortReaper flags the ones it recognizes as zombies and shows the RAM each one holds.</p><h3>Try it</h3><p>Everything in one place: <a href="https://amit-gal.dev/portreaper">amit-gal.dev/portreaper</a></p><p>With Homebrew:</p><pre>brew install --cask amitgal45/tap/portreaper</pre><p>Or download the .dmg from the <a href="https://github.com/amitgal45/portreaper/releases/latest">latest release on GitHub</a>.</p><p>The code is at <a href="https://github.com/amitgal45/portreaper">github.com/amitgal45/portreaper</a>. If it saves you one lsof today, a star on the repo helps a lot. And if you hit a zombie it doesn&#39;t catch yet, open an issue with the process name. That list grows from real cases.</p><p><em>I’m Amit Gal, a full-stack developer who builds websites, apps and the tools I wish I had. More of my work is at </em><a href="https://amit-gal.dev/"><em>amit-gal.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5036455c8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Email System Design: A Professional Guide to SendGrid and Mailgun (Part 1)]]></title>
            <link>https://medium.com/@amitgal45/nestjs-email-system-design-a-professional-guide-to-sendgrid-and-mailgun-part-1-e6a7da661473?source=rss-492b643c087e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a7da661473</guid>
            <category><![CDATA[sendgrid]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Amit Gal]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 18:12:05 GMT</pubDate>
            <atom:updated>2024-10-28T18:15:02.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Td_Vrv3IipcLcTprQmKBrw.png" /><figcaption>NestJS Email System Design: A Professional Guide to SendGrid and Mailgun (Part 1)</figcaption></figure><p>As a senior full-stack developer with five years of experience, I’ve encountered numerous challenges in managing complex email systems. This series stems from my firsthand experience and the critical need to share the importance of SOLID principles in software architecture.</p><p>Throughout my career, I’ve observed how seemingly simple email features can quickly evolve into intricate systems, often resulting in maintenance nightmares. This realization prompted me to create this comprehensive guide, focusing on the practical implementation of SOLID principles in NestJS for building robust, scalable email systems.</p><p>This two-part series aims to bridge the gap between theoretical knowledge of SOLID principles and their real-world application. Part 1 will lay the groundwork and explore core concepts, while Part 2 will delve into specific implementation details. By sharing these insights, I hope to equip fellow developers with the tools to create more maintainable and flexible email systems in their projects.</p><h3>The Progression of Email Functionality</h3><p>Consider this scenario: Your startup has just released its Minimum Viable Product (MVP). You implement a basic password reset feature using SendGrid’s SDK. Initially, this seems straightforward. However, as marketing requests welcome emails and other departments add their requirements, you soon find yourself managing:</p><ul><li>Order confirmations</li><li>Shipping updates</li><li>Marketing campaigns</li><li>Newsletter subscriptions</li><li>User activity notifications</li></ul><p>As a result, email-sending logic becomes dispersed throughout your codebase, tightly coupled to your email provider. Individual services directly import SendGrid’s SDK, manage their own templates, and handle errors inconsistently. While this approach may appear practical at first, it can lead to complications in the future.</p><h3>Practical Implications</h3><p>Consider these common scenarios:</p><ol><li><strong>Provider Outages</strong>: In the event of an email provider outage, how rapidly can you transition to a backup solution?</li><li><strong>Cost Optimization</strong>: If you identify a more cost-effective provider, how long would the migration process take?</li><li><strong>A/B Testing</strong>: When marketing needs to test different email templates, how many files require modification?</li><li><strong>Delivery Tracking</strong>: If you need to implement email delivery tracking, where would you incorporate this functionality?</li></ol><p>Without a well-structured architecture, addressing each of these scenarios necessitates changes across multiple files, increasing the potential for errors and complicating the testing process.</p><h3>Applying SOLID Principles to Email Systems</h3><p>Let’s examine how each SOLID principle influences our email architecture:</p><h3>Single Responsibility Principle: “One Purpose, One Component”</h3><p>The Single Responsibility Principle (SRP) dictates that each class should have only one reason to change. In our email system, this principle is demonstrated through:</p><ol><li><strong>Email Provider</strong>: Dedicated solely to sending emails</li></ol><pre>interface IEmailProvider {<br>  sendEmail(to: string, subject: string, content: string): Promise&lt;EmailResponse&gt;;<br>}<br><br>@Injectable()<br>class SendGridProvider implements IEmailProvider {<br>  constructor(<br>    private readonly apiKey: string,<br>    private readonly fromEmail: string<br>  ) {<br>    SendGrid.setApiKey(this.apiKey);<br>  }<br>  async sendEmail(to: string, subject: string, content: string): Promise&lt;EmailResponse&gt; {<br>    try {<br>      const [response] = await SendGrid.send({<br>        to,<br>        from: this.fromEmail,<br>        subject,<br>        html: content<br>      });<br>      return {<br>        success: true,<br>        messageId: response.headers[&#39;x-message-id&#39;]<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        error: error.message<br>      };<br>    }<br>  }<br>}</pre><ol><li><strong>Template Engine</strong>: Focused exclusively on template rendering</li></ol><pre>interface ITemplateEngine {<br>  render(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt;;<br>  renderSubject(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt;;<br>}<br><br>@Injectable()<br>class LiquidTemplateEngine implements ITemplateEngine {<br>  private readonly engine: Liquid;<br>  constructor() {<br>    this.engine = new Liquid({<br>      strictVariables: true,<br>      strictFilters: true,<br>    });<br>  }<br>  async render(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt; {<br>    return this.engine.parseAndRender(template, data);<br>  }<br>  async renderSubject(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt; {<br>    return this.render(template, data);<br>  }<br>}</pre><ol><li><strong>Template Repository</strong>: Devoted to template storage</li></ol><pre>@Entity()<br>export class EmailTemplate {<br>  @PrimaryColumn()<br>  id: string;<br>  @Column()<br>  subject: string;<br>  @Column(&#39;text&#39;)<br>  content: string;<br>  @Column(&#39;jsonb&#39;, { nullable: true })<br>  metadata?: Record&lt;string, any&gt;;<br>}<br><br><br>@Injectable()<br>export class EmailTemplateRepository implements ITemplateRepository {<br>  constructor(<br>    @InjectRepository(EmailTemplate)<br>    private readonly repository: Repository&lt;EmailTemplate&gt;<br>  ) {}<br>  async findById(id: string): Promise&lt;EmailTemplate&gt; {<br>    const template = await this.repository.findOne({ where: { id } });<br>    if (!template) throw new NotFoundException(`Template ${id} not found`);<br>    return template;<br>  }<br>}</pre><h3>Open/Closed Principle: “Open for Extension, Closed for Modification”</h3><p>The Open/Closed Principle (OCP) suggests that software entities should be open for extension but closed for modification. Our email system exemplifies this through:</p><ol><li><strong>Provider Extensions</strong></li></ol><pre>// Base provider capabilities<br>interface IEmailProvider {<br>  sendEmail(to: string, subject: string, content: string): Promise&lt;EmailResponse&gt;;<br>}<br><br>// SendGrid implementation<br>@Injectable()<br>export class SendGridProvider implements IEmailProvider {<br>  // Implementation as shown above<br>}<br>// Mailgun implementation - no changes to existing code<br>@Injectable()<br>export class MailgunProvider implements IEmailProvider {<br>  constructor(<br>    private readonly apiKey: string,<br>    private readonly fromEmail: string<br>  ) {}<br>  async sendEmail(to: string, subject: string, content: string): Promise&lt;EmailResponse&gt; {<br>    // Mailgun-specific implementation<br>  }<br>}</pre><ol><li><strong>Template Engine Flexibility</strong></li></ol><pre>@Injectable()<br>class HandlebarsTemplateEngine implements ITemplateEngine {<br>  async render(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt; {<br>    return Handlebars.compile(template)(data);<br>  }<br>  async renderSubject(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt; {<br>    return this.render(template, data);<br>  }<br>}</pre><h3>Liskov Substitution Principle: “Interchangeable Parts”</h3><p>The Liskov Substitution Principle (LSP) states that objects should be replaceable with their subtypes without affecting program correctness. In our system, this is demonstrated by:</p><pre>@Injectable()<br>export class EmailService {<br>  constructor(<br>    @Inject(INJECTION_TOKENS.EMAIL_PROVIDER)<br>    private readonly emailProvider: IEmailProvider,<br>    @Inject(INJECTION_TOKENS.TEMPLATE_ENGINE)<br>    private readonly templateEngine: ITemplateEngine,<br>    @Inject(INJECTION_TOKENS.TEMPLATE_REPOSITORY)<br>    private readonly templateRepository: ITemplateRepository,<br>  ) {}<br>  async sendTemplatedEmail(emailData: EmailData): Promise&lt;EmailResponse&gt; {<br>    const template = await this.templateRepository.findById(emailData.templateId);<br>    const [renderedSubject, renderedContent] = await Promise.all([<br>      this.templateEngine.renderSubject(template.subject, emailData.templateData),<br>      this.templateEngine.render(template.content, emailData.templateData)<br>    ]);<br>    return this.emailProvider.sendEmail(<br>      emailData.to,<br>      renderedSubject,<br>      renderedContent<br>    );<br>  }<br>}</pre><p>This service is compatible with any implementation of our interfaces, illustrating the LSP in practice.</p><h3>Interface Segregation Principle: “Focused Interfaces”</h3><p>The Interface Segregation Principle (ISP) proposes that clients should not be forced to depend on interfaces they do not use. Our system demonstrates this through targeted interfaces:</p><pre>// Core email functionality<br>interface IEmailProvider {<br>  sendEmail(to: string, subject: string, content: string): Promise&lt;EmailResponse&gt;;<br>}<br>// Template handling<br>interface ITemplateEngine {<br>  render(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt;;<br>  renderSubject(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt;;<br>}<br>// Template storage<br>interface ITemplateRepository {<br>  findById(id: string): Promise&lt;EmailTemplate&gt;;<br>}</pre><h3>Dependency Inversion Principle: “Depend on Abstractions”</h3><p>The Dependency Inversion Principle (DIP) requires high-level modules to depend on abstractions rather than concrete implementations. Our module configuration illustrates this:</p><pre>@Module({})<br>export class EmailModule {<br>  static forRoot(): DynamicModule {<br>    return {<br>      module: EmailModule,<br>      imports: [TypeOrmModule.forFeature([EmailTemplate])],<br>      providers: [<br>        {<br>          provide: INJECTION_TOKENS.EMAIL_PROVIDER,<br>          useFactory: (configService: ConfigService) =&gt; {<br>            const provider = configService.get(&#39;EMAIL_PROVIDER&#39;);<br>            const apiKey = configService.get(<br>              provider === &#39;sendgrid&#39; ? &#39;SENDGRID_API_KEY&#39; : &#39;MAILGUN_API_KEY&#39;<br>            );<br>            const fromEmail = configService.get(<br>              provider === &#39;sendgrid&#39; ? &#39;SENDGRID_FROM_EMAIL&#39; : &#39;MAILGUN_FROM_EMAIL&#39;<br>            );<br>      return provider === &#39;sendgrid&#39;<br>              ? new SendGridProvider(apiKey, fromEmail)<br>              : new MailgunProvider(apiKey, fromEmail);<br>          },<br>          inject: [ConfigService],<br>        },<br>        {<br>          provide: INJECTION_TOKENS.TEMPLATE_ENGINE,<br>          useClass: LiquidTemplateEngine,<br>        },<br>        EmailTemplateRepository,<br>        {<br>          provide: INJECTION_TOKENS.TEMPLATE_REPOSITORY,<br>          useExisting: EmailTemplateRepository,<br>        },<br>        EmailService,<br>      ],<br>      exports: [EmailService],<br>    };<br>  }<br>}</pre><h3>Practical Advantages of SOLID in Our Email System</h3><p>This architecture offers several immediate benefits:</p><ol><li><strong>Simplified Testing</strong></li></ol><pre>// Test provider for development<br>class TestEmailProvider implements IEmailProvider {<br>  async sendEmail(to: string, subject: string, content: string): Promise&lt;EmailResponse&gt; {<br>    console.log(`Email to ${to}: ${subject}`);<br>    return { success: true, messageId: &#39;test-123&#39; };<br>  }<br>}</pre><ol><li><strong>Effortless Provider Switching</strong></li></ol><pre>// In your configuration<br>EMAIL_PROVIDER=sendgrid<br>// or<br>EMAIL_PROVIDER=mailgun</pre><ol><li><strong>Streamlined Business Logic</strong></li></ol><pre>@Injectable()<br>export class UserService {<br>  constructor(private readonly emailService: EmailService) {}<br>  async sendWelcomeEmail(user: User) {<br>    await this.emailService.sendTemplatedEmail({<br>      to: user.email,<br>      templateId: &#39;welcome-email&#39;,<br>      templateData: { name: user.firstName }<br>    });<br>  }<br>}</pre><h3>Forthcoming in Part 2</h3><p>In the subsequent article, we will explore the implementation details in depth:</p><ul><li>Developing provider implementations (SendGrid, Mailgun)</li><li>Constructing a robust template engine</li><li>Configuring dependency injection</li><li>Managing errors and implementing retry mechanisms</li><li>Implementing the comprehensive email module</li><li>Exploring testing strategies and best practices</li></ul><p>We look forward to presenting this information in the next installment.</p><p>Ready to implement this architecture? Continue with <a href="https://medium.com/@amitgal45/building-a-scalable-email-architecture-with-nestjs-sendgrid-and-mailgun-part-2-4beae52b46c3">Building a Scalable Email Architecture with NestJS, SendGrid and Mailgun (Part 2)</a>, where we’ll build the complete system step by step. The full source code is available in our <a href="https://github.com/amitgal45/sendgrid-mailgun-nestjs-solid">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a7da661473" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS Email System Design: A Professional Guide to SendGrid and Mailgun (Part 2)]]></title>
            <link>https://medium.com/@amitgal45/building-a-scalable-email-architecture-with-nestjs-sendgrid-and-mailgun-part-2-4beae52b46c3?source=rss-492b643c087e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4beae52b46c3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Amit Gal]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 18:10:36 GMT</pubDate>
            <atom:updated>2024-10-28T19:51:33.384Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Td_Vrv3IipcLcTprQmKBrw.png" /><figcaption>Building a Scalable Email Architecture with NestJS, SendGrid and Mailgun (Part 2)</figcaption></figure><p>In <a href="https://medium.com/@amitgal45/nestjs-email-system-design-a-professional-guide-to-sendgrid-and-mailgun-part-1-e6a7da661473">Building a Scalable Email Architecture with NestJS, SendGrid and Mailgun (Part 1)</a>, we meticulously crafted a SOLID email architecture tailored for NestJS applications. Now, we’ll dive deep into the implementation phase, bringing each component to life while adhering to our carefully designed structure. This hands-on approach will demonstrate how our architectural decisions translate into clean, maintainable code.</p><h3>Project Setup and Dependencies</h3><p>To kick off our implementation, we’ll start by installing the necessary dependencies. These libraries will form the backbone of our email system, providing essential functionality for database interactions, email sending, and templating:</p><pre>npm install @nestjs/typeorm typeorm pg @sendgrid/mail mailgun.js liquidjs</pre><p>With our dependencies in place, let’s outline the structure of our implementation. This organization reflects the separation of concerns we established in our architecture:</p><pre>src/email/<br>├── constants/<br>│   └── injection-tokens.ts<br>├── entities/<br>│   └── email-template.entity.ts<br>├── interfaces/<br>│   ├── email-provider.interface.ts<br>│   ├── template-engine.interface.ts<br>│   └── template-repository.interface.ts<br>├── providers/<br>│   ├── sendgrid.provider.ts<br>│   └── mailgun.provider.ts<br>├── engines/<br>│   └── liquid-template.engine.ts<br>├── repositories/<br>│   └── email-template.repository.ts<br>├── services/<br>│   └── email.service.ts<br>└── email.module.ts</pre><h3>1. Establishing the Core: Constants and Interfaces</h3><p>We’ll begin by defining our injection tokens and interfaces. These form the foundation of our dependency injection system and establish clear contracts for our components:</p><pre>// constants/injection-tokens.ts<br>export const INJECTION_TOKENS = {<br>  EMAIL_PROVIDER: &#39;EMAIL_PROVIDER&#39;,<br>  TEMPLATE_ENGINE: &#39;TEMPLATE_ENGINE&#39;,<br>  TEMPLATE_REPOSITORY: &#39;TEMPLATE_REPOSITORY&#39;,<br>} as const;<br><br>export type InjectionTokens =<br>  (typeof INJECTION_TOKENS)[keyof typeof INJECTION_TOKENS];<br><br>// interfaces/email-provider.interface.ts<br>export interface EmailResponse {<br>  success: boolean;<br>  messageId?: string;<br>  error?: string;<br>}<br>export interface IEmailProvider {<br>  sendEmail(<br>    to: string,<br>    subject: string,<br>    content: string,<br>  ): Promise&lt;EmailResponse&gt;;<br>}<br><br>// interfaces/template-engine.interface.ts<br>export interface ITemplateEngine {<br>  render(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt;;<br>  renderSubject(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt;;<br>}<br><br>// interfaces/template-repository.interface.ts<br>export interface ITemplateRepository {<br>  findById(id: string): Promise&amp;lt;EmailTemplate&amp;gt;;<br>}</pre><h3>2. Defining the Email Template Entity</h3><p>Next, we’ll create our EmailTemplate entity, which will represent our email templates in the database:</p><pre>// entities/email-template.entity.ts<br>import { Entity, PrimaryColumn, Column } from &#39;typeorm&#39;;<br><br>@Entity()<br>export class EmailTemplate {<br>  @PrimaryColumn()<br>  id: string;<br>  @Column()<br>  subject: string;<br>  @Column(&#39;text&#39;)<br>  content: string;<br>  @Column(&#39;jsonb&#39;, { nullable: true })<br>  metadata?: Record&lt;string, any&gt;;<br>}</pre><h3>3. Implementing Email Providers</h3><p>Now, let’s implement our email providers for SendGrid and Mailgun. These classes will encapsulate the logic for sending emails through their respective services:</p><pre>// email/providers/sendgrid.provider.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import * as SendGrid from &#39;@sendgrid/mail&#39;;<br>import {<br>  IEmailProvider,<br>  EmailResponse,<br>} from &#39;../interfaces/email-provider.interface&#39;;<br><br>@Injectable()<br>export class SendGridProvider implements IEmailProvider {<br>  constructor(<br>    private readonly apiKey: string,<br>    private readonly fromEmail: string,<br>  ) {<br>    SendGrid.setApiKey(this.apiKey);<br>  }<br>  async sendEmail(<br>    to: string,<br>    subject: string,<br>    content: string,<br>  ): Promise&lt;EmailResponse&gt; {<br>    try {<br>      const [response] = await SendGrid.send({<br>        to,<br>        from: this.fromEmail,<br>        subject,<br>        html: content,<br>      });<br>      return {<br>        success: true,<br>        messageId: response.headers[&#39;x-message-id&#39;],<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        error: error.message,<br>      };<br>    }<br>  }<br>}</pre><pre>// email/providers/mailgun.provider.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import {<br>  EmailResponse,<br>  IEmailProvider,<br>} from &#39;../interfaces/email-provider.interface&#39;;<br>import Mailgun from &#39;mailgun.js&#39;;<br><br>@Injectable()<br>export class MailgunProvider implements IEmailProvider {<br>  private mailgun;<br>  constructor(<br>    private readonly apiKey: string,<br>    private readonly domain: string,<br>    private readonly fromEmail: string,<br>  ) {<br>    const mailgun = new Mailgun(FormData);<br>    this.mailgun = mailgun.client({ username: &#39;api&#39;, key: this.apiKey });<br>  }<br>  async sendEmail(<br>    to: string,<br>    subject: string,<br>    content: string,<br>  ): Promise&lt;EmailResponse&gt; {<br>    try {<br>      const response = await this.mailgun.messages.create(this.domain, {<br>        from: this.fromEmail,<br>        to,<br>        subject,<br>        html: content,<br>      });<br>      return {<br>        success: true,<br>        messageId: response.id,<br>      };<br>    } catch (error) {<br>      return {<br>        success: false,<br>        error: error.message,<br>      };<br>    }<br>  }<br>}</pre><h3>4. Creating the Template Engine</h3><p>Our template engine will be responsible for rendering email templates. We’ll use the Liquid templating language for this purpose:</p><pre>// email/engines/liquid-template.engine.ts<br><br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { Liquid } from &#39;liquidjs&#39;;<br>import { ITemplateEngine } from &#39;../interfaces/template-engine.interface&#39;;<br><br>@Injectable()<br>export class LiquidTemplateEngine implements ITemplateEngine {<br>  private readonly engine: Liquid;<br>  constructor() {<br>    this.engine = new Liquid({<br>      strictVariables: true,<br>      strictFilters: true,<br>      cache: true,<br>    });<br>  }<br>  async render(template: string, data: Record&lt;string, any&gt;): Promise&lt;string&gt; {<br>    try {<br>      return await this.engine.parseAndRender(template, data);<br>    } catch (error) {<br>      throw new Error(`Template rendering failed: ${error.message}`);<br>    }<br>  }<br>  async renderSubject(<br>    template: string,<br>    data: Record&lt;string, any&gt;,<br>  ): Promise&lt;string&gt; {<br>    return this.render(template, data);<br>  }<br>}</pre><h3>5. Implementing the Template Repository</h3><p>The template repository will handle database operations for our email templates:</p><pre>// email/repositories/email-template.repository.ts<br><br>import { Injectable, NotFoundException } from &#39;@nestjs/common&#39;;<br>import { ITemplateRepository } from &#39;../interfaces/template-repository.interface&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { EmailTemplate } from &#39;../entities/template-email.entity&#39;;<br><br>@Injectable()<br>export class EmailTemplateRepository implements ITemplateRepository {<br>  constructor(<br>    @InjectRepository(EmailTemplate)<br>    private readonly repository: Repository&lt;EmailTemplate&gt;,<br>  ) {}<br>  async findById(id: string): Promise&lt;EmailTemplate&gt; {<br>    const template = await this.repository.findOne({ where: { id } });<br>    if (!template) {<br>      throw new NotFoundException(`Template ${id} not found`);<br>    }<br>    return template;<br>  }<br>}</pre><h3>6. Building the Email Service</h3><p>Our email service will tie everything together, orchestrating the process of fetching templates, rendering them, and sending emails:</p><pre>// email/email.service.ts<br><br>import { Injectable, Inject } from &#39;@nestjs/common&#39;;<br>import { INJECTION_TOKENS } from &#39;./constant/injection-tokens&#39;;<br>import { ITemplateEngine } from &#39;./interfaces/template-engine.interface&#39;;<br>import { ITemplateRepository } from &#39;./interfaces/template-repository.interface&#39;;<br>import {<br>  EmailResponse,<br>  IEmailProvider,<br>} from &#39;./interfaces/email-provider.interface&#39;;<br><br>export interface EmailData {<br>  to: string;<br>  templateId: string;<br>  templateData: Record&lt;string, any&gt;;<br>}<br><br>@Injectable()<br>export class EmailService {<br>  constructor(<br>    @Inject(INJECTION_TOKENS.EMAIL_PROVIDER)<br>    private readonly emailProvider: IEmailProvider,<br>    @Inject(INJECTION_TOKENS.TEMPLATE_ENGINE)<br>    private readonly templateEngine: ITemplateEngine,<br>    @Inject(INJECTION_TOKENS.TEMPLATE_REPOSITORY)<br>    private readonly templateRepository: ITemplateRepository,<br>  ) {}<br><br>  async sendTemplatedEmail(emailData: EmailData): Promise&lt;EmailResponse&gt; {<br>    try {<br>      const template = await this.templateRepository.findById(<br>        emailData.templateId,<br>      );<br>      const [renderedSubject, renderedContent] = await Promise.all([<br>        this.templateEngine.renderSubject(<br>          template.subject,<br>          emailData.templateData,<br>        ),<br>        this.templateEngine.render(template.content, emailData.templateData),<br>      ]);<br>      return await this.emailProvider.sendEmail(<br>        emailData.to,<br>        renderedSubject,<br>        renderedContent,<br>      );<br>    } catch (error) {<br>      return {<br>        success: false,<br>        error: error.message,<br>      };<br>    }<br>  }<br>}</pre><h3>7. Configuring the Email Module</h3><p>Finally, we’ll create our EmailModule, which will tie all of our components together and make them available to the rest of our application:</p><pre>// email/email.module.ts<br>import { DynamicModule, Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { EmailTemplate } from &#39;./entities/template-email.entity&#39;;<br>import { INJECTION_TOKENS } from &#39;./constant/injection-tokens&#39;;<br>import { EmailService } from &#39;./email.service&#39;;<br>import { EmailTemplateRepository } from &#39;./repositories/email-template.repostory&#39;;<br>import { LiquidTemplateEngine } from &#39;./engines/liquid-template.engine&#39;;<br>import { SendGridProvider } from &#39;./providers/sendgrid.provider&#39;;<br>import { MailgunProvider } from &#39;./providers/mailgun.provider&#39;;<br>import { ConfigService } from &#39;@nestjs/config&#39;;<br><br>@Module({})<br>export class EmailModule {<br>  static forRoot(): DynamicModule {<br>    return {<br>      module: EmailModule,<br>      imports: [TypeOrmModule.forFeature([EmailTemplate])],<br>      providers: [<br>        {<br>          provide: INJECTION_TOKENS.EMAIL_PROVIDER,<br>          useFactory: (configService: ConfigService) =&gt; {<br>            const provider = configService.get(&#39;EMAIL_PROVIDER&#39;);<br>            const apiKey = configService.get(<br>              provider === &#39;sendgrid&#39; ? &#39;SENDGRID_API_KEY&#39; : &#39;MAILGUN_API_KEY&#39;,<br>            );<br>            const fromEmail = configService.get(&#39;EMAIL_FROM_ADDRESS&#39;);<br>            const domain =<br>              provider === &#39;mailgun&#39;<br>                ? configService.get(&#39;MAILGUN_DOMAIN&#39;)<br>                : undefined;<br>            return provider === &#39;sendgrid&#39;<br>              ? new SendGridProvider(apiKey, fromEmail)<br>              : new MailgunProvider(apiKey, domain, fromEmail);<br>          },<br>          inject: [ConfigService],<br>        },<br>        {<br>          provide: INJECTION_TOKENS.TEMPLATE_ENGINE,<br>          useClass: LiquidTemplateEngine,<br>        },<br>        EmailTemplateRepository,<br>        {<br>          provide: INJECTION_TOKENS.TEMPLATE_REPOSITORY,<br>          useExisting: EmailTemplateRepository,<br>        },<br>        EmailService,<br>      ],<br>      exports: [EmailService],<br>    };<br>  }<br>}</pre><h3>8. Integrating the Email Module</h3><p>To use our newly created email system in your application, you’ll need to import the EmailModule and inject the EmailService where needed:</p><pre>// app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { ConfigModule } from &#39;@nestjs/config&#39;;<br>import { EmailModule } from &#39;./email/email.module&#39;;<br>import { DbModule } from &#39;./db/db.module&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>      envFilePath: [&#39;.env&#39;, &#39;.env.development&#39;],<br>    }),<br>    DbModule,<br>    EmailModule.forRoot(),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><pre>// Example usage in a service<br>@Injectable()<br>export class UserService {<br>  constructor(private readonly emailService: EmailService) {}<br>  async createUser(userData: CreateUserDto) {<br>    // Create user logic...<br>    await this.emailService.sendTemplatedEmail({<br>      to: userData.email,<br>      templateId: &#39;welcome-email&#39;,<br>      templateData: {<br>        name: userData.firstName,<br>        activationLink: `${process.env.FRONTEND_URL}/activate/${activationToken}`<br>      }<br>    });<br>  }<br>}</pre><h3>Configuration Setup</h3><p>To complete our setup, we need to create a .env file with the necessary configuration:</p><pre># Email Provider Configuration<br>EMAIL_PROVIDER=sendgrid  # or &#39;mailgun&#39;<br>EMAIL_FROM_ADDRESS=noreply@yourdomain.com<br># SendGrid Configuration<br>SENDGRID_API_KEY=your_sendgrid_api_key<br># Mailgun Configuration<br>MAILGUN_API_KEY=your_mailgun_api_key<br>MAILGUN_DOMAIN=your_mailgun_domain</pre><p>Lastly, we’ll create our email template in the database:</p><pre>INSERT INTO email_template (id, subject, content)<br>VALUES (<br>  &#39;welcome-email&#39;,<br>  &#39;Welcome to {{ appName }}, {{ name }}!&#39;,<br>  &#39;&lt;div&gt;<br>    &lt;h1&gt;Welcome aboard, {{ name }}!&lt;/h1&gt;<br>    &lt;p&gt;We&#39;re excited to have you join us. Click below to get started:&lt;/p&gt;<br>    &lt;a href=&quot;{{ activationLink }}&quot;&gt;Activate Your Account&lt;/a&gt;<br>  &lt;/div&gt;&#39;<br>);</pre><h3>Conclusion: A Robust Email System</h3><p>Throughout this two-part series, we’ve tackled the complex challenge of email handling in web applications, transforming it into a robust, maintainable system. Let’s recap our journey and the key achievements:</p><p>In Part 1, we laid the groundwork by:</p><ul><li>Identifying and analyzing common email system challenges</li><li>Designing a SOLID architecture to address these challenges</li><li>Creating clear interface boundaries to ensure modularity</li><li>Establishing patterns for provider independence, allowing easy switching between email services</li></ul><p>In Part 2, we brought our design to life by:</p><ul><li>Implementing each component of the system, from providers to services</li><li>Setting up provider-specific adapters for SendGrid and Mailgun</li><li>Creating a flexible template engine using Liquid</li><li>Building a complete NestJS module that ties all components together</li></ul><p>The result of our efforts is a sophisticated email system that:</p><ul><li>Seamlessly switches between SendGrid and Mailgun without affecting the rest of the application</li><li>Manages email templates efficiently, allowing for easy customization and maintenance</li><li>Handles errors gracefully, providing clear feedback on the success or failure of email operations</li><li>Scales effortlessly with your application, thanks to its modular and extensible design</li></ul><p>This implementation serves as a prime example of how proper architecture and adherence to SOLID principles can transform a potentially complex and messy feature into a clean, maintainable system that’s not only ready for production use but also prepared for future enhancements and adaptations.</p><p>The complete code for this tutorial is available on <a href="https://github.com/amitgal45/sendgrid-mailgun-nestjs-solid">GitHub</a>. For more in-depth tutorials and professional insights on software architecture and development, visit my website at <a href="https://amit-gal.dev/">amit-gal.dev</a>. Feel free to reach out if you have any questions or need consulting on your email system implementation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4beae52b46c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nest JS — Open API Just saves so much time — Part 2]]></title>
            <link>https://medium.com/@amitgal45/nest-js-open-api-just-saves-so-much-time-part-2-6e64a76f2be7?source=rss-492b643c087e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e64a76f2be7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Amit Gal]]></dc:creator>
            <pubDate>Tue, 23 May 2023 16:55:19 GMT</pubDate>
            <atom:updated>2024-07-28T09:32:45.974Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Nest JS — Open API Just saves so much time — Part 2</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_YMwOoUC4OebYrhr-6zTg.png" /></figure><p>In the previous article, we discussed how OpenAPI helps us save time by generating API documentation based on our code.</p><p>Let’s quickly review a few properties we talked about in the last lecture:</p><p>The <strong>@ApiProperty</strong> decorator is used to add metadata to a property in a NestJS class that represents an API endpoint.</p><p>The <strong>@ApiResponseProperty</strong> decorator is used to add metadata to the response of an API endpoint.</p><p>NestJS uses the <strong>@ApiProperty</strong> decorator to describe the properties of the request or response DTO class, and the <strong>@ApiResponseProperty</strong> decorator to describe the response of the API endpoint.</p><p>In this article, we will take a deep dive into API error responses on Swagger and NestJS, and how we can create custom decorators.</p><p>Now, lets talk about <strong>Custom Decorators</strong> — Custom decorators are a powerful feature of NestJS that allow developers to extend or modify the behavior of built-in or third-party functionality. By creating custom decorators, developers can encapsulate complex logic and make it reusable across different parts of their application. Custom decorators also allow developers to add metadata and annotations to their code, which can be used by other modules and tools, such as Swagger, to generate documentation and provide insights into the structure and behavior of the application.</p><p>Usually, every API error caught should return the same type/schema for every request in the system. For example:</p><pre>{<br>  status_code:404,<br>  message:&#39;Not Found&#39;,<br>  date:&#39;&#39;<br>}</pre><p>The object contains status_code , message and the date.</p><p>First, let’s get to know the <strong>@ApiResponse</strong> decorator. It is provided by the @nestjs/swagger package and allows developers to define and document the expected responses of an API endpoint. By specifying the HTTP status code and the response payload schema, developers can provide clear and concise documentation about the expected behavior of the API.</p><p>It’s now time to build our new ErrorDTO file located at <strong>src/common/dto/error.dto.ts</strong>:</p><pre>// src/common/dto/error.dto.ts<br><br>import { HttpStatus } from &#39;@nestjs/common&#39;;<br>import { ApiProperty } from &#39;@nestjs/swagger&#39;;<br>export class ErrorDTO {<br>  @ApiProperty({ default: &#39;Internal Server Error&#39; })<br>  message: string;<br>  @ApiProperty({ enum: HttpStatus, default: HttpStatus.INTERNAL_SERVER_ERROR })<br>  status_code: HttpStatus;<br>  @ApiProperty({ default: new Date().toISOString() })<br>  date: Date;<br>}</pre><p>In our system, Error Scheme is a crucial object. It contains a message, status_code, and date with default values. This object is significant because it helps users quickly identify and understand errors that occur in the system. The error message is a brief description of the problem that occurred, while the status_code is a numerical code that indicates the type of error. The date indicates when the error occurred.</p><p>Now lets doc our first 2 Errors.</p><pre>// src/employee/employee.controller.ts<br><br>import { ErrorDTO } from &#39;src/common/dto/error.dto&#39;;<br>import { EmployeeDTO } from &#39;./dto&#39;;<br>import { EmployeeService } from &#39;./employee.service&#39;;<br>@Controller(&#39;employee&#39;)<br>@ApiTags(&#39;employee&#39;)<br>export class EmployeeController {<br>  constructor(private readonly employeeService: EmployeeService) {}<br>  @Post()<br>  @ApiOperation({<br>    summary: &#39;Create new Employee&#39;,<br>    description: &#39;Lorem ipsum ....&#39;,<br>  })<br>  @ApiResponse({<br>    status: 201,<br>    type: EmployeeDTO,<br>  })<br>  @ApiResponse({<br>    status: 500,<br>    type: ErrorDTO,<br>    description: &#39;Internal Server Error&#39;,<br>  })<br>  @ApiResponse({<br>    status: 404,<br>    type: ErrorDTO,<br>    description: &#39;Not Found&#39;,<br>  })<br>  createEmployee(@Body() employeeDto: EmployeeDTO) {<br>    return { ...employeeDto, id: Date.now() };<br>  }<br>}</pre><p>Now our Swagger Doc should look like:</p><figure><img alt="https://cdn-images-1.medium.com/max/800/1*Sfxah_ZTzd8HW87wcwf01A.png" src="https://cdn-images-1.medium.com/proxy/1*Sfxah_ZTzd8HW87wcwf01A.png" /></figure><p>As we can see, two error responses have been added to our CreateEmployee API request. “Not found” returns a 404 error, and “Internal server error” returns a 500 error. However, there is still one thing that is not working correctly: the values of the ErrorDTO are not changing. Does this mean that we need to make a class for each individual ErrorDTO? No. We can resolve this issue by using our first custom decorator: the ApiErrorDecorator. This decorator will help us add the response metadata and keep our language consistent, while also saving time by using one common language.</p><p>Lets create a new file at <strong>src/common/decorator/error/error.decorator.ts</strong></p><pre>// src/common/decorator/error/error.decorator.ts<br><br>import { applyDecorators, HttpStatus } from &#39;@nestjs/common&#39;;<br>import {<br>  ApiResponse,<br>  ApiResponseOptions,<br>  getSchemaPath,<br>} from &#39;@nestjs/swagger&#39;;<br>import { ErrorDTO } from &#39;src/common/dto/error.dto&#39;;<br>export function ApiErrorDecorator(<br>  statusCode: HttpStatus,<br>  message: string,<br>  description?: string,<br>  options?: ApiResponseOptions,<br>) {<br>  return applyDecorators(<br>    ApiResponse({<br>      ...options,<br>      status: statusCode,<br>      description: description,<br>      schema: {<br>        default: {<br>          message: message,<br>          status_code: statusCode,<br>          date: new Date().toISOString(),<br>        },<br>        type: getSchemaPath(ErrorDTO),<br>      },<br>    }),<br>  );<br>}</pre><p>ApiErrorDecorator is a function that receives the status, message, description, and options parameters, and passes them to a new custom decorator based on the API response.</p><p>The magic happens when using the Schema with getSchemaPath to build the Schema DTO and inject the message and status_code through the custom decorator.</p><p>Now, let’s replace the ApiResponses with our new decorator on the EmployeeController!</p><pre>// src/employee/employee.controller.ts<br><br>import { Body, Controller, HttpStatus, Post } from &#39;@nestjs/common&#39;;<br>import { ApiOperation, ApiResponse, ApiTags } from &#39;@nestjs/swagger&#39;;<br>import { ApiErrorDecorator } from &#39;src/common/decorators/error/error.decorator&#39;;<br>import { EmployeeDTO } from &#39;./dto&#39;;<br>import { EmployeeService } from &#39;./employee.service&#39;;<br>@Controller(&#39;employee&#39;)<br>@ApiTags(&#39;employee&#39;)<br>export class EmployeeController {<br>  constructor(private readonly employeeService: EmployeeService) {}<br>  @Post()<br>  @ApiOperation({<br>    summary: &#39;Create new Employee&#39;,<br>    description: &#39;Lorem ipsum ....&#39;,<br>  })<br>  @ApiResponse({<br>    status: 201,<br>    type: EmployeeDTO,<br>  })<br>  @ApiErrorDecorator(HttpStatus.BAD_REQUEST, &#39;Bad Request&#39;)<br>  @ApiErrorDecorator(HttpStatus.INTERNAL_SERVER_ERROR, &#39;Internal Server&#39;)<br>  createEmployee(@Body() employeeDto: EmployeeDTO) {<br>    return { ...employeeDto, id: Date.now() };<br>  }<br>}</pre><p>Our Api Docs should look like:</p><figure><img alt="https://cdn-images-1.medium.com/max/800/1*D29NJ3wUoaoK7x7JjKWmGQ.png" src="https://cdn-images-1.medium.com/proxy/1*D29NJ3wUoaoK7x7JjKWmGQ.png" /></figure><p>And as we can see, it works. We are able to inject our message and status code directly from our controller.</p><p>Another tip that I can suggest is to create additional decorators based on the ApiErrorDecorator. For example, you could create a BadRequest Decorator to handle cases where a requested resource is bad requested.</p><p>Lets Add a new file at <strong>src/decorators/error/index.ts</strong> to add Few Errors.</p><pre>// src/decorators/error/index.ts<br><br>import { HttpStatus } from &#39;@nestjs/common&#39;;<br>import { ApiResponseOptions } from &#39;@nestjs/swagger&#39;;<br>import { ApiErrorDecorator } from &#39;./error.decorator&#39;;<br>export function BadRequest(<br>  message: string,<br>  description?: string,<br>  options?: ApiResponseOptions,<br>) {<br>  return ApiErrorDecorator(<br>    HttpStatus.BAD_REQUEST,<br>    message,<br>    description,<br>    options,<br>  );<br>}<br>export function InternalError(<br>  message: string,<br>  description?: string,<br>  options?: ApiResponseOptions,<br>) {<br>  return ApiErrorDecorator(<br>    HttpStatus.INTERNAL_SERVER_ERROR,<br>    message,<br>    description,<br>    options,<br>  );<br>}</pre><p>Now let’s update our controller with our new custom decorators.</p><pre>// src/employee/employee.controller.ts<br><br>import { Body, Controller, Post } from &#39;@nestjs/common&#39;;<br>import { ApiOperation, ApiResponse, ApiTags } from &#39;@nestjs/swagger&#39;;<br>import { BadRequest, InternalError } from &#39;src/common/decorators/error&#39;;<br>import { EmployeeDTO } from &#39;./dto&#39;;<br>import { EmployeeService } from &#39;./employee.service&#39;;<br>@Controller(&#39;employee&#39;)<br>@ApiTags(&#39;employee&#39;)<br>export class EmployeeController {<br>  constructor(private readonly employeeService: EmployeeService) {}<br>  @Post()<br>  @ApiOperation({<br>    summary: &#39;Create new Employee&#39;,<br>    description: &#39;Lorem ipsum ....&#39;,<br>  })<br>  @ApiResponse({<br>    status: 201,<br>    type: EmployeeDTO,<br>  })<br>  @InternalError(&#39;Internal Server Error&#39;, &#39;Internal Server Error Description&#39;)<br>  @BadRequest(&#39;Bad Request Working&#39;, &#39;Bad Request Description&#39;)<br>  createEmployee(@Body() employeeDto: EmployeeDTO) {<br>    return { ...employeeDto, id: Date.now() };<br>  }<br>}</pre><h3>And Now it looks way way better :)</h3><p>For Conclusion, in case of error API documentation, custom decorators can help by providing a consistent and standardized way of defining and documenting error responses across the application. By encapsulating the logic for generating error responses and adding metadata such as status codes and messages, custom decorators can ensure that error responses are uniform and well-documented, making it easier for developers and consumers to understand and handle errors in a consistent and predictable way. Additionally, custom decorators can be designed to be flexible and extensible, allowing developers to customize error responses for specific use cases or modules, while still maintaining consistency and coherence across the application.</p><p><strong>Thanks for reading.</strong></p><p><a href="https://github.com/amitgal45/nestjs-open-api/tree/article-2">Github Repo</a></p><p><a href="https://medium.com/@amitgal45/nest-js-open-api-just-saves-so-much-time-part-1-551c9549f01f">Nest JS — Open API Just saves so much time — Part 1</a></p><p><a href="https://www.amit-gal.dev/blog/nestjs-open-api-just-saves-so-much-time-part-2/">My Website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e64a76f2be7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nest JS — Open API Just saves so much time — Part 1]]></title>
            <link>https://medium.com/@amitgal45/nest-js-open-api-just-saves-so-much-time-part-1-551c9549f01f?source=rss-492b643c087e------2</link>
            <guid isPermaLink="false">https://medium.com/p/551c9549f01f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Amit Gal]]></dc:creator>
            <pubDate>Fri, 14 Apr 2023 13:49:16 GMT</pubDate>
            <atom:updated>2024-07-28T09:32:06.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nest JS — Open API Just saves so much time — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*oFt-aACz823hxHhi.png" /></figure><p>After a long search, I finally found a tool that can write my backend documentation based on the code I write. I have been looking for a reliable solution for a while now, and it has been a challenge to find a tool that meets my specific needs. However, my search came to an end when I discovered NestJS OpenAPI.</p><h3>NestJS:</h3><p>NestJS provides a number of features and benefits that are particularly useful for building backend applications. For example, it offers a modular architecture that allows developers to organize their code into small, reusable modules that can be easily tested and maintained. Additionally, it provides a range of built-in modules and libraries that can help developers quickly implement common features such as authentication, caching, and database connectivity.</p><h3>OpenAPI:</h3><p>OpenAPI, previously known as Swagger, is a specification for building APIs. It provides a standardized and language-agnostic way to describe RESTful APIs, making it easier for developers to understand and interact with APIs. OpenAPI is becoming increasingly popular in the development community, and many frameworks, including NestJS, have built-in support for it.</p><p>In NestJS, OpenAPI can be used to automatically generate API documentation based on the code that developers write. This can save a significant amount of time and effort that would otherwise be spent manually documenting each API endpoint. NestJS’s integration with OpenAPI allows developers to easily define the structure and parameters of their API endpoints using decorators, which are then used to generate API documentation automatically. This ensures that the API documentation remains accurate and up-to-date, even as the code changes.</p><p>Another useful feature of OpenAPI in NestJS is the ability to validate API requests and responses. OpenAPI provides a schema for describing the structure and data types of request and response payloads. By using this schema, NestJS can automatically validate incoming requests and outgoing responses, ensuring that they conform to the expected format. This can help prevent errors and improve the overall reliability of the API.</p><h3>Installation:</h3><p>Create a new NestJS project or navigate to an existing NestJS project in your terminal.</p><p>Install the @nestjs/swagger package by running the following command:</p><pre>npm install --save @nestjs/swagger</pre><p>Update your main.ts file:</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { SwaggerModule, DocumentBuilder } from &#39;@nestjs/swagger&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  const config = new DocumentBuilder()<br>    .setTitle(&#39;Cats example&#39;)<br>    .setDescription(&#39;The cats API description&#39;)<br>    .setVersion(&#39;1.0&#39;)<br>    .addTag(&#39;cats&#39;)<br>    .build();<br>  const document = SwaggerModule.createDocument(app, config);<br>  SwaggerModule.setup(&#39;api&#39;, app, document);<br>  await app.listen(3001);<br>}<br>bootstrap();</pre><p>Right after starting your nest application, You can access the API documentation by opening your web browser and navigating to <a href="http://localhost:3001/api">http://localhost:3001/api</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cFGlAc32R0inuRdg.png" /><figcaption>Open Api endpoint</figcaption></figure><p>Once we have completed all the previous steps, we will be able to proceed with implementing the OpenAPI specification in our requests.</p><h3>Adding A new resource:</h3><p>The Nest CLI (Command Line Interface) is a powerful tool that is used to generate and manage Nest applications. It provides a set of commands that allow developers to quickly scaffold a new project, generate components such as controllers and services, and run the application.</p><p>Now we need to make a new resource we will use the next command:</p><pre>nest g resource employee</pre><p>When we use this command the CLI will generate a new module for your resource, along with a controller, service, and a test file.</p><p>You should see an employee folder inside src folder that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*ONRcwPCyEe0rtJ8x.png" /><figcaption>Employee folder</figcaption></figure><p>Employee resource folder</p><p>Now lets make a new Dto for Employee, lets create a dto folder inside employee to hold all employee dto’s. and the lets make a new file calls index.ts like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/0*6qm1S8lCbs7EariQ.png" /></figure><p>Lets add some content to the index.ts file:</p><pre>import { ApiProperty, ApiResponseProperty } from &#39;@nestjs/swagger&#39;;<br>export class EmployeeDTO {<br>  @ApiResponseProperty()<br>  id?: number;<br>  @ApiProperty()<br>  first_name: string;<br>  @ApiProperty()<br>  last_name: string;<br>}</pre><p>@ApiProperty — As you can see, the definition is empty although the class has a few declared properties. In order to make the class properties visible to the SwaggerModule, we have to either annotate them with the @ApiProperty() decorator or use the CLI plugin (read more in the Plugin section) which will do it automatically</p><p>Now when all set its time to make it works with our controllers.</p><h3>Types and parameters</h3><p>The SwaggerModule searches for all @Body(), @Query(), and @Param() decorators in route handlers to generate the API document. It also creates corresponding model definitions by taking advantage of reflection.</p><p>Lets start Edit our employee’s controller!!</p><p>We are gonna add a new method and call her create — this method will create a new Employee by the EmployeeDTO template and add it to the Employees Array</p><pre>import { Body, Controller, Post } from &#39;@nestjs/common&#39;;<br>import { ApiResponse, ApiTags } from &#39;@nestjs/swagger&#39;;<br>import { EmployeeDTO } from &#39;./dto&#39;;<br>import { EmployeeService } from &#39;./employee.service&#39;;<br>@Controller(&#39;employee&#39;)<br>@ApiTags(&#39;employee&#39;)<br>export class EmployeeController {<br>  constructor(private readonly employeeService: EmployeeService) {}<br><br>  @Post()<br>  @ApiResponse({<br>    status: 201,<br>    type: EmployeeDTO,<br>  })<br>  createEmployee(@Body() employeeDto: EmployeeDTO) {<br>    return {...employeeDto,id:Date.now()};<br>  }<br>}</pre><p>If we Check our open-api docs again we will see that things have changes. a new Api tag has added, a new POST method has been created and a new Employee Type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8O8re0jf1z_QbcQG.png" /><figcaption>Employee first method</figcaption></figure><p>Lets Open our generated employee’s POST Method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I4tG7faBnCnyzV7w.png" /><figcaption>Employee Method Body and response</figcaption></figure><p>We can see that the body and the Response has already generated with out defined “EmployeeDTO” type. But there is another question, why is The Request Body and The response are showed different if they are from the same type?</p><p>The answer is @ApiResponseProperty(), When we define a property with this tag that actual property will be shown only at the Response that we defined in our controller.</p><h3>Let’s learn another new cool decorators who are really useful:</h3><p>@ApiOperation() — Add a summary and description to your API Method:</p><p>Add the “ApiOperation” Decorator to our employee’s controller like in the following example:</p><pre>@Controller(&#39;employee&#39;)<br>@ApiTags(&#39;employee&#39;)<br>export class EmployeeController {<br>  constructor(private readonly employeeService: EmployeeService) {}<br>  @Post()<br>  @ApiOperation({<br>    summary: &#39;Create new Employee&#39;,<br>    description: &#39;Lorem ipsum ....&#39;,<br>  })<br>  @ApiResponse({<br>    status: 201,<br>    type: EmployeeDTO,<br>  })<br>  createEmployee(@Body() employeeDto: EmployeeDTO) {<br>    return { ...employeeDto, id: Date.now() };<br>  }<br>}</pre><p>The @ApiOperation decorator is used to provide metadata about the operation (HTTP endpoint) that the method handles. It takes an object with properties such as summary and description that describe the operation. In this case, the createEmployee() method is used to create a new employee, so the @ApiOperation decorator is used to provide a summary and description of the operation.</p><p>If we Check our open-api docs again we will see that our summary and description has been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHjQ2PLmD1YnOsZO.png" /><figcaption>ApiOperation Example</figcaption></figure><p>@ApiProperty() — Extra configuration!!</p><p>Usually when we build api we use validations to make sure that our properties are receives as expected. In nestjs Open api we can describe our Validations.</p><p>Lets edit our index.ts file inside dto folder like the following example:</p><pre>export class EmployeeDTO {<br>  @ApiResponseProperty()<br>  id?: number;<br>  @ApiProperty({<br>    description: &#39;The first name of a employee&#39;,<br>    minLength: 3,<br>    default: &#39;Amit&#39;,<br>  })<br>  first_name: string;<br>  @ApiProperty({<br>    description: &#39;The first name of a employee&#39;,<br>    minLength: 2,<br>    default: &#39;Gal&#39;,<br>  })<br>  last_name: string;<br>}</pre><p>As we can see we configured our ApiProperty decorator for each property. for example first_name description is ‘The first name of a employee’ min-length is 3 and the value will be default ‘amit’.</p><p>Now if we check our schemas on the bottom on the Doc-Page we will see that our properties received their doc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zQQDoD5J3j09ANzm.png" /><figcaption>EmployeeDTO Schema with validation</figcaption></figure><p>In conclusion, NestJS OpenAPI is a highly effective tool that streamlines API development and documentation. In this article you have learned just a bit about Open Api in Nests.</p><h4>Link for Github Repo:</h4><p><a href="https://github.com/amitgal45/nestjs-open-api">GitHub - amitgal45/nestjs-open-api</a></p><h4>In the next article we will talk More about Error handling, files handling and Generic Responses and Errors.</h4><h3>Thanks for reading!</h3><p><a href="https://www.amit-gal.dev/blog/nestjs-open-api-just-saves-so-much-time-part-1/">My website</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551c9549f01f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>