<?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 Abdelrahman Rezk on Medium]]></title>
        <description><![CDATA[Stories by Abdelrahman Rezk on Medium]]></description>
        <link>https://medium.com/@Abdelrahman_Rezk?source=rss-3f3aae186598------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8Fi1RyqqHi0aPxBfwbZRRA.png</url>
            <title>Stories by Abdelrahman Rezk on Medium</title>
            <link>https://medium.com/@Abdelrahman_Rezk?source=rss-3f3aae186598------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 06:57:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Abdelrahman_Rezk/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[Circuit Breaker Pattern: A Comprehensive Guide with Nest.JS Application]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/circuit-breaker-pattern-a-comprehensive-guide-with-nest-js-application-41300462d579?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/41300462d579</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Wed, 29 May 2024 12:44:49 GMT</pubDate>
            <atom:updated>2024-05-29T12:44:49.092Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UKcJqxcJIVFFlCF9hkf7cw.jpeg" /></figure><p>In modern microservices architectures, service reliability and fault tolerance are critical. The Circuit Breaker pattern is a design pattern used to detect failures and encapsulate the logic of preventing a failure from constantly recurring. In this article, we will implement the Circuit Breaker pattern in a NestJS application. We’ll walk through creating two projects: external to simulate an external server and circuit-breaker to test the Circuit Breaker implementation.</p><h3>What is the Circuit Breaker Pattern?</h3><p>The Circuit Breaker pattern is used to prevent an application from performing an operation that is likely to fail. It monitors the number of recent failures and determines when to “break” the circuit, stopping requests for a certain period. This prevents the system from being overwhelmed with failed requests and allows time for the underlying issue to be resolved.</p><h3>Why Do We Need It?</h3><ol><li><strong>Fail-Fast Behavior</strong>: The Circuit Breaker pattern ensures that the system fails fast and doesn’t waste resources on operations that are likely to fail.</li><li><strong>Improved Stability</strong>: By preventing repeated failures, it enhances the stability and resilience of the system.</li><li><strong>Graceful Degradation</strong>: Provides fallback functionality to handle failures gracefully, ensuring a better user experience.</li></ol><p>We’ll create two projects: external, which simulates an unreliable external service, and circuit-breaker, which implements the Circuit Breaker pattern to manage interactions with the external service. The external project randomly fails to demonstrate fault tolerance, while the circuit-breaker project showcases how to handle these failures gracefully. This setup highlights the importance of resilience in microservices architectures.</p><p>We will use an interceptor in Nest.JS to implement the Circuit Breaker pattern, managing service request failures and ensuring resilience.</p><h3>External Service</h3><ol><li><strong>Create a new NestJS project:</strong></li></ol><pre>nest new external<br>cd external</pre><p>2. Update app.controller.ts to randomly fail:</p><pre>import { Controller, Get, HttpException, HttpStatus } from &#39;@nestjs/common&#39;;<br><br>@Controller()<br>export class AppController {<br>  @Get()<br>  getData() {<br>    // Randomly fail to demonstrate the circuit breaker<br>    if (Math.random() &gt; 0.5) {<br>      throw new HttpException(<br>        &#39;Service Failure&#39;,<br>        HttpStatus.SERVICE_UNAVAILABLE,<br>      );<br>    }<br>    return { success: true, data: &#39;Here is your data!&#39; };<br>  }<br>}</pre><p>This controller simulates an external service that will randomly fails randomly.</p><p>3. Update the localhost port of the app to be 3001 in main.ts</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  await app.listen(3001);<br>}<br>bootstrap();</pre><h3>Circuit Breaker Setup</h3><ol><li><strong>Create a new NestJS project:</strong></li></ol><pre>nest new circuit-breaker<br>cd circuit-breaker</pre><p>2. <strong>Install the necessary dependencies:</strong></p><pre>npm install @nestjs/axios axios rxjs</pre><p>3. Create the Circuit Breaker code in src/common/interceptors/circuit-breaker.ts</p><p>First, we need to import necessary modules and define default configuration values for the Circuit Breaker.</p><pre>import { CallHandler, HttpException, HttpStatus } from &#39;@nestjs/common&#39;;<br>import { tap, Observable, throwError } from &#39;rxjs&#39;;<br>import { EventEmitter } from &#39;events&#39;;<br><br>// Default configuration values for the CircuitBreaker<br>const DEFAULT_SUCCESS_THRESHOLD = 3; // Number of successful requests before closing the circuit<br>const DEFAULT_FAILURE_THRESHOLD = 3; // Number of failed requests before opening the circuit<br>const DEFAULT_OPEN_TO_HALF_OPEN_WAIT_TIME = 60000; // Time to wait before trying to reset the circuit (in milliseconds)</pre><p>Next, we define an enum representing the possible states of the Circuit Breaker.</p><pre>// Enum representing the possible states of the circuit breaker<br>enum CircuitBreakerState {<br>  Closed, // Requests are allowed<br>  Open, // Requests are blocked<br>  HalfOpen, // A trial period to determine if the service has recovered<br>}</pre><p>We then define an interface for the options that can be passed to configure the Circuit Breaker.</p><ul><li><strong>Closed Circuit</strong>: The circuit allows all requests as the service is considered healthy.</li><li><strong>Open Circuit</strong>: The circuit blocks requests and returns fallback responses due to detected failures.</li><li><strong>Half-Open Circuit</strong>: The circuit allows a few test requests to check if the service has recovered before fully closing or reopening.</li></ul><pre>// Interface for the options that can be passed to configure the CircuitBreaker<br>interface CircuitBreakerOptions {<br>  successThreshold?: number; // Optional: number of successful requests needed to close the circuit<br>  failureThreshold?: number; // Optional: number of failed requests needed to open the circuit<br>  openToHalfOpenWaitTime?: number; // Optional: wait time before moving from open to half-open state<br>  fallback?: () =&gt; Observable&lt;any&gt;; // Optional: fallback function when the circuit is open<br>}</pre><p>We then create the CircuitBreaker class extending EventEmitter to handle events, This class is the core of the Circuit Breaker pattern. It manages the state, counts successes and failures, and decides whether to allow requests or not.</p><pre>// CircuitBreaker class extending EventEmitter to handle events<br>export class CircuitBreaker extends EventEmitter {<br>  private state = CircuitBreakerState.Closed; // Initial state is Closed<br>  private failureCount = 0; // Count of consecutive failures<br>  private successCount = 0; // Count of consecutive successes<br>  private lastError: Error; // The last error encountered<br>  private nextAttempt: number; // Timestamp for the next attempt when in Open state<br>  private options: CircuitBreakerOptions; // Configuration options</pre><p>We then add the constructor to initialize the CircuitBreaker with options. The constructor sets up the Circuit Breaker with the given options or default settings, making sure it works properly without any additional configuration.</p><pre>  // Constructor to initialize the CircuitBreaker with options<br>  constructor(options: CircuitBreakerOptions = {}) {<br>    super();<br>    // Set options with default values if not provided<br>    this.options = {<br>      successThreshold: options.successThreshold || DEFAULT_SUCCESS_THRESHOLD,<br>      failureThreshold: options.failureThreshold || DEFAULT_FAILURE_THRESHOLD,<br>      openToHalfOpenWaitTime:<br>        options.openToHalfOpenWaitTime || DEFAULT_OPEN_TO_HALF_OPEN_WAIT_TIME,<br>      fallback:<br>        options.fallback ||<br>        (() =&gt;<br>          throwError(<br>            () =&gt;<br>              new HttpException(<br>                &#39;Service unavailable. Please try again later.&#39;,<br>                HttpStatus.SERVICE_UNAVAILABLE,<br>              ),<br>          )),<br>    };<br>  }</pre><p>Next, we add the method to handle request execution, checking if the Circuit Breaker is in the Open state and managing state transitions.</p><p>The exec method manages the logic for deciding whether to allow a request to proceed or to return a fallback response based on the current state of the Circuit Breaker.</p><pre>  // Method to handle request execution<br>  exec(next: CallHandler) {<br>    // Check if the circuit breaker is in Open state<br>    if (this.state === CircuitBreakerState.Open) {<br>      // If the next attempt time has not been reached, emit failure and use fallback<br>      if (this.nextAttempt &gt; Date.now()) {<br>        this.emit(&#39;failure&#39;, this.lastError); // Emit failure event<br>        return this.options.fallback(); // Execute fallback function<br>      }<br>      // Transition to HalfOpen state if the wait time has elapsed<br>      this.state = CircuitBreakerState.HalfOpen;<br>    }<br><br>    // Handle the request and monitor its success or failure<br>    return next.handle().pipe(<br>      tap({<br>        next: () =&gt; this.handleSuccess(), // Call handleSuccess on success<br>        error: (error) =&gt; this.handleError(error), // Call handleError on error<br>      }),<br>    );<br>  }</pre><p>We then add a method to handle successful requests.<br>The handleSuccess method resets the failure count and, if the Circuit Breaker is in the HalfOpen state, increments the success count. If enough successes occur, it transitions back to the Closed state.</p><pre>  // Method to handle successful request<br>  private handleSuccess() {<br>    this.failureCount = 0; // Reset failure count on success<br>    // If in HalfOpen state, increment success count<br>    if (this.state === CircuitBreakerState.HalfOpen) {<br>      this.successCount++;<br>      // If success count reaches the threshold, close the circuit<br>      if (this.successCount &gt;= this.options.successThreshold) {<br>        this.successCount = 0;<br>        this.state = CircuitBreakerState.Closed;<br>        this.emit(&#39;closed&#39;); // Emit closed event<br>      }<br>    }<br>    this.emit(&#39;success&#39;); // Emit success event<br>  }</pre><p>Finally, we add a method to handle failed requests.<br>The handleError method increments the failure count and, if the count exceeds the threshold or the Circuit Breaker is in the HalfOpen state, transitions to the Open state, preventing further requests until the wait time has elapsed.</p><pre>  // Method to handle failed request<br>  private handleError(err: Error) {<br>    this.failureCount++; // Increment failure count on error<br>    // If failure count reaches the threshold or in HalfOpen state, open the circuit<br>    if (<br>      this.failureCount &gt;= this.options.failureThreshold ||<br>      this.state === CircuitBreakerState.HalfOpen<br>    ) {<br>      this.state = CircuitBreakerState.Open;<br>      this.lastError = err;<br>      this.nextAttempt = Date.now() + this.options.openToHalfOpenWaitTime;<br>      this.emit(&#39;open&#39;); // Emit open event<br>    }<br>    this.emit(&#39;failure&#39;, err); // Emit failure event<br>  }<br>}</pre><p>src/common/interceptors/circuit-breaker.ts full code</p><pre>import { CallHandler, HttpException, HttpStatus } from &#39;@nestjs/common&#39;;<br>import { tap, Observable, throwError } from &#39;rxjs&#39;;<br>import { EventEmitter } from &#39;events&#39;;<br><br>// Default configuration values for the CircuitBreaker<br>const DEFAULT_SUCCESS_THRESHOLD = 3;<br>const DEFAULT_FAILURE_THRESHOLD = 3;<br>const DEFAULT_OPEN_TO_HALF_OPEN_WAIT_TIME = 60000;<br><br>// Enum representing the possible states of the circuit breaker<br>enum CircuitBreakerState {<br>  Closed,<br>  Open,<br>  HalfOpen,<br>}<br><br>// Interface for the options that can be passed to configure the CircuitBreaker<br>interface CircuitBreakerOptions {<br>  successThreshold?: number;<br>  failureThreshold?: number;<br>  openToHalfOpenWaitTime?: number;<br>  fallback?: () =&gt; Observable&lt;any&gt;;<br>}<br><br>// CircuitBreaker class extending EventEmitter to handle events<br>export class CircuitBreaker extends EventEmitter {<br>  private state = CircuitBreakerState.Closed; // Initial state is Closed<br>  private failureCount = 0; // Count of consecutive failures<br>  private successCount = 0; // Count of consecutive successes<br>  private lastError: Error; // The last error encountered<br>  private nextAttempt: number; // Timestamp for the next attempt when in Open state<br>  private options: CircuitBreakerOptions; // Configuration options<br><br>  // Constructor to initialize the CircuitBreaker with options<br>  constructor(options: CircuitBreakerOptions = {}) {<br>    super();<br>    // Set options with default values if not provided<br>    this.options = {<br>      successThreshold: options.successThreshold || DEFAULT_SUCCESS_THRESHOLD,<br>      failureThreshold: options.failureThreshold || DEFAULT_FAILURE_THRESHOLD,<br>      openToHalfOpenWaitTime:<br>        options.openToHalfOpenWaitTime || DEFAULT_OPEN_TO_HALF_OPEN_WAIT_TIME,<br>      fallback:<br>        options.fallback ||<br>        (() =&gt;<br>          throwError(<br>            () =&gt;<br>              new HttpException(<br>                &#39;Service unavailable. Please try again later.&#39;,<br>                HttpStatus.SERVICE_UNAVAILABLE,<br>              ),<br>          )),<br>    };<br>  }<br><br>  // Method to handle request execution<br>  exec(next: CallHandler) {<br>    // Check if the circuit breaker is in Open state<br>    if (this.state === CircuitBreakerState.Open) {<br>      // If the next attempt time has not been reached, emit failure and use fallback<br>      if (this.nextAttempt &gt; Date.now()) {<br>        this.emit(&#39;failure&#39;, this.lastError); // Emit failure event<br>        return this.options.fallback(); // Execute fallback function<br>      }<br>      // Transition to HalfOpen state if the wait time has elapsed<br>      this.state = CircuitBreakerState.HalfOpen;<br>    }<br><br>    // Handle the request and monitor its success or failure<br>    return next.handle().pipe(<br>      tap({<br>        next: () =&gt; this.handleSuccess(), // Call handleSuccess on success<br>        error: (error) =&gt; this.handleError(error), // Call handleError on error<br>      }),<br>    );<br>  }<br><br>  // Method to handle successful request<br>  private handleSuccess() {<br>    this.failureCount = 0; // Reset failure count on success<br>    // If in HalfOpen state, increment success count<br>    if (this.state === CircuitBreakerState.HalfOpen) {<br>      this.successCount++;<br>      // If success count reaches the threshold, close the circuit<br>      if (this.successCount &gt;= this.options.successThreshold) {<br>        this.successCount = 0;<br>        this.state = CircuitBreakerState.Closed;<br>        this.emit(&#39;closed&#39;); // Emit closed event<br>      }<br>    }<br>    this.emit(&#39;success&#39;); // Emit success event<br>  }<br><br>  // Method to handle failed request<br>  private handleError(err: Error) {<br>    this.failureCount++; // Increment failure count on error<br>    // If failure count reaches the threshold or in HalfOpen state, open the circuit<br>    if (<br>      this.failureCount &gt;= this.options.failureThreshold ||<br>      this.state === CircuitBreakerState.HalfOpen<br>    ) {<br>      this.state = CircuitBreakerState.Open;<br>      this.lastError = err;<br>      this.nextAttempt = Date.now() + this.options.openToHalfOpenWaitTime;<br>      this.emit(&#39;open&#39;); // Emit open event<br>    }<br>    this.emit(&#39;failure&#39;, err); // Emit failure event<br>  }<br>}</pre><p>4. Create the Circuit Breaker Interceptor in src/common/interceptors/circuit-breaker.interceptor.ts</p><p>First, we need to import necessary modules and define the CircuitBreakerInterceptor class.</p><p>These imports are essential for creating the interceptor, handling HTTP exceptions, and integrating the Circuit Breaker functionality with the RxJS library.</p><pre>import {<br>  CallHandler,<br>  ExecutionContext,<br>  Injectable,<br>  NestInterceptor,<br>  HttpException,<br>  HttpStatus,<br>} from &#39;@nestjs/common&#39;;<br>import { Observable, of, throwError } from &#39;rxjs&#39;;<br>import { CircuitBreaker } from &#39;./circuit-breaker&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;</pre><p>We then define the CircuitBreakerInterceptor class and initialize a map to store circuit breakers for each handler.</p><p>The WeakMap is used to associate each handler method with its own CircuitBreaker instance, ensuring that circuit breaker state is maintained per method.</p><pre>@Injectable()<br>export class CircuitBreakerInterceptor implements NestInterceptor {<br>  private readonly circuitBreakerByHandler = new WeakMap&lt;<br>    // eslint-disable-next-line @typescript-eslint/ban-types<br>    Function,<br>    CircuitBreaker<br>  &gt;();</pre><p>Then we implement the intercept method to manage the circuit breaker logic for each handler.</p><pre>  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {<br>    const methodRef = context.getHandler();<br><br>    let circuitBreaker: CircuitBreaker;<br>    if (this.circuitBreakerByHandler.has(methodRef)) {<br>      circuitBreaker = this.circuitBreakerByHandler.get(methodRef);<br>    } else {<br>      circuitBreaker = new CircuitBreaker({<br>        successThreshold: 3,<br>        failureThreshold: 3,<br>        openToHalfOpenWaitTime: 60000,<br>        fallback: () =&gt; {<br>          // Throwing an HttpException with 503 status code<br>          throw new HttpException(<br>            &#39;Service unavailable. Please try again later.&#39;,<br>            HttpStatus.SERVICE_UNAVAILABLE,<br>          );<br>        },<br>      });<br>      this.circuitBreakerByHandler.set(methodRef, circuitBreaker);<br><br><br>    return circuitBreaker.exec(next).pipe(<br>      catchError((err) =&gt; {<br>        return throwError(<br>          () =&gt;<br>            new HttpException(<br>              &#39;Internal server error&#39;,<br>              HttpStatus.INTERNAL_SERVER_ERROR,<br>            ),<br>        );<br>      }),<br>    );<br>  }<br>}</pre><ul><li><strong>Method Reference</strong>: context.getHandler() gets the reference to the current method being intercepted.</li><li><strong>Circuit Breaker Retrieval/Initialization</strong>: Checks if a circuit breaker already exists for the method. If not, it initializes a new one with specified thresholds and fallback logic, then stores it in the WeakMap.</li><li><strong>Error Handling</strong>: Uses catchError to handle any errors that occur during the request, logging the error and throwing an internal server error response.</li></ul><p>circuit-breaker.interceptor.ts full code</p><pre>import {<br>  CallHandler,<br>  ExecutionContext,<br>  Injectable,<br>  NestInterceptor,<br>  HttpException,<br>  HttpStatus,<br>} from &#39;@nestjs/common&#39;;<br>import { Observable, of, throwError } from &#39;rxjs&#39;;<br>import { CircuitBreaker } from &#39;./circuit-breaker&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;<br><br>@Injectable()<br>export class CircuitBreakerInterceptor implements NestInterceptor {<br>  private readonly circuitBreakerByHandler = new WeakMap&lt;<br>    // eslint-disable-next-line @typescript-eslint/ban-types<br>    Function,<br>    CircuitBreaker<br>  &gt;();<br><br>  intercept(context: ExecutionContext, next: CallHandler): Observable&lt;any&gt; {<br>    const methodRef = context.getHandler();<br><br>    let circuitBreaker: CircuitBreaker;<br>    if (this.circuitBreakerByHandler.has(methodRef)) {<br>      circuitBreaker = this.circuitBreakerByHandler.get(methodRef);<br>    } else {<br>      circuitBreaker = new CircuitBreaker({<br>        successThreshold: 3,<br>        failureThreshold: 3,<br>        openToHalfOpenWaitTime: 60000,<br>        fallback: () =&gt; {<br>          // Throwing an HttpException with 503 status code<br>          throw new HttpException(<br>            &#39;Service unavailable. Please try again later.&#39;,<br>            HttpStatus.SERVICE_UNAVAILABLE,<br>          );<br>        },<br>      });<br>      this.circuitBreakerByHandler.set(methodRef, circuitBreaker);<br>    }<br><br>    return circuitBreaker.exec(next).pipe(<br>      catchError(() =&gt; {<br>        return throwError(<br>          () =&gt;<br>            new HttpException(<br>              &#39;Internal server error&#39;,<br>              HttpStatus.INTERNAL_SERVER_ERROR,<br>            ),<br>        );<br>      }),<br>    );<br>  }<br>}</pre><p>5. Modify AppService to call the external service in src/app.service.ts</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { HttpService } from &#39;@nestjs/axios&#39;;<br>import { firstValueFrom, catchError } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;<br><br>@Injectable()<br>export class AppService {<br>  constructor(private httpService: HttpService) {}<br><br>  getData() {<br>    // to log whether the request is made to the server<br>    console.log(`getData called at ${new Date()}`);<br><br>    const response = this.httpService.get(&#39;http://localhost:3001&#39;);<br>    return firstValueFrom(<br>      response.pipe(<br>        map((res) =&gt; res.data),<br>        catchError((err) =&gt; {<br>          throw new Error(&#39;Failed to fetch data from the service&#39;);<br>        }),<br>      ),<br>    );<br>  }<br>}</pre><p>This service uses the HttpService from @nestjs/axios to make HTTP requests to the external service. The firstValueFrom function converts the observable to a promise, and the catchError operator handles any errors that occur during the request.</p><p>6. Modify the AppController to use the Circuit Breaker interceptor in src/app.controller.ts</p><pre>import { Controller, Get, UseInterceptors } from &#39;@nestjs/common&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { CircuitBreakerInterceptor } from &#39;./common/interceptors/circuit-breaker/circuit-breaker.interceptor&#39;;<br><br>@Controller()<br>export class AppController {<br>  constructor(private readonly appService: AppService) {}<br><br>  @Get()<br>  @UseInterceptors(CircuitBreakerInterceptor)<br>  getData() {<br>    return this.appService.getData();<br>  }<br>}</pre><p>This controller uses the CircuitBreakerInterceptor to manage the circuit breaker state for the getData method. The UseInterceptors decorator applies the interceptor to the method.</p><p>7. Update the AppModule class to import HttpModule</p><pre>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 { HttpModule } from &#39;@nestjs/axios&#39;;<br><br>@Module({<br>  imports: [HttpModule],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>We will send 20 consecutive requests to the circuit-breaker service and observe the logs and responses:</p><pre>for i in {1..20}; do curl http://localhost:3000; echo &quot;&quot;; done</pre><p>Here is the App logs:</p><pre>getData called at Wed May 29 2024 15:25:56 GMT+0300 (Eastern European Summer Time)<br>getData called at Wed May 29 2024 15:25:57 GMT+0300 (Eastern European Summer Time)<br>getData called at Wed May 29 2024 15:25:57 GMT+0300 (Eastern European Summer Time)<br>getData called at Wed May 29 2024 15:25:57 GMT+0300 (Eastern European Summer Time)<br>getData called at Wed May 29 2024 15:25:57 GMT+0300 (Eastern European Summer Time)</pre><p>And the responses</p><pre>{&quot;statusCode&quot;:500,&quot;message&quot;:&quot;Internal server error&quot;}<br>{&quot;success&quot;:true,&quot;data&quot;:&quot;Here is your data!&quot;}<br>{&quot;statusCode&quot;:500,&quot;message&quot;:&quot;Internal server error&quot;}<br>{&quot;statusCode&quot;:500,&quot;message&quot;:&quot;Internal server error&quot;}<br>{&quot;statusCode&quot;:500,&quot;message&quot;:&quot;Internal server error&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}<br>{&quot;statusCode&quot;:503,&quot;message&quot;:&quot;Service unavailable. Please try again later.&quot;}</pre><p>As we notice here the circuit become open after the 5th request and no requests has been send to the external servers.</p><h3>Conclusion</h3><p>By following these steps, you have implemented a robust Circuit Breaker pattern in a NestJS application. This pattern helps improve the resilience and stability of your services by preventing repeated failures and allowing time for recovery. The detailed steps provided ensure that you can replicate this setup and adapt it to your specific use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41300462d579" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Worker Threads in NestJS: A Hands-On Guide with Fibonacci Example]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/understanding-worker-threads-in-nestjs-a-hands-on-guide-with-fibonacci-example-6f09998e9129?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f09998e9129</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Mon, 27 May 2024 12:58:17 GMT</pubDate>
            <atom:updated>2024-05-27T12:58:17.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*VUchFcxThMV4W4owjcy0Pg.jpeg" /></figure><p>Worker threads are a powerful feature in Node.js that allow for parallel execution of JavaScript code. This can significantly enhance the performance of your application by offloading CPU-intensive tasks to separate threads. In this article, we will explore worker threads in the context of a NestJS application, using the calculation of Fibonacci numbers as our example. We will cover three scenarios: without worker threads, with basic worker threads, and with the Piscina package to handle multiple workers.</p><h3>Why Use Worker Threads?</h3><p>Node.js operates on a single-threaded event loop, which makes it efficient for I/O-bound operations but less effective for CPU-bound tasks. When the event loop is blocked by a heavy computation, it affects the performance of the entire application. Worker threads solve this problem by enabling concurrent execution of tasks in separate threads, thus preventing the main thread from being blocked.</p><h3>Prerequisites</h3><p>Before we start, make sure you have Node.js and NestJS installed. If not, you can install them using the following command:</p><pre>npm install -g @nestjs/cli</pre><p>Additionally, ensure your tsconfig.json file includes &quot;esModuleInterop&quot;: true. This setting allows TypeScript to correctly handle imports from CommonJS modules.</p><p>Let’s create a new NestJS project:</p><pre>nest new nest-worker-threads<br>cd nest-worker-threads</pre><h3>Scenario 1: Without Worker Threads</h3><h4>Step 1: Create Fibonacci Module</h4><p>Generate the Fibonacci Module using the Nest CLI:</p><pre>nest generate module fibonacci</pre><h4>Step 2: Create Fibonacci Service</h4><p>Generate the Fibonacci service using the Nest CLI:</p><pre>nest generate service fibonacci</pre><p>Update the generated fibonacci.service.ts and implement the fibonacci function:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class FibonacciService {<br>   // Synchronous Fibonacci calculation<br>  calculateFibonacciSync(n: number): number {<br>    if (n &lt;= 1) return n;<br>    return (<br>      this.calculateFibonacciSync(n - 1) + this.calculateFibonacciSync(n - 2)<br>    );<br>}</pre><h4>Step 3: Create Fibonacci Controller</h4><p>Generate the Fibonacci controller using the Nest CLI:</p><pre>nest generate controller fibonacci</pre><p>Update the generated fibonacci.controller.ts file:</p><pre>import { Controller, Get, Query } from &#39;@nestjs/common&#39;;<br>import { FibonacciService } from &#39;./fibonacci.service&#39;;<br><br>@Controller(&#39;fibonacci&#39;)<br>export class FibonacciController {<br>  constructor(private readonly fibonacciService: FibonacciService) {}<br><br>  // Endpoint to calculate Fibonacci synchronously<br>  @Get(&#39;sync&#39;)<br>  calculateSync(@Query(&#39;n&#39;) n: string): number {<br>    return this.fibonacciService.calculateFibonacciSync(parseInt(n, 10));<br>  }<br>}</pre><h4>Testing Without Worker Threads</h4><p>Access the Fibonacci route at http://localhost:3000/fibonacci/sync?n=40 and the Hello World route at http://localhost:3000. Notice that while the Fibonacci calculation is running, the Hello World route is slow or unresponsive, this is because our app is single threaded and all the thread is dedicated for fibonacci calculation without being able to accept requests until the thread is freed, sure it’s bad for our app performance so in the next two scenarios will try to overcome this limitation.</p><h3>Scenario 2: With Worker Threads</h3><p>Next, we’ll use worker threads to offload the Fibonacci calculation to a separate thread.</p><h4>Step 1: Create worker thread code file</h4><p>We will create new code file that calculates Fibonacci numbers based on input received from the main thread and sends the result back to the main thread. it uses the worker_threads module in Node.js to handle the communication between the main thread and the worker thread.</p><pre>// src/fibonacci/fibonacci.worker.ts<br>import { parentPort } from &#39;worker_threads&#39;;<br><br>// Function to calculate Fibonacci number<br>function fib(n: number): number {<br>  if (n &lt; 2) return n;<br>  return fib(n - 1) + fib(n - 2);<br>}<br><br>// Event listener for messages from the main thread<br>parentPort?.on(&#39;message&#39;, ({ n, id }) =&gt; {<br>  const result = fib(n);<br>  // Send the result back to the main thread<br>  parentPort.postMessage({ result, id });<br>});</pre><h4>Code Explanation</h4><p>1. Importing parentPort:</p><ul><li>The parentPort object is imported from the worker_threads module. This object represents the communication channel between the main thread and the worker thread.</li></ul><p>2. Listening for Messages from the Main Thread:</p><ul><li>The parentPort.on(&#39;message&#39;, callback) sets up an event listener to handle messages sent from the main thread. When a message is received, the provided callback function is executed.</li><li>The callback function receives an object containing n (the input number) and id (a unique identifier for the task).</li></ul><p>3. Processing the Message:</p><ul><li>Inside the callback function, the Fibonacci number is calculated by calling the fib function with the input number n.</li><li>Once the calculation is complete, the result is sent back to the main thread using parentPort.postMessage({ result, id }). The message includes both the result and the unique ID to correlate the response with the request.</li></ul><h4>Step 2: Create worker thread host file</h4><p>We will createFibonacciWorkerHost class, it’s a service that manages the worker thread. It leverages RxJS to handle the communication between the main thread and the worker thread in a reactive manner.</p><pre>// src/fibonacci/fibonacci-worker.host.ts<br>import {<br>  Injectable,<br>  OnApplicationBootstrap,<br>  OnApplicationShutdown,<br>} from &#39;@nestjs/common&#39;; // Importing necessary decorators and interfaces from NestJS<br>import { randomUUID } from &#39;crypto&#39;; // Importing randomUUID function to generate unique IDs<br>import { join } from &#39;path&#39;; // Importing join function to create file paths<br>import { filter, firstValueFrom, fromEvent, map, Observable } from &#39;rxjs&#39;; // Importing RxJS operators and functions for reactive programming<br>import { Worker } from &#39;worker_threads&#39;; // Importing Worker class to create and manage worker threads<br><br>@Injectable()<br>export class FibonacciWorkerHost<br>  implements OnApplicationBootstrap, OnApplicationShutdown<br>{<br>  private worker: Worker; // Worker instance for managing the worker thread<br>  private messages$: Observable&lt;{ id: string; result: number }&gt;; // Observable to handle messages from the worker thread<br><br>  // Lifecycle hook executed when the application starts<br>  onApplicationBootstrap() {<br>    // Initializing the worker thread with the specified script<br>    this.worker = new Worker(join(__dirname, &#39;fibonacci.worker.js&#39;));<br>    // Creating an observable from the worker&#39;s message events<br>    this.messages$ = fromEvent(this.worker, &#39;message&#39;) as Observable&lt;{<br>      id: string;<br>      result: number;<br>    }&gt;;<br>  }<br><br>  // Lifecycle hook executed when the application shuts down<br>  async onApplicationShutdown() {<br>    // Terminating the worker thread<br>    this.worker.terminate();<br>  }<br><br>  // Method to send a task to the worker thread and get the result<br>  run(n: number) {<br>    const uniqueId = randomUUID(); // Generating a unique ID for the task<br>    // Sending a message to the worker thread with the input number and unique ID<br>    this.worker.postMessage({ n, id: uniqueId });<br><br>    // Returning a promise that resolves with the result of the Fibonacci calculation<br>    return firstValueFrom(<br>      // Convert the observable to a promise<br>      this.messages$.pipe(<br>        // Filter messages to only include those with the matching unique ID<br>        filter(({ id }) =&gt; id === uniqueId),<br>        // Extract the result from the message<br>        map(({ result }) =&gt; result),<br>      ),<br>    );<br>  }<br>}</pre><p>The FibonacciWorkerHost class in the main thread interacts with the fibonacci.worker.ts script in the worker thread. Here&#39;s a step-by-step explanation of how this interaction works:</p><p>1. Initializing the Worker</p><pre>onApplicationBootstrap() {<br>  this.worker = new Worker(join(__dirname, &#39;fibonacci.worker.js&#39;));<br>  this.messages$ = fromEvent(this.worker, &#39;message&#39;) as Observable&lt;{<br>    id: string;<br>    result: number;<br>  }&gt;;<br>}</pre><ul><li>When the application starts (onApplicationBootstrap lifecycle hook), a new worker thread is created by instantiating the Worker class with the path to the fibonacci.worker.js script.</li><li>An RxJS observable (messages$) is created from the worker&#39;s message events using fromEvent. This observable will emit objects containing the id and result when the worker thread sends a message back to the main thread.</li></ul><p>2. Sending a Task to the Worker</p><pre>run(n: number) {<br>  const uniqueId = randomUUID(); // Generate a unique ID for the task<br>  this.worker.postMessage({ n, id: uniqueId }); // Send the task to the worker thread<br><br>  return firstValueFrom(<br>    this.messages$.pipe(<br>      filter(({ id }) =&gt; id === uniqueId), // Filter messages by unique ID<br>      map(({ result }) =&gt; result), // Extract the result<br>    ),<br>  );<br>}</pre><ul><li>The run method is called with the input number n.</li><li>A unique ID is generated using randomUUID to correlate the request with the response.</li><li>A message containing the input number n and the unique ID is sent to the worker thread using this.worker.postMessage({ n, id: uniqueId }).</li></ul><p>3. Receiving the Result from the Worker</p><ul><li>The worker thread processes the message, calculates the Fibonacci number, and sends the result back to the main thread using parentPort.postMessage({ result, id }).</li><li>The main thread receives this message, and it is emitted by the messages$ observable.</li></ul><p>4. Handling the Result in the Main Thread</p><pre>return firstValueFrom(<br>  this.messages$.pipe(<br>    filter(({ id }) =&gt; id === uniqueId), // Filter messages by unique ID<br>    map(({ result }) =&gt; result), // Extract the result<br>  ),<br>);</pre><ul><li>The run method converts the messages$ observable into a promise using firstValueFrom.</li><li>The observable pipeline filters messages to include only those with the matching unique ID using filter(({ id }) =&gt; id === uniqueId).</li><li>The result is extracted from the message using map(({ result }) =&gt; result).</li><li>The promise resolves with the result of the Fibonacci calculation, which can then be returned to the caller.</li></ul><p>This setup ensures that the Fibonacci calculation is offloaded to a worker thread, allowing the main thread to remain responsive and handle other tasks concurrently. The use of RxJS provides a clean and reactive way to handle the asynchronous communication between the main thread and the worker thread.</p><h4>Step 3: Update Fibonacci Service</h4><p>Update the fibonacci.service.ts to use worker threads by adding calculateFibonacciWorker function</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { FibonacciWorkerHost } from &#39;./fibonacci-worker.host&#39;;<br>import Piscina from &#39;piscina&#39;;<br>import { resolve } from &#39;path&#39;;<br><br>@Injectable()<br>export class FibonacciService {<br>  constructor(private readonly fibonacciWorkerHost: FibonacciWorkerHost) {}<br><br>  // Synchronous Fibonacci calculation<br>  calculateFibonacciSync(n: number): number {<br>    if (n &lt;= 1) return n;<br>    return (<br>      this.calculateFibonacciSync(n - 1) + this.calculateFibonacciSync(n - 2)<br>    );<br>  }<br><br>  // Asynchronous Fibonacci calculation using worker threads<br>  calculateFibonacciWorker(n: number): Promise&lt;number&gt; {<br>    return this.fibonacciWorkerHost.run(n);<br>  }<br><br> <br>}</pre><h4>Step 4: Update the fibonacci.controller.ts file to use the worker thread implementation:</h4><pre>import { Controller, Get, Query } from &#39;@nestjs/common&#39;;<br>import { FibonacciService } from &#39;./fibonacci.service&#39;;<br>import { FibonacciWorkerHost } from &#39;./fibonacci-worker.host&#39;;<br><br>@Controller(&#39;fibonacci&#39;)<br>export class FibonacciController {<br>  constructor(<br>    private readonly fibonacciService: FibonacciService,<br>    private readonly fibonacciWorkerHost: FibonacciWorkerHost,<br>  ) {}<br><br>  // Endpoint to calculate Fibonacci synchronously<br>  @Get(&#39;sync&#39;)<br>  calculateSync(@Query(&#39;n&#39;) n: string): number {<br>    return this.fibonacciService.calculateFibonacciSync(parseInt(n, 10));<br>  }<br><br>  // Endpoint to calculate Fibonacci using worker threads<br>  @Get(&#39;worker&#39;)<br>  async calculateWorker(@Query(&#39;n&#39;) n: 10) {<br>    return this.fibonacciService.calculateFibonacciWorker(n);<br>  }<br>}</pre><h4>Testing With Worker Threads</h4><p>Access the Fibonacci route at <a href="http://localhost:3000/fibonacci/worker">http://localhost:3000/fibonacci</a>/worker?n=40 and the Hello World route at http://localhost:3000. Notice the Hello World route remains responsive even when the Fibonacci calculation is running.<br>But accessing the Fibonacci route at <a href="http://localhost:3000/fibonacci/worker">http://localhost:3000/fibonacci</a>/worker?n=1 while Fibonacci(40) request still running will delay the Fibonacci(1) until Fibonacci(40) being resolved, this is because we are using basic single worker thread, as you guessed it’s not the best practice as we may need to perform multiple calculations using workers in parallel.</p><h3>Scenario 3: Using Piscina for Multiple Workers</h3><p>Piscina is a worker pool library that makes it easy to manage multiple workers efficiently.</p><h4>Step 1: Install Piscina</h4><pre>npm install piscina</pre><h4>Step 2: Create Piscina Worker Script</h4><p>For piscina we don’t need messages event listener instead we just need a simple export of the fibonacci function</p><pre>// src/fibonacci/fibonacci.worker.pascina.ts<br>function fib(n: number): number {<br>  if (n &lt; 2) return n;<br>  return fib(n - 1) + fib(n - 2);<br>}<br><br>module.exports = (n: number) =&gt; {<br>  return fib(n);<br>};</pre><h4>Step 2: Update Fibonacci Service</h4><p>Update fibonacci.service.ts to use Piscina:</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { FibonacciWorkerHost } from &#39;./fibonacci-worker.host&#39;;<br>import Piscina from &#39;piscina&#39;; // Importing Piscina for managing worker pools<br>import { resolve } from &#39;path&#39;; // Importing resolve function to create file paths<br><br>@Injectable()<br>export class FibonacciService {<br>  constructor(private readonly fibonacciWorkerHost: FibonacciWorkerHost) {}<br>  // Initializing Piscina with the path to the Piscina worker script<br>  fibonacciWorkerPiscina = new Piscina({<br>    filename: resolve(__dirname, &#39;fibonacci.worker.piscina.js&#39;),<br>  });<br><br>  // Synchronous Fibonacci calculation<br>  calculateFibonacciSync(n: number): number {<br>    if (n &lt;= 1) return n;<br>    return (<br>      this.calculateFibonacciSync(n - 1) + this.calculateFibonacciSync(n - 2)<br>    );<br>  }<br><br>  // Asynchronous Fibonacci calculation using worker threads<br>  calculateFibonacciWorker(n: number): Promise&lt;number&gt; {<br>    return this.fibonacciWorkerHost.run(n);<br>  }<br><br>  // Asynchronous Fibonacci calculation using Piscina<br>  calculateFibonacciPiscina(n: number): Promise&lt;number&gt; {<br>    return this.fibonacciWorkerPiscina.run(n); // Delegate the task to the Piscina worker pool<br>  }<br>}</pre><h4>Step 3: Update Fibonacci Controller</h4><p>Add piscina route to Fibonacci Controller</p><pre>import { Controller, Get, Query } from &#39;@nestjs/common&#39;;<br>import { FibonacciService } from &#39;./fibonacci.service&#39;;<br>import { FibonacciWorkerHost } from &#39;./fibonacci-worker.host&#39;;<br><br>@Controller(&#39;fibonacci&#39;)<br>export class FibonacciController {<br>  constructor(<br>    private readonly fibonacciService: FibonacciService,<br>    private readonly fibonacciWorkerHost: FibonacciWorkerHost,<br>  ) {}<br><br>  // Endpoint to calculate Fibonacci synchronously<br>  @Get(&#39;sync&#39;)<br>  calculateSync(@Query(&#39;n&#39;) n: string): number {<br>    return this.fibonacciService.calculateFibonacciSync(parseInt(n, 10));<br>  }<br><br>  // Endpoint to calculate Fibonacci using worker threads<br>  @Get(&#39;worker&#39;)<br>  async calculateWorker(@Query(&#39;n&#39;) n: 10) {<br>    return this.fibonacciService.calculateFibonacciWorker(n);<br>  }<br><br>  @Get(&#39;piscina&#39;)<br>  async calculateWorkerPiscina(@Query(&#39;n&#39;) n: 10) {<br>    return this.fibonacciService.calculateFibonacciPiscina(n);<br>  }<br>}</pre><h4>Testing With Piscina</h4><p>Access the Fibonacci route at <a href="http://localhost:3000/fibonacci/worker">http://localhost:3000/fibonacci</a>/piscina?n=40 and <a href="http://localhost:3000/fibonacci/worker">http://localhost:3000/fibonacci</a>/piscina?n=1 <br>You will notice that the fibonacci(1) calculation does not need to wait for the first worker to end, this is because piscina manages multiple workers in parallel.</p><h3>Conclusion</h3><p>In this article, we’ve explored the use of worker threads in a NestJS application to handle CPU-intensive tasks like calculating Fibonacci numbers. We demonstrated the limitations of single-threaded execution, implemented worker threads for parallel processing, and used the Piscina package to manage multiple workers efficiently. This approach ensures that your application remains responsive even when performing heavy computations.</p><p>By leveraging worker threads, you can significantly improve the performance and scalability of your Node.js applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f09998e9129" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing the IoC Container in NestJS: A Practical Logging Library Example]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/accessing-the-ioc-container-in-nestjs-a-practical-logging-library-example-7b34a22fe72d?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b34a22fe72d</guid>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ioc-container]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Sun, 26 May 2024 21:25:01 GMT</pubDate>
            <atom:updated>2024-05-26T21:25:01.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nJGa1ow0keN8E8ZbErnVzw.jpeg" /></figure><p>In this detailed tutorial, we’ll create a NestJS project and build a logging library that dynamically discovers and logs method calls for all providers and controllers marked with specific metadata. This example will help you understand how to access the Inversion of Control (IoC) container, introspect registered providers and controllers, and apply dynamic behavior using custom decorators.</p><h3>What is an IoC Container?</h3><p>The IoC container in NestJS manages the creation, configuration, and lifecycle of application components, allowing for dependency injection where the container automatically provides dependencies to classes that need them.</p><h3>Why Access the IoC Container?</h3><p>Accessing the IoC container is crucial for:</p><ol><li>Introspection: To inspect all registered providers and controllers.</li><li>Dynamic Behavior: To apply dynamic behavior, such as logging, monitoring, or modifying behavior based on metadata.</li><li>Generic Libraries: To build libraries that need to interact with various application components dynamically.</li></ol><h3>Step-by-Step Guide</h3><p>We’ll go through the steps to create a NestJS project and build a dynamic logging library.</p><h4>Step 1: Setting Up the NestJS Project</h4><ol><li>Install the NestJS CLI:</li></ol><pre>npm install -g @nestjs/cli</pre><p>2. Create a New NestJS Project:</p><pre>nest new logging-library<br>cd logging-library</pre><p>3. Install Required Dependencies:</p><pre>npm install @nestjs/core @nestjs/common @nestjs-plus/discovery</pre><h4>Step 2: Creating the LoggerService</h4><p>Create a LoggerService that uses NestJS lifecycle hooks to set up and clear method call logging dynamically.</p><ol><li>Generate the LoggerService:</li></ol><pre>nest generate service logger</pre><p>2. Implement the LoggerService:</p><pre>// src/logger/logger.service.ts<br>import { Injectable, OnApplicationBootstrap, OnApplicationShutdown } from &#39;@nestjs/common&#39;;<br>import { DiscoveryService, Reflector, MetadataScanner } from &#39;@nestjs/core&#39;;<br><br>@Injectable()<br>export class LoggerService implements OnApplicationBootstrap, OnApplicationShutdown {<br>  // Map to store original methods to restore them on shutdown<br>  private readonly originals: Map&lt;any, any&gt; = new Map();<br><br>  constructor(<br>    // DiscoveryService is used to find all providers and controllers<br>    private readonly discoveryService: DiscoveryService,<br>    // Reflector is used to read metadata from classes and methods<br>    private readonly reflector: Reflector,<br>    // MetadataScanner is used to scan class prototypes for method names<br>    private readonly metadataScanner: MetadataScanner<br>  ) {}<br><br>  // Lifecycle hook that runs after all modules are initialized<br>  onApplicationBootstrap() {<br>    // Get all providers (including controllers) in the application<br>    const providers = this.discoveryService.getProviders();<br>    providers.forEach((wrapper) =&gt; {<br>      // Get the instance (actual object) of the provider<br>      const { instance } = wrapper;<br>      // Get the prototype (methods and properties shared across all instances) of the provider<br>      const prototype = instance &amp;&amp; Object.getPrototypeOf(instance);<br>      // Skip if instance or prototype is not available<br>      if (!instance || !prototype) {<br>        return;<br>      }<br>      // Check if the class is marked with @Loggable<br>      const isLoggable = this.reflector.get(&#39;LOGGABLE_KEY&#39;, instance.constructor) ?? false;<br>      if (!isLoggable) {<br>        return;<br>      }<br>      // Get all method names from the class prototype<br>      const methodKeys = this.metadataScanner.getAllMethodNames(prototype);<br>      methodKeys.forEach((methodKey) =&gt; {<br>        // Get the method by name<br>        const method = instance[methodKey];<br>        // Check if the property is a function (method)<br>        if (typeof method === &#39;function&#39;) {<br>          // Store the original method<br>          this.originals.set(method, method.bind(instance));<br>          // Replace the original method with a logging wrapper<br>          instance[methodKey] = (...args: any[]) =&gt; {<br>            console.log(`Calling ${methodKey} with args:`, args);<br>            return this.originals.get(method)(...args);<br>          };<br>        }<br>      });<br>    });<br>  }<br><br>  // Lifecycle hook that runs before the application shuts down<br>  onApplicationShutdown(signal?: string) {<br>    // Restore all original methods<br>    this.originals.forEach((original, method) =&gt; {<br>      method = original;<br>    });<br>    // Clear the map of original methods<br>    this.originals.clear();<br>  }<br>}</pre><ul><li>Instance: The actual object created by the IoC container. This is the live object that you interact with in your application.</li><li>Prototype: The blueprint for the object. It contains the methods and properties that are shared across all instances of the class. Using the prototype, you can introspect and modify the behavior of class methods dynamically.</li></ul><h3>Detailed Explanation of the Logging Method</h3><p>Let’s dive deeper into the part of the code where we dynamically wrap the methods with logging functionality:</p><pre>methodKeys.forEach((methodKey) =&gt; {<br>  // Get the method by name<br>  const method = instance[methodKey];<br>  // Check if the property is a function (method)<br>  if (typeof method === &#39;function&#39;) {<br>    // Store the original method<br>    this.originals.set(method, method.bind(instance));<br>    // Replace the original method with a logging wrapper<br>    instance[methodKey] = (...args: any[]) =&gt; {<br>      console.log(`Calling ${methodKey} with args:`, args);<br>      return this.originals.get(method)(...args);<br>    };<br>  }<br>});</pre><h4>Step-by-Step Breakdown</h4><ol><li>Iterate Over Method Keys:</li></ol><pre>methodKeys.forEach((methodKey) =&gt; {</pre><ul><li>methodKeys: An array of all method names in the prototype of the provider.</li></ul><p>2. Get the Method by Name:</p><pre>const method = instance[methodKey];</pre><ul><li>instance[methodKey]: Accesses the method on the instance by its name (key).</li><li>method: Holds the reference to the actual method function.</li></ul><p>3. Check if the Property is a Function:</p><pre>if (typeof method === &#39;function&#39;) {</pre><ul><li>Ensures that the property is indeed a function and not some other type of property (like a variable).</li></ul><p>4. Store the Original Method:</p><pre>this.originals.set(method, method.bind(instance));</pre><ul><li>this.originals: A Map object to store the original method references.</li><li>set(method, method.bind(instance)): Stores the method bound to the instance to maintain the correct context (this) when the method is called.</li></ul><p>5. Replace the Original Method with a Logging Wrapper:</p><pre>instance[methodKey] = (...args: any[]) =&gt; {<br>  console.log(`Calling ${methodKey} with args:`, args);<br>  return this.originals.get(method)(...args);<br>};</pre><ul><li>instance[methodKey]: Replaces the original method with a new function.</li><li>(...args: any[]) =&gt; { ... }: A new function that:</li><li>Logs the method call and its arguments.</li><li>Calls the original method using the stored reference in this.originals.</li></ul><h3>Example in Practice</h3><p>Suppose you have a UserService class with methods createUser and deleteUser:</p><pre>@Loggable<br>@Injectable()<br>export class UserService {<br>  createUser(name: string) {<br>    console.log(`User ${name} created.`);<br>  }<br><br>  deleteUser(id: number) {<br>    console.log(`User with id ${id} deleted.`);<br>  }<br>}</pre><p>When the LoggerService is initialized, it will:</p><ol><li>Discover the UserService provider.</li><li>Check if the UserService is marked with @Loggable.</li><li>For each method in UserService (like createUser and deleteUser)<br>- Store the original method.<br>- Replace the method with a new function that logs the call and arguments before invoking the original method</li></ol><h4>Step 3: Defining Custom Decorators</h4><p>To mark classes and methods for logging, we define a @Loggable decorator.</p><p>Create the Decorator:</p><pre>// src/logger/loggable.decorator.ts<br>import { SetMetadata } from &#39;@nestjs/common&#39;;<br><br>// Key for the loggable metadata<br>export const LOGGABLE_KEY = &#39;LOGGABLE_KEY&#39;;<br>// Loggable decorator to mark classes for logging<br>export const Loggable: ClassDecorator = SetMetadata(LOGGABLE_KEY, true);</pre><h4>Step 4: Using the Custom Decorators</h4><p>Use the @Loggable decorator in a service class to create methods that should be logged.</p><ol><li>Create a Service:</li></ol><pre>nest generate service user</pre><p>2. Implement the UserService:</p><pre>// src/user/user.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { Loggable } from &#39;../logger/loggable.decorator&#39;;<br><br>// Mark the UserService class for logging<br>@Loggable<br>@Injectable()<br>export class UserService {<br>  // Method to create a user<br>  createUser(name: string) {<br>    console.log(`User ${name} created.`);<br>  }<br><br>  // Method to delete a user<br>  deleteUser(id: number) {<br>    console.log(`User with id ${id} deleted.`);<br>  }<br>}</pre><p>3. Create a UserController to Test the Logging:</p><pre>nest generate controller user</pre><p>4. Implement the UserController:</p><pre>// src/user/user.controller.ts<br>import { Controller, Post, Body, Delete, Param } from &#39;@nestjs/common&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Controller(&#39;users&#39;)<br>export class UserController {<br>  constructor(private readonly userService: UserService) {}<br><br>  @Post()<br>  createUser(@Body(&#39;name&#39;) name: string) {<br>    return this.userService.createUser(name);<br>  }<br><br>  @Delete(&#39;:id&#39;)<br>  deleteUser(@Param(&#39;id&#39;) id: number) {<br>    return this.userService.deleteUser(id);<br>  }<br>}</pre><p>5. Step 5: Integrate LoggerService in AppModule</p><p>Ensure that the LoggerService and UserController are included in your application&#39;s module.</p><p>Update AppModule:</p><pre>// src/app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { DiscoveryModule } from &#39;@nestjs/core&#39;;<br>import { LoggerService } from &#39;./logger/logger.service&#39;;<br>import { UserService } from &#39;./user/user.service&#39;;<br>import { UserController } from &#39;./user/user.controller&#39;;<br><br>@Module({<br>  imports: [DiscoveryModule],<br>  providers: [LoggerService, UserService],<br>  controllers: [UserController],<br>})<br>export class AppModule {<br>  // Inject LoggerService to initialize it on application start<br>  constructor(private readonly loggerService: LoggerService) {}<br>}</pre><h3>Step 6: Testing the Logging</h3><p>You can use curl to test the endpoints and see the logging in action.</p><ol><li>Create a User:</li></ol><pre>curl -X POST http://localhost:3000/users -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;name&quot;: &quot;John Doe&quot;}&#39;</pre><p>2. Delete a User:</p><pre>curl -X DELETE http://localhost:3000/users/1</pre><h3>Output</h3><pre>Calling createUser with args: [ &#39;John Doe&#39; ]<br>User John Doe created.<br>Calling deleteUser with args: [ &#39;1&#39; ]<br>User with id 1 deleted.</pre><h3>Summary</h3><p>By following these steps, we created a NestJS project and built a logging library that dynamically logs method calls for all providers and controllers marked with specific metadata. This tutorial demonstrated how to access the IoC container in NestJS to introspect registered providers and controllers and apply dynamic behavior.</p><p>By leveraging custom decorators and metadata reflection, we created a flexible system for logging method calls, showcasing how to use NestJS’s powerful IoC container for advanced use cases. This approach can be extended to build various generic and integration libraries that need to interact dynamically with different parts of a NestJS application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b34a22fe72d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in NestJS: A Comprehensive Guide with Examples]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/dependency-injection-in-nestjs-a-comprehensive-guide-with-examples-ea0fe4be1256?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea0fe4be1256</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Sun, 26 May 2024 18:08:32 GMT</pubDate>
            <atom:updated>2024-05-26T18:08:32.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70aKhFf9LzCAISxwlC8O9g.gif" /></figure><p>Dependency Injection (DI) is a design pattern that promotes loose coupling and enhances the testability and maintainability of applications. NestJS, a progressive Node.js framework, leverages DI to manage the dependencies within an application efficiently. In this article, we’ll explore the concept of DI in NestJS and provide practical examples to illustrate its implementation, along with its benefits for memory efficiency and potential disadvantages.</p><h3>What is Dependency Injection?</h3><p>Dependency Injection involves the process of supplying a class with its dependencies from external sources rather than creating them internally. This pattern allows for greater modularity and flexibility, making it easier to manage dependencies and conduct unit testing.</p><h3>Why Use Dependency Injection in NestJS?</h3><ol><li>Separation of Concerns: DI separates the creation of a class’s dependencies from its behavior, leading to cleaner and more maintainable code.</li><li>Testability: Classes that use DI are easier to test because their dependencies can be mocked or replaced with test-specific implementations.</li><li>Flexibility and Scalability: DI allows for easier swapping of implementations and promotes the reuse of common services across different parts of the application.</li><li>Memory Efficiency: DI can lead to improved memory efficiency by managing the lifecycle of dependencies, ensuring that only one instance of each dependency is created and shared across the application.</li></ol><h3>Implementing Dependency Injection in NestJS</h3><p>NestJS uses a built-in DI system inspired by Angular, which provides decorators and metadata to declare dependencies and manage their lifecycle.</p><h4>Step-by-Step Guide</h4><p>1. Creating a Service</p><p>Services are fundamental building blocks in NestJS, used to encapsulate business logic. To create a service, use the @Injectable() decorator:</p><pre>// src/services/users.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class UsersService {<br>  private readonly users = [<br>    { id: 1, name: &#39;John Doe&#39; },<br>    { id: 2, name: &#39;Jane Doe&#39; },<br>  ];<br><br>  findAll() {<br>    return this.users;<br>  }<br><br>  findOne(id: number) {<br>    return this.users.find(user =&gt; user.id === id);<br>  }<br>}</pre><p>2. Injecting the Service into a Controller</p><p>Controllers handle incoming requests and return responses. To use the UsersService in a controller, inject it via the constructor:</p><pre>// src/controllers/users.controller.ts<br>import { Controller, Get, Param } from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;../services/users.service&#39;;<br><br>@Controller(&#39;users&#39;)<br>export class UsersController {<br>  constructor(private readonly usersService: UsersService) {}<br><br>  @Get()<br>  findAll() {<br>    return this.usersService.findAll();<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  findOne(@Param(&#39;id&#39;) id: string) {<br>    return this.usersService.findOne(+id);<br>  }<br>}</pre><p>3. Registering the Service and Controller in a Module</p><p>Modules in NestJS serve as organizational units for related components. Register the UsersService and UsersController in a module:</p><pre>// src/modules/users.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;../services/users.service&#39;;<br>import { UsersController } from &#39;../controllers/users.controller&#39;;<br><br>@Module({<br>  controllers: [UsersController],<br>  providers: [UsersService],<br>})<br>export class UsersModule {}</pre><p>4. Using Dependency Injection for Custom Providers</p><p>Custom providers can be used to inject more complex dependencies. For instance, you might need to inject a configuration object or a factory:</p><pre>// src/providers/config.provider.ts<br>export const ConfigProvider = {<br>  provide: &#39;CONFIG&#39;,<br>  useValue: {<br>    apiKey: &#39;12345&#39;,<br>    apiUrl: &#39;https://api.example.com&#39;,<br>  },<br>};</pre><p>Register the provider in the module:</p><pre>// src/modules/app.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersModule } from &#39;./users.module&#39;;<br>import { ConfigProvider } from &#39;../providers/config.provider&#39;;<br><br>@Module({<br>  imports: [UsersModule],<br>  providers: [ConfigProvider],<br>})<br>export class AppModule {}</pre><p>Inject the provider into a service:</p><pre>// src/services/users.service.ts<br>import { Injectable, Inject } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class UsersService {<br>  constructor(@Inject(&#39;CONFIG&#39;) private readonly config: any) {<br>    console.log(this.config.apiUrl); // Output: https://api.example.com<br>  }<br>}</pre><h3>Memory Efficiency in Dependency Injection</h3><p>One of the often-overlooked benefits of DI is its contribution to memory efficiency. Here’s how DI enhances memory efficiency:</p><p>1. Singleton Services: By default, NestJS services are singletons. This means that a single instance of the service is created and shared across the application. This approach avoids the overhead of creating multiple instances of the same service, reducing memory consumption.</p><pre>@Injectable()<br>export class SingletonService {<br>  // This instance will be shared<br>}</pre><p>2. Lifecycle Management: NestJS’s DI container manages the lifecycle of dependencies. It ensures that instances are created only when needed and disposed of appropriately, preventing memory leaks and optimizing resource usage.</p><p>3. Reuse of Common Dependencies: DI allows the reuse of common dependencies across different parts of the application. For example, a database connection service can be injected into multiple repositories or services without creating new connections each time.</p><pre>@Injectable()<br>export class DatabaseService {<br>  private readonly connection;<br><br>  constructor() {<br>    this.connection = /* create connection */;<br>  }<br><br>  getConnection() {<br>    return this.connection;<br>  }<br>}<br><br>@Injectable()<br>export class UsersService {<br>  constructor(private readonly databaseService: DatabaseService) {}<br><br>  // Reuses the same database connection<br>}</pre><h3>Potential Disadvantages of Dependency Injection</h3><p>While DI offers many benefits, it also has some potential drawbacks:</p><ol><li>Complexity: Implementing DI can introduce additional complexity, especially in large applications with numerous dependencies. Managing and configuring these dependencies might become challenging.</li><li>Learning Curve: For developers unfamiliar with DI, especially those new to NestJS or similar frameworks, there can be a steep learning curve. Understanding how to properly design and implement DI requires time and practice.</li><li>Performance Overhead: Although DI can enhance memory efficiency, it might also introduce some performance overhead due to the additional layer of abstraction. The DI container needs to resolve dependencies at runtime, which can add a slight performance cost.</li><li>Debugging Challenges: Debugging issues related to DI can be more complex compared to direct instantiation. Tracking down the source of a problem might require tracing through multiple layers of dependency configuration.</li><li>Overhead of Configuration: Setting up DI requires additional configuration, such as registering services and providers. This can be seen as overhead, especially in simple applications where DI might not be necessary.</li></ol><h3>Conclusion</h3><p>Dependency Injection is a powerful pattern that helps create scalable, maintainable, and testable applications. NestJS simplifies DI with its robust built-in system, allowing developers to focus on building features rather than managing dependencies. By following the steps and examples provided in this article, you can effectively implement DI in your NestJS applications and reap the benefits of this design pattern, including enhanced memory efficiency.</p><p>However, it’s important to be aware of the potential disadvantages of DI, such as increased complexity and performance overhead. Understanding these drawbacks allows you to make informed decisions about when and how to use DI in your projects.</p><p>Whether you’re new to NestJS or looking to deepen your understanding, mastering DI will undoubtedly enhance your development workflow and the overall quality of your codebase.</p><p>Feel free to share your thoughts or questions in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea0fe4be1256" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Loading in NestJS: Boosting Performance and Efficiency]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/lazy-loading-in-nestjs-boosting-performance-and-efficiency-2c6350a6ab84?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c6350a6ab84</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Sun, 26 May 2024 17:45:43 GMT</pubDate>
            <atom:updated>2024-05-26T17:45:43.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gIRksNA6btlAkXPgokkbw.jpeg" /></figure><p>Lazy loading is a powerful design pattern that delays the initialization of resources until they are actually needed. This can significantly enhance the performance and resource management of your application. In NestJS, lazy loading can be implemented using dynamic modules and the LazyModuleLoader from @nestjs/core. This article explores both methods, providing detailed examples to help you implement lazy loading in your NestJS applications.</p><h4>Why Lazy Loading?</h4><p>Lazy loading helps in:</p><ol><li>Reducing Initial Load Time: By not loading everything at startup, the application can start faster.</li><li>Optimizing Resource Usage: Only load the components or modules when they are actually needed.</li><li>Improving Scalability: Efficient use of resources can help the application scale better.</li></ol><h3>Using LazyModuleLoader for Lazy Loading</h3><p>To implement lazy loading in NestJS we useLazyModuleLoader from @nestjs/core.</p><h4>Step 1: Create the Module to be Lazy Loaded</h4><p>Create the ReportsModule similarly as before.</p><pre>// reports.module.ts<br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ReportsService } from &#39;./reports.service&#39;;<br>import { ReportsController } from &#39;./reports.controller&#39;;<br><br>@Module({<br>  controllers: [ReportsController],<br>  providers: [ReportsService],<br>})<br>export class ReportsModule {}</pre><h4>Step 2: Create the Service for the Lazy Loaded Module</h4><p>Define the service for the ReportsModule.</p><pre>// reports.service.ts<br>import { Injectable } from &#39;@nestjs/common&#39;;<br><br>@Injectable()<br>export class ReportsService {<br>  getReport(): string {<br>    console.log(&#39;lazily loaded reports module&#39;);<br>    return &#39;This is a report!&#39;;<br>  }<br>}</pre><h4>Step 3: Define the Main Module</h4><p>Define the AppModule without importing ReportsModule as we will import it later lazilly.</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><br>@Module({<br>  imports: [],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><h4>Step 4: Create a Controller to Handle Lazy Loading and Other Logic</h4><p>Create a controller that uses LazyModuleLoader to load the ReportsModule dynamically.</p><pre>// app.controller.ts<br>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import { LazyModuleLoader } from &#39;@nestjs/core&#39;;<br>import { ReportsModule } from &#39;./reports/reports.module&#39;;<br>import { ReportsService } from &#39;./reports/reports.service&#39;;<br><br>@Controller()<br>export class AppController {<br>  constructor(private readonly lazyModuleLoader: LazyModuleLoader) {}<br><br>  @Get()<br>  async getLazyReport(): Promise&lt;string&gt; {<br>    // use console.time() and console.timeEnd() <br>    //to get the initialization time of ReportsModule<br>    console.time();<br>    const moduleRef = await this.lazyModuleLoader.load(() =&gt; ReportsModule);<br>    const reportsService = moduleRef.get(ReportsService);<br>    console.timeEnd();<br>    return reportsService.getReport();<br>  }<br>}</pre><h3>Example Usage</h3><p>When the first request is made to the endpoint, the ReportsModule will be loaded lazily, and the ReportsService will handle the request, returning a report.</p><pre>$ curl http://localhost:3000/lazy-reports<br>This is a report!</pre><p>And if you made more requests each consecutive attempt to load ReportsModule is much faster the load method returns a cached instance of the module.</p><p>Making more than one request you will see output like this in app logs.</p><pre>default: 6.226ms<br>lazily loaded reports module<br>[Nest] 208649  - 05/26/2024, 8:33:22 PM     LOG [LazyModuleLoader] ReportsModule dependencies initialized<br>default: 2.323ms<br>lazily loaded reports module<br>[Nest] 208649  - 05/26/2024, 8:33:22 PM     LOG [LazyModuleLoader] ReportsModule dependencies initialized<br>default: 2.012ms<br>lazily loaded reports module</pre><h3>Conclusion</h3><p>Implementing lazy loading in NestJS can significantly enhance the performance and resource efficiency of your application.</p><p>Using LazyModuleLoader in NestJS ensures that modules are loaded lazily once for first time and cached, optimizing performance and resource usage. This approach helps manage dynamic module loading efficiently, providing a balance between initial load time and runtime efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c6350a6ab84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Understanding Explicit vs. Implicit Dependencies in NestJS ]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/understanding-explicit-vs-implicit-dependencies-in-nestjs-6e0c8fdbea56?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0c8fdbea56</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Sun, 26 May 2024 14:18:27 GMT</pubDate>
            <atom:updated>2024-05-26T14:19:53.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*G0RUcAMHvyQ_RZNX0_-N-Q.png" /></figure><p>As developers, managing dependencies efficiently is crucial for building modular and maintainable applications. In NestJS, a robust framework for building server-side applications, understanding the difference between explicit and implicit dependencies can significantly enhance our coding practices. Let’s dive in! 🏊‍♂️</p><h3>Explicit Dependencies</h3><p>Explicit dependencies are directly specified and injected into a class or module. These dependencies are declared in the constructor and managed by the NestJS Dependency Injection (DI) system.</p><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable()<br>export class UserController {<br>  constructor(<br>    private readonly usersService: UsersService,<br>    private readonly authService: AuthService,<br>  ) {}<br><br>  // methods<br>}</pre><p>In this example, UsersService and AuthService are explicit dependencies of the UserController. They are declared in the constructor and injected by the NestJS DI system.</p><h3>Implicit Dependencies</h3><p>Implicit dependencies are not directly specified or injected into a class. Instead, they are dependencies of dependencies, often required by the services or modules that a class depends on. These are resolved automatically by the DI system without being declared in the constructor of the consuming class.</p><pre>@Injectable()<br>export class AuthService {<br>  constructor(private readonly jwtService: JwtService) {}<br><br>  // methods<br>}<br><br>@Injectable()<br>export class UserController {<br>  constructor(private readonly authService: AuthService) {}<br><br>  // methods<br>}</pre><p>In this case, AuthService is an explicit dependency of UserController. However, JwtService is an implicit dependency of UserController because it is required by AuthService but not directly injected into UserController. The NestJS DI system resolves JwtService when creating an instance of AuthService.</p><h3>Key Differences</h3><p>1. Declaration:</p><ul><li>Explicit Dependencies: Declared in the constructor of the consuming class.</li><li>Implicit Dependencies: Not declared in the constructor but required by the dependencies of the consuming class.</li></ul><p>2. Visibility:</p><ul><li>Explicit Dependencies: Visible and directly managed by the consuming class.</li><li>Implicit Dependencies: Hidden and managed indirectly through other dependencies.</li></ul><p>3. Management:</p><ul><li>Explicit Dependencies: Explicitly managed and injected by the DI system into the class.</li><li>Implicit Dependencies: Automatically resolved and injected by the DI system as needed by other services or modules.</li></ul><p>4. Control:</p><ul><li>Explicit Dependencies: Greater control over what dependencies a class receives.</li><li>Implicit Dependencies: Less direct control, as they are managed through the DI system’s resolution of other dependencies.</li></ul><h3>Why It Matters</h3><p>Understanding explicit and implicit dependencies helps in designing a more modular and maintainable codebase. It ensures that dependencies are managed efficiently and that the DI system can resolve all necessary services without issues.</p><p>By mastering this distinction, we can build more robust and scalable applications. Happy coding! 💻✨</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0c8fdbea56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Node.js Operates as Single-Threaded and Executes Multiple Tasks Using Callbacks]]></title>
            <link>https://medium.com/@Abdelrahman_Rezk/how-node-js-operates-as-single-threaded-and-executes-multiple-tasks-using-callbacks-32a99a5db95b?source=rss-3f3aae186598------2</link>
            <guid isPermaLink="false">https://medium.com/p/32a99a5db95b</guid>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abdelrahman Rezk]]></dc:creator>
            <pubDate>Fri, 24 May 2024 18:45:19 GMT</pubDate>
            <atom:updated>2024-05-24T18:45:54.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJw_f9aVwuHM-OCMe-UMBg.jpeg" /></figure><p>Node.js operates in a single-threaded manner, meaning it uses one thread to execute operations. However, thanks to the event loop and non-blocking I/O, Node.js can efficiently manage and execute multiple tasks. In this post, we’ll explain how Node.js can schedule and execute various tasks using callbacks, and we’ll compare Node.js with other languages that use multi-threading.</p><h3>What Does Single-Threaded Mean in Node.js?</h3><p>When we say Node.js is single-threaded, it means it uses one thread to execute code. This differs from systems that use multi-threading, allowing multiple pieces of code to run simultaneously on different threads. Node.js employs the event loop to manage multiple tasks, helping to efficiently utilize memory and CPU.</p><h3>How Does Node.js Manage Multiple Tasks?</h3><h3>The Event Loop</h3><p>The event loop is the core of Node.js. It acts as a task manager, handling the execution of asynchronous code such as file reading, database fetching, and request handling.</p><h3>Non-blocking I/O</h3><p>Non-blocking I/O allows long-running tasks (like network requests and file reading) to be executed in the background. Meanwhile, the event loop can continue executing other tasks without waiting for the long-running task to complete.</p><h3>Callbacks</h3><p>Callbacks are functions passed as arguments to asynchronous operations. When the operation completes, the callback is executed. This allows the event loop to continue executing other code without waiting for the asynchronous operation to finish.</p><h3>How Do Callbacks Work?</h3><h4>1. Initiating the Operation</h4><p>When an asynchronous operation starts, a callback function is passed as an argument. The operation itself runs in the background.</p><h4>2. Completing the Operation</h4><p>Once the operation is complete, the callback is automatically invoked. The callback is executed as part of the event loop’s task queue.</p><h4>3. Returning to the Event Loop</h4><p>After the callback finishes execution, the event loop continues executing the remaining tasks in the queue.</p><h3>Example of Task Management</h3><p>If we have three tasks: reading a file, fetching data from a database, and handling an HTTP request, Node.js manages them as follows:</p><h4>1. Reading a File</h4><h4>2. Fetching Data from a Database</h4><h4>3. Handling an HTTP Request</h4><h3>Steps of Execution</h3><ol><li>Initial Execution:</li></ol><ul><li>Node.js starts by executing any synchronous operations directly.</li><li>Asynchronous operations like file reading and data fetching begin in the background.</li></ul><p>2. Managing Asynchronous Operations:</p><ul><li>Asynchronous operations run in the background thanks to non-blocking I/O.</li><li>The event loop continues processing other tasks concurrently.</li></ul><p>3. Callbacks:</p><ul><li>When asynchronous operations complete, their callbacks are sent to the event loop to be executed.</li></ul><h3>Practical Example of Task Scheduling</h3><p>Let’s look at some code that demonstrates these operations:</p><pre>const fs = require(&#39;fs&#39;);<br>const http = require(&#39;http&#39;);<br>const db = require(&#39;./db&#39;); // Assume you have a db.js file handling database operations<br><br>// 1. Reading a File<br>fs.readFile(&#39;file.txt&#39;, (err, data) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;File content:&#39;, data.toString());<br>});<br><br>// 2. Fetching Data from the Database<br>db.getData((err, data) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;Database data:&#39;, data);<br>});<br><br>// 3. Handling an HTTP Request<br>const server = http.createServer((req, res) =&gt; {<br>  res.writeHead(200, {&#39;Content-Type&#39;: &#39;text/plain&#39;});<br>  res.end(&#39;Hello World\n&#39;);<br>});<br><br>server.listen(3000, () =&gt; {<br>  console.log(&#39;Server running at http://127.0.0.1:3000/&#39;);<br>});</pre><h3>How Callbacks Are Executed</h3><ol><li>Handling an HTTP Request:</li></ol><ul><li>The server starts handling requests immediately. Thanks to non-blocking I/O, it can continue waiting for requests without blocking other tasks.</li><li>When an HTTP request comes in, the server’s callback is executed to respond to the request.</li></ul><p>2. Reading a File:</p><ul><li>The file reading operation begins and runs in the background. When the reading is complete, the callback prints the file content. The operation starts like this:</li></ul><pre>fs.readFile(&#39;file.txt&#39;, (err, data) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;File content:&#39;, data.toString());<br>});</pre><ul><li>Here, fs.readFile takes the file name and a callback function as arguments. This function is executed when the operation completes.</li></ul><p>3. Fetching Data from the Database:</p><ul><li>he data fetching operation begins in the background. When it’s complete, the callback prints the fetched data. The operation starts like this:</li></ul><pre>db.getData((err, data) =&gt; {<br>  if (err) throw err;<br>  console.log(&#39;Database data:&#39;, data);<br>});Copy code</pre><ul><li>Here, db.getData takes a callback function as an argument. This function is executed when the data is retrieved from the database.</li></ul><h3>Comparing Node.js with Multi-threading Languages</h3><p>Some programming languages like Java and C++ use multi-threading to execute multiple tasks simultaneously on different threads. This can be useful for tasks requiring true parallel execution. However, multi-threading adds complexity, such as managing threads and synchronization between them, which can lead to issues like deadlocks.</p><h3>Is Single-threaded a Problem in Node.js?</h3><p>Although Node.js is single-threaded, it can handle many tasks efficiently thanks to the event loop and non-blocking I/O. However, for CPU-intensive tasks, performance issues might arise because these tasks can block the event loop.</p><h3>Advantages of Node.js Despite Being Single-threaded</h3><ol><li>Simplicity in Programming: Programming in Node.js is much simpler than in multi-threading languages because you don’t have to worry about thread management and synchronization.</li><li>High Performance in I/O Operations: Node.js excels in applications relying on I/O operations, such as web applications, APIs, and real-time applications, thanks to non-blocking I/O.</li><li>Callbacks and Promises: The callback and Promise system in Node.js makes writing and managing asynchronous code easier.</li><li>Comprehensive Ecosystem: Node.js comes with a rich set of libraries and tools that simplify application development, like npm, which offers millions of packages you can use in your projects.</li></ol><h3>Conclusion</h3><p>Node.js can efficiently manage and execute multiple tasks thanks to the event loop and non-blocking I/O. Despite being single-threaded, it can utilize resources efficiently and handle many tasks without significant issues. Callbacks allow Node.js to execute asynchronous tasks smoothly, enhancing performance and reducing programming complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32a99a5db95b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>