<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ezile Mdodana</title>
    <description>The latest articles on DEV Community by Ezile Mdodana (@ezilemdodana).</description>
    <link>https://dev.to/ezilemdodana</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F933356%2F909e30a1-4d01-4f33-a2a4-40879c70d498.png</url>
      <title>DEV Community: Ezile Mdodana</title>
      <link>https://dev.to/ezilemdodana</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ezilemdodana"/>
    <language>en</language>
    <item>
      <title>Introducing @ezilemdodana/nest-mapper — Lightweight Mapping for NestJS</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Thu, 05 Feb 2026 06:47:35 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/introducing-ezilemdodananest-mapper-lightweight-mapping-for-nestjs-523g</link>
      <guid>https://dev.to/ezilemdodana/introducing-ezilemdodananest-mapper-lightweight-mapping-for-nestjs-523g</guid>
      <description>&lt;p&gt;Hi NestJS community,&lt;/p&gt;

&lt;p&gt;I’ve recently published &lt;a class="mentioned-user" href="https://dev.to/ezilemdodana"&gt;@ezilemdodana&lt;/a&gt;/nest-mapper, a lightweight object mapper built specifically for NestJS projects.&lt;/p&gt;

&lt;p&gt;The motivation behind it was simple: many existing NestJS mapping solutions introduce dependency or configuration challenges, especially in larger or evolving projects. This package aims to provide a clean, dependency-light, and NestJS-friendly alternative focused on straightforward DTO ↔ entity mapping.&lt;/p&gt;

&lt;p&gt;If you’re working with NestJS and looking for a simpler mapping approach, I’d appreciate it if you could try it out and share feedback, issues, or improvement suggestions.&lt;/p&gt;

&lt;p&gt;Package: &lt;a href="https://www.npmjs.com/package/@ezilemdodana/nest-mapper" rel="noopener noreferrer"&gt;https://www.npmjs.com/package/@ezilemdodana/nest-mapper&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Feedback and contributions are welcome!&lt;/p&gt;

</description>
      <category>backend</category>
      <category>node</category>
      <category>showdev</category>
      <category>typescript</category>
    </item>
    <item>
      <title>10 Common Mistakes Beginners Make</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Wed, 17 Jul 2024 06:49:11 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/10-common-mistakes-beginners-make-53c6</link>
      <guid>https://dev.to/ezilemdodana/10-common-mistakes-beginners-make-53c6</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;br&gt;
Starting a career in software development is both exciting and challenging. While learning to code is crucial, understanding common pitfalls can help new developers navigate their journey more effectively. In this article, we will explore ten common mistakes that beginner software developers make and provide tips on how to avoid them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Not Asking for Help&lt;/strong&gt;&lt;br&gt;
Many beginners feel intimidated about asking for help, fearing it might make them seem less competent. However, seeking assistance is a vital part of learning. Experienced developers, mentors, and even online communities can provide valuable insights and solutions to problems that might take hours to solve alone. Remember, asking questions is a sign of eagerness to learn and grow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Neglecting Code Readability&lt;/strong&gt;&lt;br&gt;
Writing code that only you can understand is a common rookie mistake. Code readability is essential for collaboration and maintenance. Adopting best practices like using meaningful variable names, consistent indentation, and commenting on your code helps others (and your future self) understand your work. Following coding standards and guidelines also ensures that your code remains clean and maintainable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Overlooking Version Control&lt;/strong&gt;&lt;br&gt;
Version control systems like Git are indispensable tools for developers. They allow you to track changes, collaborate with others, and revert to previous versions if something goes wrong. Despite its importance, many beginners avoid using version control due to perceived complexity. Start with basic Git commands like commit, push, pull, and branch, and gradually explore more advanced features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Skipping Testing&lt;/strong&gt;&lt;br&gt;
Testing is often neglected by beginners, leading to unstable and buggy software. Writing tests ensures that your code works as intended and helps catch errors early. Start with unit tests to validate individual components, and gradually incorporate integration and automated tests. Tools like Jest for JavaScript, JUnit for Java, and PyTest for Python can help you get started.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Ignoring Documentation&lt;/strong&gt;&lt;br&gt;
Documentation is an often overlooked aspect of software development. It provides a roadmap for users and developers, explaining how the code works and how to use it. Whether it's inline comments, README files, or API documentation, take the time to document your code thoroughly. This practice not only helps others but also reinforces your understanding of the code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Not Understanding the Problem Before Coding&lt;/strong&gt;&lt;br&gt;
Beginners may jump into coding without fully understanding the problem. It's essential to analyze and plan before writing code. Techniques like pseudocode, flowcharts, and diagrams can help clarify the problem and outline a solution. Taking the time to understand the problem can save a lot of rework and frustration later.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;7. Overcomplicating Solutions&lt;/strong&gt;&lt;br&gt;
New developers might write overly complex solutions to simple problems. Advocate for simplicity and clarity in code. Introduce the KISS (Keep It Simple, Stupid) principle. Simple solutions are often more robust and easier to understand. Avoid over-engineering and focus on solving the problem at hand.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;8. Lack of Consistent Learning&lt;/strong&gt;&lt;br&gt;
Some beginners stop learning once they get a job or complete a course. However, technology is always evolving, and continuous learning is essential. Stay updated with industry trends and best practices by reading books, taking online courses, and participating in coding challenges. Engage with the developer community through forums, blogs, and conferences.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;9. Underestimating the Importance of Soft Skills&lt;/strong&gt;&lt;br&gt;
Technical skills are crucial, but soft skills like communication, teamwork, and time management are equally important. These skills can impact a developer's career and work environment significantly. Good communication ensures that ideas are clearly conveyed, and teamwork fosters a collaborative and productive environment. Managing your time effectively helps in meeting deadlines and balancing workloads.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;10. Failure to Review and Refactor Code&lt;/strong&gt;&lt;br&gt;
Beginners often write code and move on without reviewing or refactoring. Code reviews are an excellent way to catch mistakes, get feedback, and learn from more experienced developers. Regularly refactoring code improves its structure and performance. Adopt a mindset of continuous improvement and seek opportunities to enhance your code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
By addressing these common mistakes and adopting best practices, beginner software developers can set themselves up for success. Continuous learning, seeking feedback, and being open to new ideas will help you grow and excel in your career. Embrace the journey, learn from your mistakes, and remember that every experienced developer started where you are now.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>beginners</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Implementing Queues Using Linked Lists in NestJS</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Mon, 15 Jul 2024 17:01:21 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/implementing-queues-using-linked-lists-in-nestjs-539h</link>
      <guid>https://dev.to/ezilemdodana/implementing-queues-using-linked-lists-in-nestjs-539h</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;One of the fundamental data structures is the queue, which follows the First-In-First-Out (FIFO) principle. Combining the flexibility of linked lists with the functionality of queues can lead to efficient and dynamic data handling. This article guides you through the implementation of queues using linked lists in NestJS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding Queues and Linked Lists&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Queue Overview:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A queue is a linear data structure where elements are added at one end (rear) and removed from the other end (front). This structure is ideal for scenarios like task scheduling, request handling, and managing asynchronous operations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Linked List Overview:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A linked list is a collection of nodes where each node contains data and a reference to the next node in the sequence. Linked lists allow for efficient insertions and deletions without the need for contiguous memory.&lt;/p&gt;

&lt;p&gt;Combining these two, we can create a queue that efficiently handles dynamic data with minimal overhead.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementing the Queue Using Linked Lists&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Node Class&lt;/strong&gt;
Each node in the linked list will contain data and a reference 
to the next node.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class ListNode {
  constructor(
    public data: any,
    public next: ListNode | null = null,
  ) {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Queue Class:&lt;/strong&gt;
The queue class manages the nodes, ensuring elements are enqueued at 
the rear and dequeued from the front.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class LinkedListQueue {
  private head: ListNode | null = null;
  private tail: ListNode | null = null;

  enqueue(data: any): void {
    const newNode: ListNode = new ListNode(data);
    if (!this.tail) {
      this.head = this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
  }

  dequeue(): null | any {
    if (!this.head) return null;
    const data = this.head.data;
    this.head = this.head.next;
    if (!this.head) this.tail = null;
    return data;
  }

  isEmpty(): boolean {
    return this.head === null;
  }

  front(): null | any {
    return this.head ? this.head.data : null;
  }

  print(): void {
    let current: ListNode = this.head;
    while (current) {
      console.log(current.data);
      current = current.next;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;NestJS Service:&lt;/strong&gt;
Encapsulate the queue operations within a NestJS service.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable()
export class QueueService {
  private queue: LinkedListQueue = new LinkedListQueue();

  enqueueElement(data: any): void {
    this.queue.enqueue(data);
  }

  dequeueElement(): any {
    return this.queue.dequeue();
  }

  isQueueEmpty(): boolean {
    return this.queue.isEmpty();
  }

  getFrontElement(): any {
    return this.queue.front();
  }

  printQueue(): void {
    this.queue.print();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Controller Integration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a controller to expose the queue operations through API endpoints.&lt;br&gt;
I used &lt;a href="https://www.npmjs.com/package/@nestjs/swagger" rel="noopener noreferrer"&gt;swagger&lt;/a&gt; for testing the endpoints, you need to install swagger if you want to do the same.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Controller('queue')
@ApiTags('Queue')
export class QueueController {
  constructor(private readonly queueService: QueueService) {}

  @Post('enqueue/:data')
  @ApiParam({ name: 'data', type: 'string' })
  enqueueElement(@Param('data') data: string) {
    this.queueService.enqueueElement(data);
    return { message: 'Element enqueued successfully' };
  }

  @Delete('dequeue')
  dequeueElement() {
    const data = this.queueService.dequeueElement();
    return { data };
  }

  @Get('is-empty')
  isQueueEmpty() {
    return { isEmpty: this.queueService.isQueueEmpty() };
  }

  @Get('front')
  getFrontElement() {
    const data = this.queueService.getFrontElement();
    return { data };
  }

  @Get()
  printQueue() {
    this.queueService.printQueue();
    return { message: 'Queue printed successfully' };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Optimizing Queue Operations&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Time Complexity:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Enqueue: O(1) – Adding an element to the tail.&lt;/li&gt;
&lt;li&gt;Dequeue: O(1) – Removing an element from the head.&lt;/li&gt;
&lt;li&gt;Front: O(1) – Accessing the front element.&lt;/li&gt;
&lt;li&gt;IsEmpty: O(1) – Checking if the queue is empty.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Task scheduling systems.&lt;/li&gt;
&lt;li&gt;Managing asynchronous operations in web applications.
...and many more.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implementing queues using linked lists in NestJS provides a dynamic and efficient way to manage data. By encapsulating queue operations within services and exposing them through controllers, you can create robust solutions for various real-world scenarios. Experiment with these implementations to enhance your NestJS applications' performance and scalability.&lt;/p&gt;

&lt;p&gt;My way is not the only way!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Efficient Implementation of Linked Lists in NestJS</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Fri, 12 Jul 2024 16:56:21 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/efficient-implementation-of-linked-lists-in-nestjs-4mnc</link>
      <guid>https://dev.to/ezilemdodana/efficient-implementation-of-linked-lists-in-nestjs-4mnc</guid>
      <description>&lt;p&gt;&lt;strong&gt;Introduction&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;NestJS, a progressive Node.js framework, offers a robust platform for building efficient and scalable server-side applications. Understanding and implementing efficient data structures can significantly improve the performance and maintainability of your applications. This article focuses on linked lists, specifically Single Linked List(SLL), a fundamental data structure, and how to effectively use them in NestJS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding Linked Lists&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A linked list is a linear data structure where each element (node) contains a reference (link) to the next element in the sequence. Unlike arrays, linked lists do not require contiguous memory locations, making them efficient for insertions and deletions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Types of Linked Lists:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Singly Linked List: Each node points to the next node.&lt;/li&gt;
&lt;li&gt;Doubly Linked List: Each node points to both the next and the previous nodes.&lt;/li&gt;
&lt;li&gt;Circular Linked List: The last node points back to the first node, forming a circle.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Implementing a Singly Linked List in NestJS&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Node Class:&lt;/strong&gt;
Each node in a linked list contains data and a reference to the next node.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class ListNode {
  constructor(
    public data: any,
    public next: ListNode | null = null,
  ) {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Linked List Class:&lt;/strong&gt;
The linked list class manages the nodes and provides methods for common operations.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class LinkedList {
  private head: ListNode | null = null;

  add(data: any): void {
    const newNode: ListNode = new ListNode(data);
    if (!this.head) {
      this.head = newNode;
    } else {
      let current: ListNode = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
  }

  remove(data: any): void {
    if (!this.head) {
      return;
    }

    if (this.head.data === data) {
      this.head = this.head.next;
      return;
    }

    let current: ListNode = this.head;
    while (current.next &amp;amp;&amp;amp; current.next.data !== data) {
      current = current.next;
    }

    if (current.next) {
      current.next = current.next.next;
    }
  }

  find(data: any): ListNode | null {
    let current: ListNode = this.head;
    while (current &amp;amp;&amp;amp; current.data !== data) {
      current = current.next;
    }
    return current;
  }

  print(): void {
    let current: ListNode = this.head;
    while (current) {
      console.log(current.data);
      current = current.next;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;NestJS Service:&lt;/strong&gt;
Integrate the linked list into a NestJS service to encapsulate its operations.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Injectable()
export class LinkedListService {
  private linkedList: LinkedList = new LinkedList();

  addElement(data: any): void {
    this.linkedList.add(data);
  }

  removeElement(data: any): void {
    this.linkedList.remove(data);
  }

  findElement(data: any): ListNode {
    return this.linkedList.find(data);
  }

  getElements(): void {
    return this.linkedList.print();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Controller Integration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a controller to expose the linked list operations through API endpoints.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Controller('linked-list')
export class LinkedListController {
  constructor(private readonly linkedListService: LinkedListService) {}

  @Post('add')
  addElement(@Body('data') data: any) {
    this.linkedListService.addElement(data);
    return { message: 'Element added successfully' };
  }

  @Delete('remove')
  removeElement(@Body('data') data: any) {
    this.linkedListService.removeElement(data);
    return { message: 'Element removed successfully' };
  }

  @Get('find')
  findElement(@Body('data') data: any) {
    const element = this.linkedListService.findElement(data);
    return { element };
  }

  @Get()
  getElements() {
    this.linkedListService.getElements();
    return { message: 'Elements printed successfully' };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Optimizing Linked Lists&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Time Complexity:

&lt;ul&gt;
&lt;li&gt;Insertion: O(1) if inserting at the head; O(n) if inserting at the 
tail.&lt;/li&gt;
&lt;li&gt;Deletion: O(1) if deleting the head; O(n) if deleting another node.&lt;/li&gt;
&lt;li&gt;Search: O(n).&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use Cases:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use linked lists for scenarios where frequent insertions and 
deletions are required.&lt;/li&gt;
&lt;li&gt;Suitable for implementing queues, stacks, and other dynamic data 
structures.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Understanding and implementing linked lists in NestJS can greatly enhance the performance and scalability of your applications. By integrating linked lists into NestJS services and controllers, you can create robust and efficient solutions for various use cases. Experiment with these implementations in your projects to see the benefits firsthand.&lt;/p&gt;

&lt;p&gt;My way is not the only way!&lt;/p&gt;

</description>
      <category>datastructures</category>
      <category>typescript</category>
      <category>nestjs</category>
      <category>backend</category>
    </item>
    <item>
      <title>Middleware and Interceptors in NestJS: Best Practices</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Fri, 14 Jun 2024 10:04:12 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/middleware-and-interceptors-in-nestjs-best-practices-5923</link>
      <guid>https://dev.to/ezilemdodana/middleware-and-interceptors-in-nestjs-best-practices-5923</guid>
      <description>&lt;p&gt;NestJS is a progressive Node.js framework for building efficient and scalable server-side applications. Among its many powerful features, middleware and interceptors stand out as essential tools for handling cross-cutting concerns in a clean and reusable manner. In this article, we'll explore the concepts of middleware and interceptors, their use cases, and best practices for implementing them in your NestJS applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Middleware in NestJS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;What is Middleware?&lt;/p&gt;

&lt;p&gt;Middleware functions are functions that have access to the request and response objects, and the next middleware function in the application's request-response cycle. Middleware can perform a variety of tasks, such as logging, authentication, parsing, and more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating Middleware&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In NestJS, middleware can be created as either a function or a class implementing the &lt;strong&gt;NestMiddleware&lt;/strong&gt; interface. Here’s an example of both approaches:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Function-based Middleware&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Request, Response, NextFunction } from 'express';

export function logger(req: Request, res: Response, next: NextFunction) {
  console.log(`Request...`);
  next();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Class-based Middleware&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Request...');
    next();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Applying Middleware&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { logger } from './common/middleware/logger.middleware';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(logger);
  await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To apply middleware to specific routes, use the configure method in a module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsController } from './cats/cats.controller';

@Module({
  controllers: [CatsController],
})
export class CatsModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes(CatsController);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Use Cases for Middleware&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Logging: Log requests for debugging and analytics.&lt;/li&gt;
&lt;li&gt;Authentication: Check if a user is authenticated before proceeding.&lt;/li&gt;
&lt;li&gt;Request Parsing: Parse incoming request bodies (e.g., JSON, URL-encoded).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Interceptors in NestJS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is an Interceptor?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Interceptors are used to perform actions before and after the execution of route handlers. They can transform request/response data, handle logging, or modify the function execution flow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Interceptors are implemented using the NestInterceptor interface and the @Injectable decorator. Here’s an example of a basic interceptor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor&amp;lt;T&amp;gt; implements NestInterceptor&amp;lt;T, any&amp;gt; {
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable&amp;lt;any&amp;gt; {
    return next
      .handle()
      .pipe(map(data =&amp;gt; ({ data })));
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Applying Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Interceptors can be applied globally, at the controller level, or at the route handler level.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Global Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To apply an interceptor globally, use the useGlobalInterceptors method in the main.ts file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalInterceptors(new TransformInterceptor());
  await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Controller-level Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To apply an interceptor at the controller level, use the @UseInterceptors decorator:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';

@Controller('cats')
@UseInterceptors(TransformInterceptor)
export class CatsController {
  @Get()
  findAll() {
    return { message: 'This action returns all cats' };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Route-level Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To apply an interceptor at the route handler level, use the @UseInterceptors decorator directly on the method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';

@Controller('cats')
export class CatsController {
  @Get()
  @UseInterceptors(TransformInterceptor)
  findAll() {
    return { message: 'This action returns all cats' };
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Use Cases for Interceptors&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Response Transformation: Modify response data before sending it to the client.&lt;/li&gt;
&lt;li&gt;Logging: Log method execution time and other details.&lt;/li&gt;
&lt;li&gt;Exception Mapping: Transform exceptions into user-friendly error messages.&lt;/li&gt;
&lt;li&gt;Caching: Implement caching mechanisms for repeated requests.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Best Practices&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Keep Middleware Lightweight: Middleware should be focused on tasks that need to be performed on every request, such as logging or authentication. Avoid heavy processing in middleware.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use Interceptors for Transformation: Use interceptors for transforming request and response data, logging execution time, and handling errors.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Modularize Middleware and Interceptors: Create separate files and directories for middleware and interceptors to keep the codebase organized.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Leverage Dependency Injection: Use NestJS's dependency injection system to inject services into middleware and interceptors.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Avoid Redundant Code: Use global middleware and interceptors for tasks that need to be applied across the entire application, and use route-specific ones for more granular control.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Middleware and interceptors are powerful tools in NestJS that help you handle cross-cutting concerns effectively. By following best practices and understanding their use cases, you can create more maintainable and scalable NestJS applications. Whether you're logging requests, handling authentication, transforming responses, or caching data, middleware and interceptors provide the flexibility and control needed to build robust applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;My way is not the only way!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>backend</category>
      <category>typescript</category>
      <category>middleware</category>
    </item>
    <item>
      <title>Recursion</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Thu, 13 Jun 2024 06:11:53 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/recursion-3j78</link>
      <guid>https://dev.to/ezilemdodana/recursion-3j78</guid>
      <description>&lt;p&gt;&lt;em&gt;This is a submission for DEV Computer Science Challenge v24.06.12: One Byte Explainer.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Explainer
&lt;/h2&gt;

&lt;p&gt;A programming technique where a function calls itself to solve a problem. It breaks down complex problems into simpler ones. Crucial for tasks like tree traversal and solving puzzles (e.g., Fibonacci sequence). Helps write clean, concise code but can risk infinite loops if not handled correctly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Additional Context
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Fundamental Concept: Recursion is a fundamental concept in computer science, used across various domains from algorithms to problem-solving techniques.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Practical Applications: It's widely used in sorting algorithms (like quicksort and mergesort), data structures (like trees and graphs), and problem-solving (like backtracking and dynamic programming).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Educational Value: Understanding recursion is essential for learning more advanced concepts in computer science, making it a pivotal topic for both students and professionals.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Balance of Simplicity and Power: While recursion simplifies code and reduces redundancy, it also requires careful handling to avoid issues like infinite recursion and stack overflow.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Common Misconceptions: Many beginners struggle with recursion, so a clear and concise explanation can demystify the concept and highlight its importance and utility in a way that's approachable and informative.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>devchallenge</category>
      <category>cschallenge</category>
      <category>computerscience</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Real-time Applications with NestJS and WebSockets</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Mon, 10 Jun 2024 19:10:48 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/real-time-applications-with-nestjs-and-websockets-5afk</link>
      <guid>https://dev.to/ezilemdodana/real-time-applications-with-nestjs-and-websockets-5afk</guid>
      <description>&lt;p&gt;Real-time applications have become an integral part of modern web development, enabling instant communication and dynamic interactions. NestJS, with its powerful framework and support for WebSockets, makes it easy to build such applications. In this article, we'll explore how to create real-time applications with NestJS and WebSockets, covering key concepts, implementation steps, and best practices.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use WebSockets?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;WebSockets provide a full-duplex communication channel over a single TCP connection, allowing real-time data exchange between the client and server. Unlike traditional HTTP requests, WebSockets maintain an open connection, enabling instant updates without the need for polling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting Up a NestJS Project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, create a new NestJS project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nest new real-time-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Navigate to the project directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd real-time-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Installing WebSocket Dependencies&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;NestJS provides a WebSocket module out of the box. Install the necessary package:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @nestjs/websockets @nestjs/platform-socket.io
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Creating a WebSocket Gateway&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;A gateway in NestJS acts as a controller for WebSocket events. Create a new gateway using the NestJS CLI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nest generate gateway chat
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a new chat.gateway.ts file. Let's define our gateway to handle real-time chat messages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {
  SubscribeMessage,
  WebSocketGateway,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect,
  WebSocketServer,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Socket, Server } from 'socket.io';

@WebSocketGateway()
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('ChatGateway');

  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: string): void {
    this.server.emit('message', payload);
  }

  afterInit(server: Server) {
    this.logger.log('Init');
  }

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`);
  }

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;@WebSocketGateway(): Decorator to mark the class as a WebSocket gateway&lt;/li&gt;
&lt;li&gt;@WebSocketServer(): Decorator to inject the WebSocket server instance&lt;/li&gt;
&lt;li&gt;handleMessage(): Method to handle incoming messages and broadcast them to all connected clients&lt;/li&gt;
&lt;li&gt;afterInit(): Lifecycle hook called after the gateway is initialized&lt;/li&gt;
&lt;li&gt;handleConnection(): Lifecycle hook called when a client connects&lt;/li&gt;
&lt;li&gt;handleDisconnect(): Lifecycle hook called when a client disconnects&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Handling Events on the Client-Side&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To handle WebSocket events on the client side, you can use the socket.io-client library. Install it using:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install socket.io-client
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s an example of a simple client-side implementation in an HTML file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset="UTF-8"&amp;gt;
  &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
  &amp;lt;title&amp;gt;Chat App&amp;lt;/title&amp;gt;
  &amp;lt;script src="https://cdn.socket.io/4.0.1/socket.io.min.js"&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script&amp;gt;
    document.addEventListener('DOMContentLoaded', () =&amp;gt; {
      const socket = io('http://localhost:3000');

      const form = document.getElementById('form');
      const input = document.getElementById('input');
      const messages = document.getElementById('messages');

      form.addEventListener('submit', (e) =&amp;gt; {
        e.preventDefault();
        if (input.value) {
          socket.emit('message', input.value);
          input.value = '';
        }
      });

      socket.on('message', (message) =&amp;gt; {
        const item = document.createElement('li');
        item.textContent = message;
        messages.appendChild(item);
      });
    });
  &amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;ul id="messages"&amp;gt;&amp;lt;/ul&amp;gt;
  &amp;lt;form id="form" action=""&amp;gt;
    &amp;lt;input id="input" autocomplete="off" /&amp;gt;&amp;lt;button&amp;gt;Send&amp;lt;/button&amp;gt;
  &amp;lt;/form&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Socket.IO: The socket.io-client library is used to handle WebSocket connections&lt;/li&gt;
&lt;li&gt;Connecting to the Server: io('&lt;a href="http://localhost:3000'"&gt;http://localhost:3000'&lt;/a&gt;) establishes a connection to the WebSocket server&lt;/li&gt;
&lt;li&gt;Sending Messages: The form submission event sends messages to the server using socket.emit('message', input.value)&lt;/li&gt;
&lt;li&gt;Receiving Messages: The socket.on('message') event handler updates the DOM with new messages&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Best Practices&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Authentication and Authorization: Ensure that WebSocket connections are authenticated and authorized. Use middlewares or guards to secure your WebSocket endpoints&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Error Handling: Implement proper error handling for your WebSocket events to ensure robustness&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scalability: Use tools like Redis for pub/sub patterns if you need to scale your WebSocket server&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Monitoring and Logging: Integrate monitoring tools to keep track of WebSocket connections and events&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Building real-time applications with NestJS and WebSockets is straightforward and efficient. By leveraging NestJS's WebSocket module, you can create highly interactive and responsive applications. Follow best practices for authentication, error handling, and scalability to ensure your real-time application is robust and secure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;My way is not the only way!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>backend</category>
      <category>typescript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Event-Driven Architecture with NestJS: Using the EventEmitter Module</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Sat, 08 Jun 2024 12:58:34 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/event-driven-architecture-with-nestjs-using-the-eventemitter-module-35fe</link>
      <guid>https://dev.to/ezilemdodana/event-driven-architecture-with-nestjs-using-the-eventemitter-module-35fe</guid>
      <description>&lt;p&gt;In today's software development landscape, building scalable and maintainable applications is a primary concern for developers. Event-driven architecture (EDA) is a powerful design pattern that helps address these concerns by promoting decoupled and asynchronous communication between different parts of a system. NestJS, a progressive Node.js framework, provides robust support for EDA through its EventEmitter module. This article explores the benefits of EDA and demonstrates how to implement it using the EventEmitter module in a NestJS application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Understanding Event-Driven Architecture&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Event-driven architecture is a design paradigm in which system components communicate by producing and consuming events. An event is a significant change in state, such as a user action or system occurrence. This architecture consists of three main components:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Event Producers: Generate events when certain actions or changes occur.&lt;/li&gt;
&lt;li&gt;Event Consumers: Listen for and react to specific events.&lt;/li&gt;
&lt;li&gt;Event Channels: Transport events from producers to consumers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;EDA offers several benefits:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Decoupling: Components are loosely coupled, reducing dependencies and making the system more modular and maintainable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Scalability: Asynchronous event handling allows the system to scale more effectively.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Responsiveness: Real-time event processing leads to more responsive applications.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;NestJS and the EventEmitter Module&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;NestJS is a framework that leverages TypeScript to build efficient and scalable server-side applications. It incorporates many design patterns and best practices from Angular, providing a structured way to develop applications. One of the key features of NestJS is its support for event-driven programming through the EventEmitter module.&lt;/p&gt;

&lt;p&gt;The EventEmitter module in NestJS is built on top of the Node.js events module, offering a simple yet powerful way to implement EDA. It allows you to define events, emit them from various parts of your application, and handle them with dedicated listeners.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting Up a NestJS Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before diving into the implementation, let's set up a basic NestJS application. If you haven't already, install the Nest CLI globally:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @nestjs/cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a new NestJS project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nest new event-driven-app
cd event-driven-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Install the EventEmitter module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @nestjs/event-emitter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Implementing Event-Driven Architecture&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Defining Events&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, define the events your application will use. Create a events directory in the src folder, and within it, create an events.ts file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/events/events.ts

export class UserCreatedEvent {
  constructor(public readonly userId: string, public readonly username: string) {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Emitting Events&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Next, emit events from appropriate parts of your application. For demonstration purposes, let's assume we have a UserService that creates users and emits a UserCreatedEvent when a new user is created.&lt;/p&gt;

&lt;p&gt;Create a user directory in the src folder, and within it, create user.service.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/user/user.service.ts

import { Injectable } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { UserCreatedEvent } from '../events/events';

@Injectable()
export class UserService {
  constructor(private eventEmitter: EventEmitter2) {}

  createUser(userId: string, username: string): void {
    // Logic to create a user (e.g., saving to a database)

    // Emit UserCreatedEvent
    const event = new UserCreatedEvent(userId, username);
    this.eventEmitter.emit('user.created', event);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Handling Events&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now, create an event listener to handle the UserCreatedEvent. Create a listeners directory in the src folder, and within it, create user-created.listener.ts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/listeners/user-created.listener.ts

import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { UserCreatedEvent } from '../events/events';

@Injectable()
export class UserCreatedListener {
  @OnEvent('user.created')
  handleUserCreatedEvent(event: UserCreatedEvent) {
    // Logic to handle the event (e.g., sending a welcome email)
    console.log(`User created: ${event.userId} (${event.username})`);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Registering the Listener&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Finally, register the event listener in your application's module. Open app.module.ts and update it as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/app.module.ts

import { Module } from '@nestjs/common';
import { EventEmitterModule } from '@nestjs/event-emitter';
import { UserService } from './user/user.service';
import { UserCreatedListener } from './listeners/user-created.listener';

@Module({
  imports: [
    EventEmitterModule.forRoot(),
  ],
  providers: [UserService, UserCreatedListener],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Running the Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;With everything set up, you can now run your NestJS application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start:dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Test the event-driven functionality by creating a user through the UserService:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { UserService } from './user/user.service';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const userService = app.get(UserService);

  userService.createUser('1', 'Test User');

  await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Upon running the application, you should see the following output, indicating that the UserCreatedEvent was emitted and handled:

User created: 1 (Test User)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Event-driven architecture is a powerful approach for building scalable, maintainable, and responsive applications. NestJS's EventEmitter module makes it easy to implement EDA by providing a simple yet effective way to define, emit, and handle events. By following the steps outlined in this article, you can start leveraging the benefits of EDA in your NestJS applications, leading to more modular and efficient codebases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;My way is not the only way!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>typescript</category>
      <category>backend</category>
      <category>eventdriven</category>
    </item>
    <item>
      <title>Deploying NestJS Apps to Heroku: A Comprehensive Guide</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Fri, 07 Jun 2024 08:26:35 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/deploying-nestjs-apps-to-heroku-a-comprehensive-guide-hhj</link>
      <guid>https://dev.to/ezilemdodana/deploying-nestjs-apps-to-heroku-a-comprehensive-guide-hhj</guid>
      <description>&lt;p&gt;Deploying a NestJS application to Heroku can be a straightforward process if you follow the right steps. In this guide, we'll walk you through the entire process, from setting up your NestJS application to deploying it on Heroku and handling any dependencies or configurations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Setting Up Your NestJS Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before deploying, ensure you have a NestJS application ready. If you don't have one, you can create a new NestJS project using the Nest CLI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Install Nest CLI:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g @nestjs/cli
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Create a New Project:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;nest new my-nestjs-app
cd my-nestjs-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Run the Application Locally:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run start:dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Prepare Your Application for Heroku&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Heroku requires a few specific configurations to properly deploy a Node.js application.&lt;br&gt;
Let's go through these configurations step by step.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Create a Procfile:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the root of your project, create a file named Procfile and add the following line:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;web: npm run start:prod
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This tells Heroku to start your application using the production build.&lt;br&gt;
&lt;strong&gt;NB:&lt;/strong&gt; The name of the file should be Procfile, nothing more nothing less, if the case is different from this, heroku won't recognize the file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.Update package.json:&lt;/strong&gt;&lt;br&gt;
Ensure your package.json has the following scripts:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
  "start": "nest start",
  "start:dev": "nest start --watch",
  "start:prod": "node dist/main.js",
  "build": "nest build"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Additionally, add the following configuration to ensure your app runs on the correct port:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"engines": {
  "node": "&amp;gt;=14.0.0"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Depending on the node version you are using for your application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Initialize a Git Repository&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Heroku uses Git for deployments. Initialize a Git repository if you don't have one already.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1.Initialize Git:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git init
git add .
git commit -m "Initial commit"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Deploy to Heroku&lt;/strong&gt;&lt;br&gt;
Now, let's deploy your application to Heroku.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Login to Heroku:&lt;/strong&gt;&lt;br&gt;
Let's use the Heroku CLI to login, run the command on your project directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heroku login
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will open a browser and require your login credentials, populate and complete 2FA, if enabled. The come back to the CLI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Create a New Heroku Application:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heroku create my-nestjs-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Deploy Your Application:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;git push heroku master
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Handle Environment Variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Heroku allows you to manage environment variables through its dashboard or CLI, let's manage a few via the CLI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Set Environment Variables:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heroku config:set NODE_ENV=production
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you have other environment variables, set them as well:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heroku config:set DATABASE_URL=your_database_url
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 6: Verify Your Deployment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Open Your Application:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heroku open
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can open the application from the Heroku dashboard as well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Check Logs:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you encounter any issues, check the logs with:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;heroku logs --tail
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Deploying a NestJS application to Heroku is a straightforward process if you follow these steps. By preparing your application properly and using Heroku's powerful features, you can have your NestJS app running in the cloud in no time. Whether you're deploying a simple API or a complex application with multiple dependencies, Heroku provides a robust platform for managing your applications. Happy coding!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;My way is not the only way!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>heroku</category>
      <category>nestjs</category>
      <category>typescript</category>
      <category>backend</category>
    </item>
    <item>
      <title>Best Practices for Building Microservices with NestJS</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Thu, 06 Jun 2024 06:57:49 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/best-practices-for-building-microservices-with-nestjs-p3e</link>
      <guid>https://dev.to/ezilemdodana/best-practices-for-building-microservices-with-nestjs-p3e</guid>
      <description>&lt;p&gt;Microservices architecture has become a popular approach for developing scalable and maintainable applications. NestJS, a progressive Node.js framework, offers robust support for building microservices with its modular architecture and powerful features. In this article, we'll explore best practices for building microservices with NestJS, providing clear details and examples to help you implement these practices effectively.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Design Microservices with a Clear Domain&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;br&gt;
Start by defining the boundaries of each microservice based on the business domains. Each microservice should have a single responsibility and encapsulate a specific business capability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;br&gt;
Suppose we are building an e-commerce platform. We can define the following microservices:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User Service&lt;/strong&gt;: Handles user authentication, registration, and profile management.&lt;br&gt;
&lt;strong&gt;Product Service&lt;/strong&gt;: Manages product listings, inventory, and pricing.&lt;br&gt;
&lt;strong&gt;Order Service&lt;/strong&gt;: Processes customer orders and handles payment transactions.&lt;/p&gt;

&lt;p&gt;By designing microservices around specific business domains, we ensure better scalability and maintainability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Use a Consistent Communication Protocol&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Choose a consistent communication protocol for inter-service communication. Common protocols include HTTP, &lt;a href="https://grpc.io/"&gt;gRPC&lt;/a&gt;, and message brokers like &lt;a href="https://www.rabbitmq.com/"&gt;RabbitMQ&lt;/a&gt; or &lt;a href="https://kafka.apache.org/"&gt;Kafka&lt;/a&gt;. NestJS supports various communication strategies, allowing you to choose the one that best fits your needs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using RabbitMQ for event-driven communication between microservices:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// user.service.ts
import { Controller } from '@nestjs/common';
import { EventPattern } from '@nestjs/microservices';

@Controller()
export class UserService {
  @EventPattern('user_created')
  handleUserCreated(data: any) {
    console.log('User created event received:', data);
    // Process the event
  }
}

// product.service.ts
import { Controller } from '@nestjs/common';
import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices';

@Controller()
export class ProductService {
  private client: ClientProxy;

  constructor() {
    this.client = ClientProxyFactory.create({
      transport: Transport.RMQ,
      options: {
        urls: ['amqp://localhost:5672'],
        queue: 'product_queue',
      },
    });
  }

  createProduct(product: any) {
    // Create product logic
    this.client.emit('product_created', product);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Implement API Gateways&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Use an API gateway to aggregate multiple microservice endpoints into a single entry point. This simplifies client interactions and allows for better management of cross-cutting concerns like authentication, rate limiting, and logging.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Creating an API gateway with NestJS:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';

@Module({
  imports: [
    ClientsModule.register([
      { name: 'USER_SERVICE', transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'user_queue' } },
      { name: 'PRODUCT_SERVICE', transport: Transport.RMQ, options: { urls: ['amqp://localhost:5672'], queue: 'product_queue' } },
    ]),
  ],
})
export class ApiGatewayModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4. Implement Robust Error Handling&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement consistent and robust error handling mechanisms across all microservices. This includes handling exceptions, retries, and fallback mechanisms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Using an exception filter in NestJS:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpErrorFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    const errorResponse = {
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: ctx.getRequest().url,
    };

    response.status(status).json(errorResponse);
  }
}

// In your main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpErrorFilter } from './common/filters/http-error.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpErrorFilter());
  await app.listen(3000);
}
bootstrap();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5. Secure Microservices&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement security best practices to protect your microservices. This includes using TLS/SSL, API keys, OAuth, and JWT for authentication and authorization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Securing an endpoint with JWT in NestJS:&lt;/p&gt;

&lt;p&gt;// auth.module.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy } from './jwt.strategy';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      secret: 'secretKey',
      signOptions: { expiresIn: '60s' },
    }),
  ],
  providers: [JwtStrategy],
  exports: [PassportModule, JwtModule],
})
export class AuthModule {}

// jwt.strategy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secretKey',
    });
  }

  async validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}

// In your controller
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('protected')
export class ProtectedController {
  @Get()
  @UseGuards(AuthGuard('jwt'))
  getProtectedResource() {
    return 'This is a protected resource';
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;6. Implement Health Checks and Monitoring&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement health checks and monitoring to ensure the availability and performance of your microservices. Use tools like &lt;a href="https://prometheus.io/"&gt;Prometheus&lt;/a&gt;, &lt;a href="https://grafana.com/"&gt;Grafana&lt;/a&gt;, or NestJS built-in health checks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Adding a health check endpoint in NestJS:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { TypeOrmModule } from '@nestjs/typeorm';
import { HealthController } from './health.controller';

@Module({
  imports: [TerminusModule, TypeOrmModule.forRoot()],
  controllers: [HealthController],
})
export class AppModule {}

// health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { HealthCheck, HealthCheckService, TypeOrmHealthIndicator } from '@nestjs/terminus';

@Controller('health')
export class HealthController {
  constructor(
    private health: HealthCheckService,
    private db: TypeOrmHealthIndicator,
  ) {}

  @Get()
  @HealthCheck()
  check() {
    return this.health.check([
      async () =&amp;gt; this.db.pingCheck('database'),
    ]);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;7. Use CI/CD for Continuous Deployment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Best Practice&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement continuous integration and continuous deployment (CI/CD) pipelines to automate the testing, building, and deployment of your microservices. Use tools like GitHub Actions, Jenkins, or GitLab CI/CD.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Building microservices with NestJS offers a powerful and flexible approach to developing scalable and maintainable applications. By following these best practices, you can ensure your microservices are well-designed, secure, and resilient. Embrace the modular architecture of NestJS, leverage its rich ecosystem, and implement robust communication and error-handling strategies to create a successful microservices-based system. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;My way is not the only way!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>typescript</category>
      <category>microservices</category>
      <category>backend</category>
    </item>
    <item>
      <title>Animated Spinner - React Native</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Tue, 21 Mar 2023 12:36:26 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/animated-spinner-react-native-1mo4</link>
      <guid>https://dev.to/ezilemdodana/animated-spinner-react-native-1mo4</guid>
      <description>&lt;p&gt;Most of the times in Mobile Development, you might want to have an interactive spinner/activity indicator. In this short article we are going to demonstrate how we can achieve that to an Expo generated React Native app.&lt;/p&gt;

&lt;p&gt;We demonstrate this using &lt;strong&gt;Lottie React Native&lt;/strong&gt;, therefore, you need to install the librabry &lt;em&gt;&lt;strong&gt;lottie-react-native&lt;/strong&gt;&lt;/em&gt; by running the command &lt;em&gt;&lt;strong&gt;yarn add lottie-react-native&lt;/strong&gt;&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;Now, go to &lt;em&gt;&lt;strong&gt;&lt;a href="https://lottiefiles.com/"&gt;https://lottiefiles.com/&lt;/a&gt;&lt;/strong&gt;&lt;/em&gt;, you need to create a free account before you can be able to download animations, here you can search and download the animated activity indicator that you want to use, select to download the Lottie JSON file. Take the JSON file and put it inside your react native project (e.g assets/animation.json).&lt;/p&gt;

&lt;p&gt;Now, you can create a shared component that you will use throughout your project, or wherever you want to use it. Let's have a look at the example of such component below:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import Lottie from 'lottie-react-native';

const LoadingComponent = () =&amp;gt; {
   return(
       &amp;lt;Lottie source={require('../src/assets/animation.json')} autoPlay loop /&amp;gt;
    );
};
export default LoadingComponent;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are importing Lottie from 'lottie-react-native', a library that we installed, the component returns and animation which is created from the JSON file we downloaded from &lt;em&gt;&lt;strong&gt;&lt;a href="https://lottiefiles.com/"&gt;https://lottiefiles.com/&lt;/a&gt;&lt;/strong&gt;&lt;/em&gt;. Notice, what we return on the component has &lt;em&gt;&lt;strong&gt;autoPlay&lt;/strong&gt;&lt;/em&gt; and &lt;em&gt;&lt;strong&gt;loop&lt;/strong&gt;&lt;/em&gt;, &lt;strong&gt;&lt;em&gt;autoPlay&lt;/em&gt;&lt;/strong&gt; is for making the animation play automatically, and &lt;em&gt;&lt;strong&gt;loop&lt;/strong&gt;&lt;/em&gt; is for the animation to continue playing, while rendered. &lt;/p&gt;

&lt;p&gt;You can always modify or play around these on the React useEffect, give the animation the behavior you want based on some conditions.&lt;/p&gt;

&lt;p&gt;You now have an animated activity indicator on your app.&lt;/p&gt;

&lt;p&gt;Thank you very much for reading.🤓😎&lt;/p&gt;

</description>
      <category>mobile</category>
      <category>reactnative</category>
      <category>javascript</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Suspense for Data Fetching - React</title>
      <dc:creator>Ezile Mdodana</dc:creator>
      <pubDate>Sun, 19 Mar 2023 07:20:35 +0000</pubDate>
      <link>https://dev.to/ezilemdodana/suspense-for-data-fetching-react-3hie</link>
      <guid>https://dev.to/ezilemdodana/suspense-for-data-fetching-react-3hie</guid>
      <description>&lt;p&gt;React 16.6 has added a &amp;lt;&lt;strong&gt;Suspense&lt;/strong&gt;&amp;gt; component that lets you wait for some code to load and declaratively specify a loading state (like a spinner) while the data is still being fetched.&lt;br&gt;
&lt;strong&gt;_Suspense _&lt;/strong&gt;lets your components wait for something(data) before they can render.&lt;/p&gt;

&lt;p&gt;A common way to fetch data in React apps today is to use an effect, like this:&lt;/p&gt;

&lt;p&gt;// In a function component:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
  fetchSomething();
}, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This approach is called &lt;strong&gt;fetch-on-render&lt;/strong&gt; since it does not start fetching until after the component has rendered on screen, this approach normally leads async &lt;strong&gt;waterfall&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Let's take a look on a component fetching data with the traditional way, consider the components,  and :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Student() {
  const [student, setStudent] = useState(null);

  useEffect(() =&amp;gt; {
    getStudent().then(s =&amp;gt; setStudent(s));
  }, []);

  if (student === null) {
    return &amp;lt;p&amp;gt;Loading, please wait...&amp;lt;/p&amp;gt;;
  }
  return (
    &amp;lt;&amp;gt;
      &amp;lt;h1&amp;gt;{student.name}&amp;lt;/h1&amp;gt;
      &amp;lt;Text&amp;gt;{student.name} Subjects&amp;lt;/Text&amp;gt;
      &amp;lt;StudentSubjects /&amp;gt;
    &amp;lt;/&amp;gt;
  );
}

function StudentSubjects() {
  const [subjects, setSubjects] = useState(null);

  useEffect(() =&amp;gt; {
    getStudentSubjects().then(ss =&amp;gt; setSubjects(ss));
  }, []);

  if (subjects === null) {
    return &amp;lt;h2&amp;gt;Loading, please wait...&amp;lt;/h2&amp;gt;;
  }
  return (
    &amp;lt;ul&amp;gt;
      {subjects.map(subject =&amp;gt; (
        &amp;lt;li key={subject.id}&amp;gt;{subject.name}&amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What's happening here is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We start fetching a student&lt;/li&gt;
&lt;li&gt;We wait…&lt;/li&gt;
&lt;li&gt;We finish fetching student&lt;/li&gt;
&lt;li&gt;We start fetching student subjects&lt;/li&gt;
&lt;li&gt;We wait…&lt;/li&gt;
&lt;li&gt;We finish fetching student subjects&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If fetching a student takes three seconds, we’ll only start fetching the student subjects after three seconds! Remember our old friend, &lt;strong&gt;waterfall&lt;/strong&gt;? That’s a &lt;strong&gt;waterfall&lt;/strong&gt; right there: an unintentional sequence that should have been parallelized.&lt;/p&gt;

&lt;p&gt;Waterfalls are common in code that fetches data on render. They’re possible to solve, but as the product grows, many people prefer to use a solution that guards against this problem.&lt;/p&gt;

&lt;p&gt;Now, let's see how we can improve this by using &lt;strong&gt;&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This is not a Promise. It's a special object from the Suspense integration.
const resource = fetchProfileData();

function StudentDetails() {
  return (
    &amp;lt;Suspense fallback={&amp;lt;h1&amp;gt;Loading student...&amp;lt;/h1&amp;gt;}&amp;gt;
      &amp;lt;Student /&amp;gt;
      &amp;lt;Suspense fallback={&amp;lt;h1&amp;gt;Loading student subjects...&amp;lt;/h1&amp;gt;}&amp;gt;
        &amp;lt;StudentSubjects/&amp;gt;
      &amp;lt;/Suspense&amp;gt;
    &amp;lt;/Suspense&amp;gt;
  );
}

function Student() {
  // Try to read student info, although it might not have loaded yet
  const student = resource.student.read();
  return &amp;lt;h1&amp;gt;{student.name}&amp;lt;/h1&amp;gt;;
}

function StudentSubjects() {
  // attempt to read student subjects, although they might not have loaded yet
  const subjects = resource.subjects.read();
  return (
    &amp;lt;ul&amp;gt;
      {subjects.map(subject =&amp;gt; (
        &amp;lt;li key={subject.id}&amp;gt;{subject.name}&amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;strong&gt;Suspense&lt;/strong&gt;, here's what happens:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Start fetching&lt;/li&gt;
&lt;li&gt;Start rendering&lt;/li&gt;
&lt;li&gt;Finish fetching&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the traditional approach here's what was happening:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Start fetching&lt;/li&gt;
&lt;li&gt;Finish fetching&lt;/li&gt;
&lt;li&gt;Start rendering
We fetched data before we called setState.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With Suspense, we don’t wait for the response to come back before we start rendering on screen. We start rendering immediately after kicking off the network request.&lt;/p&gt;

&lt;p&gt;On the &lt;strong&gt;Suspense&lt;/strong&gt; component, the fallback is basically what is displayed while still loading, a spinner, maybe.&lt;/p&gt;

&lt;p&gt;Thank you very much for reading.&lt;br&gt;
Happy coding!🤓😎&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
