<?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 Dejan Radmanović on Medium]]></title>
        <description><![CDATA[Stories by Dejan Radmanović on Medium]]></description>
        <link>https://medium.com/@office_61934?source=rss-796971487192------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*thlsYNdF4FWxrMAQbOH64Q.png</url>
            <title>Stories by Dejan Radmanović on Medium</title>
            <link>https://medium.com/@office_61934?source=rss-796971487192------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:40:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@office_61934/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[Marketplace Backend: Nestjs Request Throttling]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-nestjs-request-throttling-fbe68996314e?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbe68996314e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 23:54:58 GMT</pubDate>
            <atom:updated>2023-04-13T04:11:37.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5e6ol2F2hi4-bktMJ7Erw.png" /></figure><h3><strong>Introduction</strong></h3><p>In a modern web application, it’s essential to ensure that our APIs can handle high traffic and are resistant to failure. One way to achieve this is by implementing a throttling mechanism. In this article, we’ll explore how to use the throttler module in NestJS to limit the number of requests a user can make in a given time period.</p><h3>What is throttling?</h3><p>Throttling is a technique used to control the rate at which requests are made to an API. It’s often used to prevent users from overwhelming the API with too many requests at once. By implementing a throttling mechanism, we can ensure that our API remains available to all users, even during periods of high traffic.</p><p>There are several types of throttling, including:</p><ul><li>Request throttling: Limits the number of requests a user can make in a given time period.</li><li>Bandwidth throttling: Limits the amount of data a user can transfer in a given time period.</li><li>Concurrency throttling: Limits the number of concurrent requests a user can make at once.</li></ul><p>In this article, we’ll focus on request throttling using the throttler module in NestJS.</p><h3>What is the throttler module?</h3><p>The throttler module is a NestJS module that provides a middleware to limit the number of requests a user can make in a given time period. It uses Redis to store the request count for each user, making it easy to scale and distribute across multiple servers.</p><p>To use the throttler module, we need to first install it using npm:</p><pre>npm install --save @nestjs/throttler</pre><h3>Implementing request throttling in a NestJS application</h3><p>Let’s consider an example scenario where we want to limit the number of requests a user can make to our API to 10 requests per minute. To achieve this, we’ll use the ThrottlerGuard provided by the throttler module.</p><p>First, we need to import the ThrottlerModule in our application module:</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { ThrottlerModule } from &#39;@nestjs/throttler&#39;;<br><br>@Module({<br>  imports: [<br>    ThrottlerModule.forRoot({<br>      ttl: 60, // The time-to-live for each request count record (in seconds)<br>      limit: 10, // The maximum number of requests allowed in the given time period<br>    }),<br>  ],<br>})<br>export class AppModule {}</pre><p>In the above code, we’re configuring the ThrottlerModule with a time-to-live (TTL) of 60 seconds, which means that each request count record will expire after 60 seconds. We&#39;re also setting the maximum number of requests allowed in the given time period to 10.</p><p>Next, we need to add the ThrottlerGuard to our controller method:</p><pre>import { Controller, Get, UseGuards } from &#39;@nestjs/common&#39;;<br>import { ThrottlerGuard } from &#39;@nestjs/throttler&#39;;<br><br>@Controller()<br>export class AppController {<br>  @Get()<br>  @UseGuards(ThrottlerGuard)<br>  findAll(): string {<br>    return &#39;This endpoint is throttled!&#39;;<br>  }<br>}</pre><p>In the above code, we’re using the ThrottlerGuard as a middleware for our findAll method. This means that every time this method is called, the ThrottlerGuard will check if the user has exceeded their request limit. If they have, the ThrottlerGuard will throw an exception with a 429 status code (Too Many Requests).</p><h3>Conclusion</h3><p>In this article, we’ve explored how to use the throttler module in NestJS to limit the number of requests a user can make in a given time period. By implementing request throttling, we can ensure that our API remains available to all users, even during periods of high traffic.</p><p>Throttling is an important technique to ensure the stability and reliability of our web applications. By implementing throttling mechanisms like request throttling, we can prevent users from overwhelming our APIs with too many requests, ensuring that our services remain available to all users.</p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbe68996314e" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-nestjs-request-throttling-fbe68996314e">Marketplace Backend: Nestjs Request Throttling</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: Creating a Health Check Endpoint in NestJS App Using Terminus]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/25727e96c7d2</guid>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[health-check]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 23:33:21 GMT</pubDate>
            <atom:updated>2023-04-13T04:11:41.177Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDIy4TXJJ-r_ihKsK6gkUQ.png" /><figcaption>Health Response After we are done with tutorial</figcaption></figure><h3><strong>Introduction</strong></h3><p>Health checks are a critical aspect of any application as they ensure that the application is running correctly and the services it relies on are available. In this article, we will go through the process of creating a health check endpoint in a NestJS app using the Terminus library.</p><h3><strong>What is Terminus?</strong></h3><p>Terminus is a library that provides a set of health check endpoints for Node.js applications. It is built on top of NestJS and allows you to define a set of checks that your application can perform to ensure that it is running correctly.</p><p>Creating a Health Check Endpoint in NestJS Using Terminus</p><p>To create a health check endpoint in a NestJS app using Terminus, we need to follow these steps:</p><h3><strong>Install Required Packages</strong></h3><p>First, we need to install the required packages for Terminus. We will be using the @nestjs/terminus package to create our health check endpoint.</p><pre>npm install --save @nestjs/terminus</pre><h3><strong>Create a Health Check Module</strong></h3><p>Next, we need to create a health check module using the Terminus library. To do this, we will create a new HealthModule and add a HealthController to it.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TerminusModule } from &#39;@nestjs/terminus&#39;;<br>import { HealthController } from &#39;./health.controller&#39;;<br><br>/** This is a module that imports the TerminusModule and includes a HealthController. */<br>@Module({<br>  imports: [TerminusModule],<br>  controllers: [HealthController],<br>})<br>export class HealthModule {}</pre><p>In this example, we have created a new module called HealthModule and imported the TerminusModule from the @nestjs/terminus package.</p><h3><strong>Create Health Controller</strong></h3><pre>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import {<br>  DiskHealthIndicator,<br>  HealthCheckService,<br>  MemoryHealthIndicator,<br>  TypeOrmHealthIndicator,<br>} from &#39;@nestjs/terminus&#39;;<br><br>/** The HealthController class checks the health of various components including the database, memory,<br> and disk. */<br>@Controller(&#39;health&#39;)<br>export class HealthController {<br>  constructor(<br>    private health: HealthCheckService,<br>    private db: TypeOrmHealthIndicator,<br>    private memory: MemoryHealthIndicator,<br>    private disk: DiskHealthIndicator,<br>  ) {<br>    console.log(db);<br>  }<br><br>  /**<br>   * The function checks the health of various components including the database, memory, and storage.<br>   * @returns The `check()` function is returning the result of calling the `health.check()` method<br>   * with an array of functions as arguments. Each function in the array is a check for a different<br>   * aspect of the system&#39;s health, including the status of the database, memory usage, and disk<br>   * storage. The `health.check()` method will return a Promise that resolves with an array of objects<br>   * representing the results of each check<br>   */<br>  @Get()<br>  async check() {<br>    return this.health.check([<br>      /* istanbul ignore next */<br>      () =&gt; this.db.pingCheck(&#39;database&#39;, { timeout: 300 }),<br>      /* istanbul ignore next */<br>      () =&gt; this.memory.checkHeap(&#39;memory_heap&#39;, 150 * 1024 * 1024),<br>      /* istanbul ignore next */<br>      () =&gt; this.memory.checkRSS(&#39;memory_rss&#39;, 150 * 1024 * 1024),<br>      /* istanbul ignore next */<br>      () =&gt;<br>        this.disk.checkStorage(&#39;storage&#39;, { thresholdPercent: 0.8, path: &#39;/&#39; }),<br>    ]);<br>  }<br>}</pre><p>Let me elaborate the code above</p><p>The @Controller decorator is used to define the controller with a version of 1 and a path of /health.</p><p>The HealthController class constructor takes in four dependencies: HealthCheckService, TypeOrmHealthIndicator, MemoryHealthIndicator, and DiskHealthIndicator.</p><p>The check() function is decorated with @Get() and is used to handle HTTP GET requests to the /health endpoint. This function calls the health.check() method with an array of functions as arguments. Each function in the array is a check for a different aspect of the system&#39;s health.</p><p>The health.check() method returns a Promise that resolves with an array of objects representing the results of each check.</p><p>For example, this.db.pingCheck() is called to check the status of the database, this.memory.checkHeap() and this.memory.checkRSS() are called to check memory usage, and this.disk.checkStorage() is called to check disk storage.</p><h3><strong>Add the Health Check Endpoint to the Application</strong></h3><p>Finally, we need to add our health check endpoint to our NestJS application. We can do this by importing our HealthModule and adding it to the imports array in our AppModule.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { HealthModule } from &#39;@app/modules/health/health.module&#39;;<br><br>@Module({<br>  imports: [HealthModule],<br>})<br>export class AppModule {}</pre><p>Finally we can run our nestjs application and check it’s helt by accessing next endpoint: <a href="http://localhost:3000/api/health">http://localhost:3000/api/health</a></p><h3><strong>Writing the Unit Tests</strong></h3><p>We will always need to be sure that our application is working as intended so i always encourage people to test their code.</p><p>Here is an example on how you can test your controller:</p><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { HealthController } from &#39;./health.controller&#39;;<br>import { mockDeep, MockProxy } from &#39;jest-mock-extended&#39;;<br>import {<br>  DiskHealthIndicator,<br>  HealthCheckService,<br>  MemoryHealthIndicator,<br>  TypeOrmHealthIndicator,<br>  HealthCheckStatus,<br>} from &#39;@nestjs/terminus&#39;;<br><br>describe(&#39;HealthController&#39;, () =&gt; {<br>  let healthController: HealthController;<br>  let healthCheckService: MockProxy&lt;HealthCheckService&gt;;<br>  beforeEach(async () =&gt; {<br>    const module: TestingModule = await Test.createTestingModule({<br>      controllers: [HealthController],<br>      providers: [<br>        {<br>          provide: HealthCheckService,<br>          useValue: mockDeep&lt;HealthCheckService&gt;(),<br>        },<br>        {<br>          provide: TypeOrmHealthIndicator,<br>          useValue: mockDeep&lt;TypeOrmHealthIndicator&gt;(),<br>        },<br>        {<br>          provide: MemoryHealthIndicator,<br>          useValue: mockDeep&lt;MemoryHealthIndicator&gt;(),<br>        },<br>        {<br>          provide: DiskHealthIndicator,<br>          useValue: mockDeep&lt;DiskHealthIndicator&gt;(),<br>        },<br>      ],<br>    }).compile();<br><br>    healthController = module.get&lt;HealthController&gt;(HealthController);<br>    healthCheckService = module.get(HealthCheckService);<br>  });<br><br>  describe(&#39;check&#39;, () =&gt; {<br>    it(&#39;should return the health of various components&#39;, async () =&gt; {<br>      const mockResult = {<br>        database: { status: &#39;up&#39; },<br>        memory_heap: { status: &#39;up&#39; },<br>        memory_rss: { status: &#39;up&#39; },<br>        storage: { status: &#39;up&#39; },<br>        details: {},<br>        status: &#39;ok&#39; as HealthCheckStatus,<br>      };<br><br>      healthCheckService.check.mockImplementation(async () =&gt; mockResult);<br><br>      const result = await healthController.check();<br><br>      expect(result).toEqual(mockResult);<br>    });<br><br>    it(&#39;should handle health check failures&#39;, async () =&gt; {<br>      const mockResult = {<br>        database: { status: &#39;down&#39; },<br>        memory_heap: { status: &#39;up&#39; },<br>        memory_rss: { status: &#39;up&#39; },<br>        storage: { status: &#39;down&#39; },<br>        details: {},<br>        status: &#39;error&#39; as HealthCheckStatus,<br>      };<br><br>      healthCheckService.check.mockImplementation(async () =&gt; mockResult);<br><br>      const result = await healthController.check();<br><br>      expect(result).toEqual(mockResult);<br>    });<br>  });<br>});</pre><h3><strong>Conclusion</strong></h3><p>In this article, we have seen how to use the Terminus library to add a health endpoint to our NestJS application. We have also seen how to add checks for the database, memory, and storage to ensure that our application is functioning correctly. Finally, we have seen how to create a custom controller to display the results of these checks. By adding a health endpoint to our application, we can ensure that our application is running smoothly and detect any issues early. This can help us provide a better user experience and improve the overall reliability of our application.</p><p>Full example can be found on <a href="https://github.com/suppressf0rce/mobile-marketplace-app-backend/tree/master/src/app/modules/health">GitHub</a></p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25727e96c7d2" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2">Marketplace Backend: Creating a Health Check Endpoint in NestJS App Using Terminus</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: Core Users Module Implementation]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-core-users-module-implementation-4dc5aa96b264?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dc5aa96b264</guid>
            <category><![CDATA[nestjs-tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nestjs-module]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 01:16:12 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:04.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpn9PiUL6TzBXPzYzZCDgg.png" /></figure><h3><strong>Introduction</strong></h3><p>Creating multiple entities like users, roles, and permissions is a fundamental step in building a marketplace application. In this post, we’ll explore how to design and implement these entities using TypeScript and the NestJS framework.</p><h3>Entity Design</h3><p>First, let’s design our entities. A user can have many roles, and a role can have many permissions. We’ll use a many-to-many relationship to represent this association.</p><h3>Permissions</h3><p>The Permission entity represents the different permissions that can be assigned to roles. A role can have multiple permissions. For example, a role can have the permission to create, read, update, and delete products. The Permission entity has the following properties:</p><ul><li>id: The unique identifier of the permission.</li><li>name: The name of the permission.</li></ul><pre>import { Entity, Column, PrimaryGeneratedColumn } from &#39;typeorm&#39;;<br><br>/** This is a TypeScript class representing a Permission entity with an id and a unique name column. */<br>@Entity()<br>export class Permission {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column({ unique: true, nullable: false })<br>  name: string;<br>}</pre><h3>Roles</h3><p>The Role entity represents the different roles that can be assigned to users. A user can have multiple roles. For example, a user can be both a buyer and a seller. The Role entity has the following properties:</p><ul><li>id: The unique identifier of the role.</li><li>name: The name of the role.</li></ul><pre>import {<br>  Entity,<br>  Column,<br>  PrimaryGeneratedColumn,<br>  ManyToMany,<br>  JoinTable,<br>} from &#39;typeorm&#39;;<br>import { Permission } from &#39;./permission.entity&#39;;<br><br>/** This is a TypeScript class representing a Role entity with an id, name, and many-to-many<br>relationship with Permission entities. */<br>@Entity()<br>export class Role {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column({ unique: true, nullable: false })<br>  name: string;<br><br>  @ManyToMany(() =&gt; Permission, { eager: true })<br>  @JoinTable()<br>  permissions: Permission[];<br>}</pre><h3><strong>Users</strong></h3><p>Now that we have our Permission and Role entities defined, we can start defining our User entity. Here&#39;s the code:</p><pre>import {<br>  Entity,<br>  Column,<br>  PrimaryGeneratedColumn,<br>  ManyToMany,<br>  JoinTable,<br>  Index,<br>} from &#39;typeorm&#39;;<br>import { Role } from &#39;./role.entity&#39;;<br><br>/** This is a TypeScript class representing a User entity with various properties and relationships. */<br>@Entity()<br>export class User {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  name: string;<br><br>  @Column({ nullable: false })<br>  @Index({ unique: true })<br>  email: string;<br><br>  @Column({ nullable: false })<br>  password: string;<br><br>  @Column({ default: false, nullable: false })<br>  isEmailVerified: boolean;<br><br>  @Column({ default: false, nullable: false })<br>  isAccountSuspended: boolean;<br><br>  @ManyToMany(() =&gt; Role, { eager: true })<br>  @JoinTable()<br>  roles: Role[];<br>}</pre><p>In this entity, we define the basic properties of a User entity, such as their first name, last name, email, and password. We also define two boolean properties, isEmailVerified and isAccountSuspended, that can be used to manage the user&#39;s account. Finally, we define a many-to-many relationship with the Role entity, using the @ManyToMany decorator. The roles property will hold an array of Role entities assigned to the user.</p><h3>Entity Implementation</h3><p>Now that we have our three entities defined, we can start building the logic to manage them in our marketplace project. We’ll need to create repositories and services for each entity, and then use them to implement the necessary functionality.</p><p>Here are the services:</p><h3><strong>Permission Service</strong></h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Permission } from &#39;@shared/core-user-module/entities/permission.entity&#39;;<br>import { DeleteResult, Repository } from &#39;typeorm&#39;;<br><br>/** The PermissionService class provides methods for creating, updating, deleting, and retrieving<br> permissions from a repository. */<br>@Injectable()<br>export class PermissionService {<br>  constructor(<br>    @InjectRepository(Permission)<br>    private readonly permissionRepository: Repository&lt;Permission&gt;,<br>  ) {}<br><br>  /**<br>   * This function creates a new permission and returns it as a Promise.<br>   * @param {Permission} permission - The parameter `permission` is an object of type `Permission` that<br>   * contains the data needed to create a new permission. The exact properties of the `Permission`<br>   * object will depend on the specific implementation of the `Permission` class, but it might include<br>   * things like a name, description, and level of<br>   * @returns A Promise that resolves to a Permission object.<br>   */<br>  async createPermission(permission: Permission): Promise&lt;Permission&gt; {<br>    return this.permissionRepository.create(permission);<br>  }<br><br>  /**<br>   * This function updates a permission in a repository and returns the updated permission.<br>   * @param {Permission} permission - The parameter `permission` is of type `Permission`, which is<br>   * likely an interface or a class representing a permission object with various properties such as<br>   * `id`, `name`, `description`, etc. The `updatePermission` function takes in a `permission` object<br>   * and saves it to the database using the<br>   * @returns A Promise that resolves to a Permission object.<br>   */<br>  async updatePermission(permission: Permission): Promise&lt;Permission&gt; {<br>    return this.permissionRepository.save(permission);<br>  }<br><br>  /**<br>   * This function deletes a permission by its ID and returns a Promise containing the result of the<br>   * deletion.<br>   * @param {number} id - The `id` parameter is a number that represents the unique identifier of a<br>   * permission that needs to be deleted from the database. The function `deletePermissionById` is an<br>   * asynchronous function that takes in this `id` parameter and returns a `Promise` that resolves to a<br>   * `DeleteResult` object.<br>   * @returns The `deletePermissionById` function is returning a `Promise` that resolves to a<br>   * `DeleteResult` object. The `DeleteResult` object contains information about the result of the<br>   * delete operation, such as the number of affected rows.<br>   */<br>  async deletePermissionById(id: number): Promise&lt;DeleteResult&gt; {<br>    return this.permissionRepository.delete(id);<br>  }<br><br>  /**<br>   * This function retrieves a permission by its ID from a repository and returns it as a Promise.<br>   * @param {number} id - The `id` parameter is a number that represents the unique identifier of a<br>   * permission. The `getPermissionById` function is an asynchronous function that takes in this `id`<br>   * parameter and returns a Promise that resolves to a `Permission` object if a permission with the<br>   * specified `id` is found in<br>   * @returns The `getPermissionById` function is returning a Promise that resolves to either a<br>   * `Permission` object or `undefined`. The `Permission` object represents a permission entity<br>   * retrieved from the `permissionRepository` using the `findOneBy` method with the `id` parameter. If<br>   * no permission entity is found with the given `id`, the function will return `undefined`.<br>   */<br>  async getPermissionById(id: number): Promise&lt;Permission | undefined&gt; {<br>    return this.permissionRepository.findOneBy({ id: id });<br>  }<br>}</pre><h3><strong>Role Service</strong></h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { Role } from &#39;@shared/core-user-module/entities/role.entity&#39;;<br>import { DeleteResult, Repository } from &#39;typeorm&#39;;<br><br>/** The RoleService class provides methods for creating, updating, deleting, and retrieving Role objects<br> from a repository. */<br>@Injectable()<br>export class RoleService {<br>  constructor(<br>    @InjectRepository(Role)<br>    private readonly roleRepository: Repository&lt;Role&gt;,<br>  ) {}<br><br>  /**<br>   * This function creates a new role and returns it as a Promise.<br>   * @param {Role} role - The parameter `role` is an object of type `Role` that contains information<br>   * about a role. This object is passed as an argument to the `createRole` function. The function then<br>   * uses this object to create a new role in the database using the `roleRepository.create` method.<br>   * The function<br>   * @returns A Promise that resolves to a Role object.<br>   */<br>  async createRole(role: Role): Promise&lt;Role&gt; {<br>    return this.roleRepository.create(role);<br>  }<br><br>  /**<br>   * This function updates a role and returns the updated role object.<br>   * @param {Role} role - Role object that contains the updated information for a specific role.<br>   * @returns A Promise that resolves to a Role object.<br>   */<br>  async updateRole(role: Role): Promise&lt;Role&gt; {<br>    return this.roleRepository.save(role);<br>  }<br><br>  /**<br>   * This function deletes a role from the database by its ID and returns a Promise with the result of<br>   * the deletion.<br>   * @param {number} id - The `id` parameter is a number that represents the unique identifier of a<br>   * role that needs to be deleted from the database.<br>   * @returns The `deleteRoleById` function is returning a Promise that resolves to a `DeleteResult`<br>   * object. The `DeleteResult` object contains information about the result of the delete operation,<br>   * such as the number of rows affected.<br>   */<br>  async deleteRoleById(id: number): Promise&lt;DeleteResult&gt; {<br>    return this.roleRepository.delete(id);<br>  }<br><br>  /**<br>   * This function retrieves a role by its ID from a repository and returns it as a Promise.<br>   * @param {number} id - The parameter &quot;id&quot; is a number that represents the unique identifier of a<br>   * role. The function &quot;getRoleById&quot; takes this parameter and returns a Promise that resolves to a Role<br>   * object or undefined if no role with the given id is found in the roleRepository.<br>   * @returns A promise that resolves to either a `Role` object or `undefined`.<br>   */<br>  async getRoleById(id: number): Promise&lt;Role | undefined&gt; {<br>    return this.roleRepository.findOneBy({ id: id });<br>  }<br>}</pre><h3><strong>User Service</strong></h3><pre>import { Injectable } from &#39;@nestjs/common&#39;;<br>import { InjectRepository } from &#39;@nestjs/typeorm&#39;;<br>import { User } from &#39;@shared/core-user-module/entities/user.entity&#39;;<br>import { DeleteResult, Repository } from &#39;typeorm&#39;;<br><br>/** The UserService class provides methods for creating, updating, deleting, and retrieving user data<br> from a repository. */<br>@Injectable()<br>export class UserService {<br>  constructor(<br>    @InjectRepository(User)<br>    private readonly userRepository: Repository&lt;User&gt;,<br>  ) {}<br><br>  /**<br>   * This function creates a new user and returns a promise containing the created user.<br>   * @param {User} user - The parameter `user` is an object of type `User` which contains information<br>   * about a user that needs to be created. This object likely includes properties such as `name`,<br>   * `email`, `password`, and other relevant information. The `createUser` function is an asynchronous<br>   * function that takes in this<br>   * @returns A Promise that resolves to a User object.<br>   */<br>  async createUser(user: User): Promise&lt;User&gt; {<br>    return this.userRepository.create(user);<br>  }<br><br>  /**<br>   * This function updates a user in a database and returns the updated user.<br>   * @param {User} user - The parameter `user` is an object of type `User` which contains information<br>   * about a user. This method `updateUser` takes this `user` object as input and returns a Promise<br>   * that resolves to the updated `User` object after saving it to the database using the<br>   * `userRepository.save()` method<br>   * @returns The `updateUser` function is returning a Promise that resolves to a `User` object. The<br>   * `User` object is the result of saving the updated user data to the database using the `save`<br>   * method of the `userRepository`.<br>   */<br>  async updateUser(user: User): Promise&lt;User&gt; {<br>    return this.userRepository.save(user);<br>  }<br><br>  /**<br>   * This function deletes a user from the database by their ID and returns a Promise with the result<br>   * of the deletion.<br>   * @param {number} id - The id parameter is a number that represents the unique identifier of a user<br>   * that needs to be deleted from the database. The function is an asynchronous function that returns<br>   * a Promise that resolves to a DeleteResult object. The DeleteResult object contains information<br>   * about the number of rows affected by the delete operation.<br>   * @returns The `deleteUserById` function is returning a `Promise` that resolves to a `DeleteResult`<br>   * object. The `DeleteResult` object contains information about the result of the delete operation,<br>   * such as the number of rows affected.<br>   */<br>  async deleteUserById(id: number): Promise&lt;DeleteResult&gt; {<br>    return this.userRepository.delete(id);<br>  }<br><br>  /**<br>   * This function retrieves a user by their ID from a repository and returns it as a Promise.<br>   * @param {number} id - The `id` parameter is a number that represents the unique identifier of a<br>   * user. The `getUserById` function is an asynchronous function that takes in this `id` parameter and<br>   * returns a Promise that resolves to a `User` object or `undefined` if no user is found with the<br>   * given `<br>   * @returns The `getUserById` function is returning a Promise that resolves to either a `User` object<br>   * or `undefined`. The `User` object represents a user entity retrieved from the database using the<br>   * `id` parameter passed to the function. If no user is found with the given `id`, the function<br>   * returns `undefined`.<br>   */<br>  async getUserById(id: number): Promise&lt;User | undefined&gt; {<br>    return this.userRepository.findOneBy({ id: id });<br>  }<br><br>  /**<br>   * This function returns a promise that resolves to a user object with a given email or undefined if<br>   * no user is found.<br>   * @param {string} email - The email parameter is a string that represents the email address of a<br>   * user. This function is designed to retrieve a user from a repository based on their email address.<br>   * @returns The `getUserByEmail` function is returning a Promise that resolves to either a `User`<br>   * object or `undefined`. The `User` object represents a user in the system and contains information<br>   * such as their email, name, and other details. If no user is found with the specified email, the<br>   * function will return `undefined`.<br>   */<br>  async getUserByEmail(email: string): Promise&lt;User | undefined&gt; {<br>    return this.userRepository.findOneBy({ email: email });<br>  }<br>}</pre><h3><strong>Creating Shared User Core Module</strong></h3><p>Finally, let’s create the UserCoreModule which is an shared module that may be implemented by multiple modules by our application, for example both AuthModule and UsersModule can take advantage of this module.</p><pre>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { UserService } from &#39;@shared/core-user-module/services/user.service&#39;;<br>import { User } from &#39;@shared/core-user-module/entities/user.entity&#39;;<br>import { Role } from &#39;@shared/core-user-module/entities/role.entity&#39;;<br>import { Permission } from &#39;@shared/core-user-module/entities/permission.entity&#39;;<br>import { RoleService } from &#39;@shared/core-user-module/services/role.service&#39;;<br>import { PermissionService } from &#39;@shared/core-user-module/services/permission.service&#39;;<br><br>/** This is a shared module in a TypeScript application that imports and exports services related to users,<br>roles, and permissions using TypeORM. */<br>@Module({<br>  imports: [TypeOrmModule.forFeature([User, Role, Permission])],<br>  providers: [UserService, RoleService, PermissionService],<br>  exports: [UserService, RoleService, PermissionService],<br>})<br>export class UserCoreModule {}</pre><h3><strong>Testing our Services</strong></h3><p>In order to make sure that our services work as intended we will need to make sure to write Unit Tests. Here is an example of user.service.spec.ts which will test our UserService class</p><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br>import { User } from &#39;@shared/core-user-module/entities/user.entity&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { getRepositoryToken } from &#39;@nestjs/typeorm&#39;;<br>import { mockDeep, MockProxy } from &#39;jest-mock-extended&#39;;<br><br>describe(&#39;UserService&#39;, () =&gt; {<br>  let userService: UserService;<br>  let userRepository: MockProxy&lt;Repository&lt;User&gt;&gt;;<br><br>  const user = {<br>    id: 1,<br>    name: &#39;John Doe&#39;,<br>    email: &#39;johndoe@example.com&#39;,<br>    password: &#39;password&#39;,<br>    isEmailVerified: false,<br>    isAccountSuspended: false,<br>    roles: [],<br>  };<br><br>  beforeEach(async () =&gt; {<br>    const module: TestingModule = await Test.createTestingModule({<br>      providers: [<br>        UserService,<br>        {<br>          provide: getRepositoryToken(User),<br>          useValue: mockDeep&lt;Repository&lt;User&gt;&gt;(),<br>        },<br>      ],<br>    }).compile();<br><br>    userService = module.get&lt;UserService&gt;(UserService);<br>    userRepository = module.get(getRepositoryToken(User));<br>  });<br><br>  it(&#39;should be defined&#39;, () =&gt; {<br>    expect(userService).toBeDefined();<br>  });<br><br>  describe(&#39;createUser&#39;, () =&gt; {<br>    it(&#39;should create a user&#39;, async () =&gt; {<br>      userRepository.create.mockReturnValue(user);<br>      userRepository.save.mockResolvedValue(user);<br><br>      const result = await userService.createUser(user);<br><br>      expect(result).toEqual(user);<br>      expect(userRepository.create).toHaveBeenCalledWith(user);<br>    });<br>  });<br><br>  describe(&#39;updateUser&#39;, () =&gt; {<br>    it(&#39;should update a user&#39;, async () =&gt; {<br>      userRepository.save.mockResolvedValue(user);<br><br>      const result = await userService.updateUser(user);<br><br>      expect(result).toEqual(user);<br>      expect(userRepository.save).toHaveBeenCalledWith(user);<br>    });<br>  });<br><br>  describe(&#39;deleteUserById&#39;, () =&gt; {<br>    it(&#39;should delete a user by id&#39;, async () =&gt; {<br>      userRepository.delete.mockResolvedValue({ affected: 1, raw: {} });<br><br>      const result = await userService.deleteUserById(user.id);<br><br>      expect(result).toEqual({ affected: 1, raw: {} });<br>      expect(userRepository.delete).toHaveBeenCalledWith(user.id);<br>    });<br>  });<br><br>  describe(&#39;getUserById&#39;, () =&gt; {<br>    it(&#39;should return a user by id&#39;, async () =&gt; {<br>      userRepository.findOneBy.mockResolvedValue(user);<br><br>      const result = await userService.getUserById(user.id);<br><br>      expect(result).toEqual(user);<br>      expect(userRepository.findOneBy).toHaveBeenCalledWith({ id: user.id });<br>    });<br>  });<br><br>  describe(&#39;getUserByEmail&#39;, () =&gt; {<br>    it(&#39;should return a user by email&#39;, async () =&gt; {<br>      userRepository.findOneBy.mockResolvedValue(user);<br><br>      const result = await userService.getUserByEmail(user.email);<br><br>      expect(result).toEqual(user);<br>      expect(userRepository.findOneBy).toHaveBeenCalledWith({<br>        email: user.email,<br>      });<br>    });<br>  });<br>});</pre><p>The Test.createTestingModule method is used to create a test module for the UserService. In the providers array, the UserService is provided along with a mocked instance of the User repository using the getRepositoryToken function from the @nestjs/typeorm module. The mockDeep function from the jest-mock-extended library is used to create a deep mock of the Repository&lt;User&gt; interface.</p><p>In the beforeEach hook, the userService and userRepository variables are assigned values from the module instance using the module.get method.</p><p>The test cases are written in describe blocks that group related test cases together. For example, the createUser test case checks that the createUser method of the UserService class creates a new User object by invoking the create method of the userRepository instance and saves the object by invoking the save method of the userRepository instance.</p><p>Each test case is written in an it block, which contains the code that will be executed and verified. The expected outcome is defined using the Jest expect function and the Jest matchers. For example, the expect(userService).toBeDefined() statement in the first it block checks that the userService instance is defined.</p><p>The MockProxy type is used to define the userRepository variable, which is a mocked instance of the Repository&lt;User&gt; interface. This allows Jest to track the calls made to the mocked methods of the userRepository instance, such as create, save, delete, and findOneBy.</p><p>Full example can be found on <a href="https://github.com/suppressf0rce/mobile-marketplace-app-backend">GitHub</a></p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dc5aa96b264" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-core-users-module-implementation-4dc5aa96b264">Marketplace Backend: Core Users Module Implementation</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: Database Connection & Docker Compose]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-database-connection-docker-compose-7cd0df0675e5?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cd0df0675e5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 00:47:27 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:07.274Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>NestJS is a progressive Node.js framework used for building scalable and efficient server-side applications. One of the crucial aspects of any server-side application is the database connectivity. In this article, we’ll explore how to connect a NestJS application to a database.</p><p>There are several databases available for NestJS, including PostgreSQL, MySQL, MongoDB, and others. In this article, we’ll focus on connecting to a PostgreSQL database using the TypeORM library.</p><h3><strong>Why PostgreSQL?</strong></h3><p>PostgreSQL, also known as Postgres, is a popular open source relational database management system (RDBMS) that is often used in web applications and enterprise software. There are several reasons why PostgreSQL may be a good choice for a marketplace application:</p><ol><li>Reliability and stability: PostgreSQL has a reputation for being reliable and stable, which is important for any critical application that needs to be available 24/7. It has a proven track record of handling large-scale applications with high transaction volumes and complex data models.</li><li>Advanced features: PostgreSQL offers a wide range of advanced features such as support for JSON data types, full-text search, and geospatial data. It also supports complex queries and transactions, making it suitable for complex applications with multiple data sources.</li><li>Open source and free: PostgreSQL is open source and free to use, making it an attractive option for startups and small businesses that want to keep their costs low.</li><li>Scalability: PostgreSQL can be easily scaled horizontally and vertically, allowing you to add more resources as your application grows. It also supports clustering and replication, which can help improve performance and availability.</li><li>Community support: PostgreSQL has a large and active community of users and developers who provide support, bug fixes, and feature enhancements. This community ensures that PostgreSQL remains up-to-date and relevant to the needs of modern web applications.</li></ol><h3><strong>What is TypeORM?</strong></h3><p>TypeORM is an object-relational mapping (ORM) library that provides a way to interact with relational databases using object-oriented programming techniques. It allows developers to define database models as classes and then use those classes to query and manipulate data in the database.</p><p>TypeORM supports a wide range of relational database management systems, including MySQL, PostgreSQL, SQLite, Oracle, and Microsoft SQL Server. It provides features such as data validation, type checking, query building, and migrations.</p><p>TypeORM is often used in conjunction with Node.js and popular web frameworks such as NestJS, Express, and Koa. It integrates well with these frameworks and provides a simple and intuitive API for database interactions.</p><h3><strong>What is Docker Compose and why should i use it?</strong></h3><p>Docker Compose is a tool for defining and running multi-container Docker applications. It allows developers to specify the configuration for multiple Docker containers as a single file, making it easy to manage and deploy complex applications.</p><p>Here are some of the key benefits of using Docker Compose:</p><ol><li>Simplified deployment: Docker Compose provides a simple way to deploy complex applications with multiple containers. By defining the configuration for all of the containers in a single file, you can easily deploy and manage your entire application with a single command.</li><li>Consistent environments: Docker Compose ensures that each container in your application is running the same version of the software, with the same configuration settings. This helps eliminate issues related to environment inconsistencies that can arise when running applications across multiple environments.</li><li>Scalability: Docker Compose makes it easy to scale your application horizontally by adding more containers. You can simply update the configuration file to include additional containers, and then deploy the updated application with a single command.</li><li>Portability: Because the Docker Compose configuration file specifies all of the dependencies and settings for your application, it can be easily moved between different environments. This makes it easy to deploy your application to different servers or cloud providers without having to modify the configuration.</li><li>Integration with other Docker tools: Docker Compose integrates well with other Docker tools, such as Docker Swarm and Docker Machine, allowing you to build and deploy complex applications in a seamless manner.</li></ol><h3><strong>Creating Docker Compose file</strong></h3><p>Now that we’ve discussed my reasoning behind my choices, let’s set up Docker Compose to easily manage our application and database containers.</p><p>First, create a new file named docker-compose.yml in the root directory of your application and add the following code:</p><pre>version: &#39;3&#39;<br>services:<br>  db:<br>    image: postgres<br>    environment:<br>      POSTGRES_USER: postgres<br>      POSTGRES_PASSWORD: postgres<br>      POSTGRES_DB: maobile-marketplace-app<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data<br>  app:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - db<br>volumes:<br>  postgres_data:</pre><p>his defines two services: db and app. The db service uses the postgres image and sets the POSTGRES_USER, POSTGRES_PASSWORD, and POSTGRES_DB environment variables. It also exposes port 5432 for incoming connections and creates a named volume to persist data.</p><p>The app service builds the Docker image for our NestJS application using the Dockerfile in the root directory of our application. It exposes port 3000 for incoming connections and depends on the db service.</p><h3>Installing the Required Packages</h3><p>To integrate our NestJS application with a PostgreSQL database using TypeORM, we need to install the following packages:</p><ul><li>typeorm</li><li>@nestjs/typeorm</li><li>pg</li></ul><p>To install these packages, run the following command:</p><pre>npm install --save typeorm @nestjs/typeorm pg</pre><h3>Configuring the database connection</h3><p>Open the app.module.ts file in your NestJS application and add the following import:</p><pre>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;</pre><p>Next, add the TypeOrmModule.forRoot() method to the imports array:</p><pre>@Module({<br>  imports: [<br>    CoreModule,<br>    TypeOrmModule.forRoot({<br>      type: &#39;postgres&#39;,<br>      host: &#39;db&#39;,<br>      port: 5432,<br>      username: &#39;postgres&#39;,<br>      password: &#39;postgres&#39;,<br>      database: &#39;mobile-marketplace-app&#39;,<br>      entities: [],<br>      synchronize: true,<br>    }),<br>  ],<br>  controllers: [],<br>  providers: [],<br>})<br>export class AppModule {}</pre><p>Here, we’re configuring the database connection by specifying the database type, host, port, username, password, and database name. We’re also setting synchronize to true, which will automatically create the database schema for us.</p><h3>Testing the application</h3><p>Now that we have the application set up, let’s test it out. Start the application by running the following command in your terminal:</p><pre>docker compose up</pre><p>This will start the containers in the foreground and output logs to the console. To run the containers in the background, use the -d option:</p><pre>docker compose up -d</pre><p>If you wish to rebuild your image, you can use:</p><pre>docker compose up --build</pre><h3><strong>Conclusion</strong></h3><p>In this article, we learned how to integrate a NestJS application with a Postgres database using TypeORM. We also learned how to use Docker Compose to easily manage our application and database containers. With this knowledge, you should be able to quickly build and deploy scalable NestJS applications with a robust database backend.</p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cd0df0675e5" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-database-connection-docker-compose-7cd0df0675e5">Marketplace Backend: Database Connection &amp; Docker Compose</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: NestJS Global prefixes and Versioning]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-nestjs-global-prefixes-and-versioning-5757602b9f66?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/5757602b9f66</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 22:57:18 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:09.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*G0RUcAMHvyQ_RZNX0_-N-Q.png" /></figure><h3><strong>Introduction</strong></h3><p>As APIs grow and evolve over time, it is essential to add a prefix and versioning to your NestJS application. Doing so helps to maintain backward compatibility and provide a clear separation between different versions of the API. In this post, we will explore how to add a prefix and versioning to your NestJS application.</p><h3>Why Prefix and Version Your API?</h3><p>Adding a prefix and versioning to your API is essential for several reasons:</p><ul><li>Backward compatibility: As your API evolves, you may need to make changes that break backward compatibility with earlier versions. By versioning your API, you can ensure that clients can continue to use earlier versions of your API while still allowing you to make changes to newer versions.</li><li>Clear separation: Versioning your API helps to provide a clear separation between different versions of your API. This separation can help to prevent conflicts between different versions of your API and make it easier for clients to understand which version of the API they are using.</li><li>Ease of use: Adding a prefix and versioning to your API can make it easier for clients to understand and use your API. It provides a clear structure for your API and makes it easier to navigate.</li></ul><h3>Adding a Prefix to Your API</h3><p>To add a prefix to your API, you can use the setGlobalPrefix method in your main.ts file. This method allows you to specify a prefix that will be added to all of your API endpoints.</p><p>Here’s an example:</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>  app.setGlobalPrefix(&#39;api&#39;);<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>In this example, we’ve added the prefix api to our API. This means that all of our API endpoints will start with /api.</p><h3>Versioning Your API</h3><p>To version your API, you can create a separate module for each version of your API. This module can then be used to define the controllers, services, and providers for that version of the API.</p><p>Here’s an example:</p><pre>// app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { AppController } from &#39;./app.controller&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { V1Module } from &#39;./v1/v1.module&#39;;<br><br>@Module({<br>  imports: [V1Module],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>In this example, we’ve imported the V1Module module into our AppModule. This module contains all of the controllers, services, and providers for version 1 of our API.</p><pre>// v1.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersController } from &#39;./users.controller&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br><br>@Module({<br>  controllers: [UsersController],<br>  providers: [UsersService],<br>})<br>export class V1Module {}</pre><p>In our V1Module, we&#39;ve defined the controllers and services for version 1 of our API. This module can be used to define any additional controllers, services, or providers that are specific to version 1 of our API.</p><h3><strong>Specifying version of the module (version prefix)</strong></h3><p>To specify the version in the API route, we can use the @Controller decorator in the version module and pass in the version number as a parameter. Here&#39;s an updated example of the V1Module with the version number specified:</p><pre>// v1.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { UsersController } from &#39;./users.controller&#39;;<br>import { UsersService } from &#39;./users.service&#39;;<br><br>@Controller(&#39;v1&#39;) // specify the version number in the route<br>export class V1Module {<br>  constructor(private readonly usersService: UsersService) {}<br>}</pre><p>In this example, we use the @Controller decorator and pass in &#39;v1&#39; as a parameter. This specifies that all the routes in this controller will be prefixed with /v1, meaning that the endpoint to access the UsersController would be /api/v1/users.</p><p>You can do the same thing in any other versioned module, specifying the appropriate version number for each one. This approach helps to maintain clear separation and backward compatibility between different versions of your API.</p><h3>Conclusion</h3><p>Adding a prefix and versioning to your NestJS application is essential for maintaining backward compatibility, providing a clear separation between different versions of your API, and making it easier for clients to use your API. By following the steps outlined in this post, you can easily add a prefix and versioning to your NestJS application.</p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5757602b9f66" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-nestjs-global-prefixes-and-versioning-5757602b9f66">Marketplace Backend: NestJS Global prefixes and Versioning</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: How to Integrate Swagger in a NestJS Application]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-how-to-integrate-swagger-in-a-nestjs-application-b779bf208662?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/b779bf208662</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 22:12:58 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:11.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sglapCxDJAHQP_MHdUWRXw.png" /></figure><h3><strong>Introduction</strong></h3><p>Swagger is a powerful tool for documenting and testing APIs, and it can be particularly useful in NestJS applications. With Swagger, you can generate interactive documentation for your API that makes it easy for developers to understand how to use your endpoints and test them out.</p><p>In this tutorial, we’ll walk through how to integrate Swagger in a NestJS application using the @nestjs/swagger module. By the end of this tutorial, you&#39;ll have a fully documented API that you can share with other developers.</p><h3><strong>Install the @nestjs/swagger module</strong></h3><p>The first step to integrating Swagger in your NestJS application is to install the @nestjs/swagger module. You can do this using npm:</p><pre>npm install --save @nestjs/swagger</pre><h3><strong>Enable Swagger in your application</strong></h3><p>Now that we have installed the necessary dependencies, we need to configure Swagger in our NestJS application.</p><p>Create a new file called swagger.config.ts in the config directory of the project and add the following code:</p><pre>import { DocumentBuilder, SwaggerModule } from &#39;@nestjs/swagger&#39;;<br><br>export function setupSwagger(app) {<br>  const options = new DocumentBuilder()<br>    .setTitle(&#39;API Documentation&#39;)<br>    .setDescription(&#39;Mobile Marketplace API documentation&#39;)<br>    .setVersion(&#39;1.0.0&#39;)<br>    .addBearerAuth()<br>    .build();<br>  const document = SwaggerModule.createDocument(app, options);<br>  SwaggerModule.setup(&#39;docs&#39;, app, document);<br>}</pre><p>Here, we’re creating a new Swagger document using the DocumentBuilder class from @nestjs/swagger. We&#39;re setting the title, description, and version of our API, but you can customize these fields to fit your own API.</p><p>Next, we’re creating a Swagger config and setting it up with our NestJS application. We’re passing in the document we just created, and specifying that we want the Swagger UI to be available at the /docs endpoint.</p><h3><strong>Include Swagger Configuration in Main File</strong></h3><p>Now that we have created the Swagger configuration, we need to include it in the main file of our NestJS application.</p><p>Update the main.ts file in the root directory of the project to include the following code:</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;@app/app.module&#39;;<br>import { setupSwagger } from &#39;@config/swagger.config&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  setupSwagger(app);<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>This will call the setupSwagger() function and pass in the NestJS application instance.</p><h3><strong>Add Swagger decorators to your controllers</strong></h3><p>Now that you’ve enabled Swagger in your NestJS application, you can start adding Swagger decorators to your controllers. These decorators will tell Swagger how to generate the API documentation.</p><p>Here’s an example controller with Swagger decorators:</p><pre>import { Controller, Get, Query } from &#39;@nestjs/common&#39;;<br>import { ApiQuery, ApiResponse, ApiTags } from &#39;@nestjs/swagger&#39;;<br><br>@Controller(&#39;cats&#39;)<br>@ApiTags(&#39;cats&#39;)<br>export class CatsController {<br>  @Get()<br>  @ApiResponse({ status: 200, description: &#39;List of cats.&#39;})<br>  async findAll(@Query(&#39;limit&#39;) limit: number) {<br>    return `This action returns all cats (limit: ${limit} items)`;<br>  }<br>  <br>  @Get(&#39;:id&#39;)<br>  @ApiResponse({ status: 200, description: &#39;The found cat.&#39;, type: Cat })<br>  @ApiResponse({ status: 404, description: &#39;Cat not found.&#39;})<br>  async findOne(@Param(&#39;id&#39;) id: number) {<br>    return `This action returns a #${id} cat`;<br>  }<br>}</pre><p>Here, we’re using the ApiTags decorator to add a tag to our controller, which will be used to group the endpoints in the Swagger UI. We&#39;re also using the ApiResponse decorator to define the response format for each endpoint.</p><h3><strong>Test Swagger Documentation</strong></h3><p>We are now ready to test the Swagger documentation. Start the NestJS application by running the following command in the terminal:</p><pre>npm run start:dev</pre><p>This will start the NestJS application on port 3000.</p><p>Open a web browser and navigate to the following URL:</p><pre>http://localhost:3000/docs/</pre><p>You should see the Swagger documentation for your NestJS application. You can now use this documentation to test your API endpoints and ensure they are working correctly.</p><h3><strong>Writing Test Suite</strong></h3><p>In order to make sure that our code is running without any problems we will need to write a simple test suite to test it and prevent bugs from happening. This is optional part and it want be necessity for this tutorial to get you up and running, but still i like my code to be safe tested.</p><p>This is the content of the swagger.config.spec.ts:</p><pre>import { Test, TestingModule } from &#39;@nestjs/testing&#39;;<br>import { setupSwagger } from &#39;@config/swagger.config&#39;;<br>import { INestApplication } from &#39;@nestjs/common&#39;;<br>import { SwaggerModule, DocumentBuilder } from &#39;@nestjs/swagger&#39;;<br><br>describe(&#39;Swagger&#39;, () =&gt; {<br>  let app: INestApplication;<br><br>  beforeAll(async () =&gt; {<br>    const module: TestingModule = await Test.createTestingModule({<br>      // ...<br>    }).compile();<br><br>    app = module.createNestApplication();<br>    await app.init();<br>  });<br><br>  afterAll(async () =&gt; {<br>    await app.close();<br>  });<br><br>  describe(&#39;setupSwagger&#39;, () =&gt; {<br>    it(&#39;should setup swagger correctly&#39;, () =&gt; {<br>      const options = new DocumentBuilder()<br>        .setTitle(&#39;API Documentation&#39;)<br>        .setDescription(&#39;Mobile Marketplace API documentation&#39;)<br>        .setVersion(&#39;1.0.0&#39;)<br>        .addBearerAuth()<br>        .build();<br><br>      const setupSpy = jest.spyOn(SwaggerModule, &#39;setup&#39;);<br><br>      setupSwagger(app);<br><br>      expect(setupSpy).toHaveBeenCalledWith(<br>        &#39;docs&#39;,<br>        app,<br>        SwaggerModule.createDocument(app, options),<br>      );<br>    });<br>  });<br>});</pre><p>This test suite uses Jest and Nest’s testing utilities to test the behavior of the setupSwagger() function. The beforeAll() and afterAll() hooks create and close the Nest application respectively, while the describe() and it() blocks test the setupSwagger() function.</p><p>In the it() block, we create a new DocumentBuilder instance with the same options as in the setupSwagger() function, and we spy on the SwaggerModule.setup() method using Jest&#39;s jest.spyOn() function. We then call the setupSwagger() function with the app instance we created in the beforeAll() hook.</p><p>Finally, we use Jest’s expect() function to verify that the SwaggerModule.setup() method was called with the correct arguments. We expect it to be called with the string &#39;api&#39;, the app instance, and an object containing the options from the documentBuilder object.</p><h3><strong>Conclusion</strong></h3><p>In this tutorial, we have learned how to integrate Swagger into a NestJS application. Swagger provides a convenient way to document and test API endpoints, making it easier to develop and maintain APIs. By following the steps outlined in this tutorial, you should now be able to integrate Swagger into your own NestJS application and start documenting and testing your API endpoints.</p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b779bf208662" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-how-to-integrate-swagger-in-a-nestjs-application-b779bf208662">Marketplace Backend: How to Integrate Swagger in a NestJS Application</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: NestJS SOLID principles and folder structure]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-nestjs-solid-principles-and-folder-structure-82cc72a82490?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/82cc72a82490</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[project-structure]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 18:47:23 GMT</pubDate>
            <atom:updated>2023-11-27T06:27:37.489Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eh-iy-ZSsE3IId8h9kcY0A.png" /><figcaption>SOLID principles from shekhall.com</figcaption></figure><h3><strong>Introduction:</strong></h3><p>NestJS is a powerful Node.js framework that allows developers to build scalable and maintainable web applications. One of the key benefits of NestJS is its support for SOLID architecture principles, which help to make your code more modular, testable, and maintainable. In this article, we will discuss SOLID principles and how to apply them to your NestJS application. We will also cover directory design and best practices to help organize your code in a way that is intuitive and easy to navigate.</p><figure><a href="https://risingmax.com/?utm_source=MAC"><img alt="" src="https://cdn-images-1.medium.com/max/878/1*igw18skRXwuKb49oZZsDeQ.png" /></a></figure><h3>What is SOLID?</h3><p>SOLID is an acronym that stands for five principles of object-oriented design:</p><ul><li>Single Responsibility Principle (SRP)</li><li>Open/Closed Principle (OCP)</li><li>Liskov Substitution Principle (LSP)</li><li>Interface Segregation Principle (ISP)</li><li>Dependency Inversion Principle (DIP)</li></ul><p>Let’s take a closer look at each of these principles and how they relate to NestJS.</p><h3>Single Responsibility Principle (SRP)</h3><p>The SRP states that a class should have only one responsibility. In other words, each class should be responsible for one thing and one thing only. This helps to make your code more modular and easier to test.</p><p>In a NestJS application, you can apply the SRP by creating small, focused services that perform a single task. For example, if you have a user registration feature in your application, you can create a UserService that handles all the logic related to user registration, such as validating the input, creating the user record in the database, and sending a welcome email.</p><h3>Open/Closed Principle (OCP)</h3><p>The OCP states that a class should be open for extension but closed for modification. In other words, you should be able to add new functionality to a class without changing its existing code. This helps to make your code more flexible and easier to maintain.</p><p>In a NestJS application, you can apply the OCP by using dependency injection to inject dependencies into your classes. For example, if you have a UserService that depends on a UserRepository to interact with the database, you can inject the UserRepository into the UserService, rather than hard-coding it. This makes it easy to swap out the UserRepository with a different implementation in the future, without having to modify the UserService code.</p><h3>Liskov Substitution Principle (LSP)</h3><p>The LSP states that subtypes should be substitutable for their base types. In other words, any code that works with a base type should also work with its subtypes. This helps to ensure that your code is compatible with different implementations and reduces the likelihood of bugs.</p><p>In a NestJS application, you can apply the LSP by using interfaces to define common contracts for your classes. For example, if you have multiple UserRepository implementations for different databases, you can define a UserRepository interface that specifies the methods that each implementation should support. This allows you to swap out the implementation without having to change any code that depends on the UserRepository.</p><h3>Interface Segregation Principle (ISP)</h3><p>The ISP states that clients should not be forced to depend on interfaces they do not use. In other words, you should keep your interfaces small and focused, rather than creating large, monolithic interfaces. This helps to make your code more maintainable and easier to understand.</p><p>In a NestJS application, you can apply the ISP by creating small, focused interfaces that define only the methods that a class needs to implement. For example, if you have a UserService that depends on a UserRepository, you can create a UserRepository interface that defines only the methods that the UserService needs to use, rather than a large, generic interface that defines all the methods that a database can support.</p><h3>Dependency Inversion Principle (DIP)</h3><p>The DIP states that higher-level modules should not depend on lower-level modules, but rather both should depend on abstractions.</p><p>In other words, you should define interfaces or abstract classes that define the functionality that a module needs, and then have the concrete implementation of those interfaces injected into the module.</p><p>This allows for greater flexibility and modularity in your code, as you can swap out different implementations of a given interface without affecting the rest of the codebase. By following DIP, you can avoid tightly coupling your code to specific implementations, which can make it easier to maintain and modify your application over time.</p><h3>Directory Design</h3><p>Once you have a good understanding of the SOLID principles, you can start to organize your NestJS application’s directories in a way that supports those principles. Here’s an example of a directory structure that follows SOLID principles:</p><pre>├── src<br>│   ├── app<br>│   │   ├── modules<br>│   │   │   ├── transaction<br>│   │   │   │   ├── controllers<br>│   │   │   │   ├── dto<br>│   │   │   │   ├── entities<br>│   │   │   │   ├── services<br>│   │   │   │   ├── tests<br>│   │   │   │   └── users.module.ts<br>│   │   │   └── tasks<br>│   │   │       ├── controllers<br>│   │   │       ├── dto<br>│   │   │       ├── entities<br>│   │   │       ├── services<br>│   │   │       ├── tests<br>│   │   │       └── tasks.module.ts<br>│   │   └── app.module.ts<br>│   ├── config<br>│   ├── database<br>|   ├── shared<br>│   ├── core<br>│   │   ├── exceptions<br>│   │   ├── filters<br>│   │   ├── guards<br>│   │   ├── interfaces<br>│   │   ├── middlewares<br>│   │   ├── pipes<br>│   │   ├── providers<br>│   │   ├── utils<br>|   |   └── core.module.ts<br>│   └── main.ts</pre><p>Let’s break this down:</p><ul><li>app directory: This directory contains all of the modules in your application. Each module is organized into its own directory, with its own module.ts file that defines the module&#39;s imports, controllers, services, and providers.</li><li>config directory: This directory contains configuration files for your application, such as environment variables, database connections, etc.</li><li>database directory: This directory contains all of the database-related files, such as entity definitions, migrations, and seed data.</li><li>shared directory: This directory contains all the modules that can be shared between other application module, for example we want use the users module in both Authentication, and Role modules</li><li>core directory: This directory contains all of the core code that can be used by multiple modules in your application. This includes things like custom exceptions, filters, guards, interfaces, middlewares, pipes, providers, and utilities.</li><li>main.ts file: This is the entry point for your NestJS application.</li></ul><p>By organizing your application in this way, you can easily follow the SOLID principles by keeping each module independent and loosely-coupled, with clearly-defined responsibilities. Additionally, you can easily reuse code across your application by keeping it in the shared directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*GOQlHz4-EuEEp3hNsQl8Cg.png" /></figure><h3>Conclusion</h3><p>In this post, we’ve discussed how to apply SOLID principles and directory design to your NestJS application. By following these principles and organizing your code in a clear and concise way, you can build a more maintainable, scalable, and extensible application.</p><p>Remember, the SOLID principles are guidelines, not strict rules. It’s up to you to decide how to apply them to your specific application and use case. But by keeping them in mind as you write your code, you can ensure that your application is robust, testable, and easy to maintain.</p><p>Link to GitHub example: <a href="https://github.com/suppressf0rce/mobile-marketplace-app-backend/tree/solid-folder-structure">https://github.com/suppressf0rce/mobile-marketplace-app-backend/tree/solid-folder-structure</a></p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82cc72a82490" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-nestjs-solid-principles-and-folder-structure-82cc72a82490">Marketplace Backend: NestJS SOLID principles and folder structure</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: Dockerizing and Deploying a NestJS Application to GitHub with GitHub Actions…]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-dockerizing-and-deploying-a-nestjs-application-to-github-with-github-actions-a300293ac88d?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/a300293ac88d</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 02:16:46 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:15.183Z</atom:updated>
            <content:encoded><![CDATA[<h3>Marketplace Backend: Dockerizing and Deploying a NestJS Application to GitHub with GitHub Actions on Version Tag</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6CvfE6WUgoIdT8Mp0Ev_g.png" /></figure><h3><strong>Introduction:</strong></h3><p>Dockerizing your NestJS application is a great way to simplify the deployment process and make your application more portable. By using GitHub Actions, you can also automate the deployment process and easily deploy your application to GitHub.</p><p>In this tutorial, we’ll walk you through the process of dockerizing and deploying a NestJS application to GitHub using GitHub Actions on a version tag.</p><h3><strong>Dockerize Your NestJS Application:</strong></h3><p>The first step is to dockerize your NestJS application. This involves creating a Dockerfile that defines the image for your application. Here’s an example Dockerfile for a basic NestJS application:</p><pre>FROM node:14-alpine<br><br>WORKDIR /app<br><br>COPY package*.json ./<br><br>RUN npm install<br><br>COPY . .<br><br>RUN npm run build<br><br>EXPOSE 3000<br><br>CMD [ &quot;npm&quot;, &quot;run&quot;, &quot;start:prod&quot; ]</pre><p>This Dockerfile uses the node:18-alpine image as the base and sets the working directory to /app. It then copies the package*.json files and runs npm install. Next, it copies the rest of the files and runs npm run build to build the application. Finally, it exposes port 3000 and starts the application using npm run start:prod.</p><h3><strong>Set up GitHub Actions Workflow:</strong></h3><p>Now that you’ve dockerized your application and published the Docker image to GitHub Packages, you can set up a GitHub Actions workflow to deploy the Docker image to GitHub on a version tag. Here’s an example workflow that you can use:</p><pre>name: Docker<br><br>on:<br>  schedule:<br>    - cron: &#39;19 1 * * *&#39;<br>  push:<br>    branches: [ &quot;master&quot; ]<br>    # Publish semver tags as releases.<br>    tags: [ &#39;v*.*.*&#39; ]<br>  pull_request:<br>    branches: [ &quot;master&quot; ]<br><br>env:<br>  # Use docker.io for Docker Hub if empty<br>  REGISTRY: ghcr.io<br>  # github.repository as &lt;account&gt;/&lt;repo&gt;<br>  IMAGE_NAME: ${{ github.repository }}<br><br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br>    permissions:<br>      contents: read<br>      packages: write<br>      id-token: write<br><br>    steps:<br>      - name: Checkout repository<br>        uses: actions/checkout@v3<br><br>      - name: Install cosign<br>        if: github.event_name != &#39;pull_request&#39;<br>        uses: sigstore/cosign-installer@f3c664df7af409cb4873aa5068053ba9d61a57b6 #v2.6.0<br>        with:<br>          cosign-release: &#39;v1.13.1&#39;<br><br>      - name: Setup Docker buildx<br>        uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf<br><br>      - name: Log into registry ${{ env.REGISTRY }}<br>        if: github.event_name != &#39;pull_request&#39;<br>        uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c<br>        with:<br>          registry: ${{ env.REGISTRY }}<br>          username: ${{ github.actor }}<br>          password: ${{ secrets.GITHUB_TOKEN }}<br><br>      - name: Extract Docker metadata<br>        id: meta<br>        uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38<br>        with:<br>          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}<br><br>      - name: Build and push Docker image<br>        id: build-and-push<br>        uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a<br>        with:<br>          context: .<br>          push: ${{ github.event_name != &#39;pull_request&#39; }}<br>          tags: ${{ steps.meta.outputs.tags }}<br>          labels: ${{ steps.meta.outputs.labels }}<br>          cache-from: type=gha<br>          cache-to: type=gha,mode=max<br><br>      - name: Sign the published Docker image<br>        if: ${{ github.event_name != &#39;pull_request&#39; }}<br>        env:<br>          COSIGN_EXPERIMENTAL: &quot;true&quot;<br>        run: echo &quot;${{ steps.meta.outputs.tags }}&quot; | xargs -I {} cosign sign {}@${{ steps.build-and-push.outputs.digest }}</pre><h3><strong>Create a Version Tag:</strong></h3><p>To trigger the GitHub Actions workflow, you’ll need to create a version tag in your repository. Here’s how to create a version tag:</p><ol><li>Open your repository in GitHub.</li><li>Click on the Releases tab.</li><li>Click on the Draft a new release button.</li><li>Enter the version number and any release notes.</li><li>Click on the Publish release button.</li></ol><h3><strong>Deploy Your Application:</strong></h3><p>After you’ve created the version tag, the GitHub Actions workflow will be triggered and the Docker image will be built, pushed to GitHub Packages, and deployed to your production server. You can check the status of the workflow by going to the Actions tab in your repository.</p><h3><strong>Conclusion:</strong></h3><p>In this tutorial, we’ve shown you how to dockerize and deploy a NestJS application to GitHub using GitHub Actions on a version tag. By following the steps outlined in this article, you can easily automate the deployment process and ensure that your application is always up-to-date and running smoothly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a300293ac88d" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-dockerizing-and-deploying-a-nestjs-application-to-github-with-github-actions-a300293ac88d">Marketplace Backend: Dockerizing and Deploying a NestJS Application to GitHub with GitHub Actions…</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: Integrating Compodoc Documentation in NestJS Project with GitHub Actions and…]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-integrating-compodoc-documentation-in-nestjs-project-with-github-actions-and-35b9127c6019?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/35b9127c6019</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[compodoc]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 23:55:38 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:18.159Z</atom:updated>
            <content:encoded><![CDATA[<h3>Marketplace Backend: Integrating Compodoc Documentation in NestJS Project with GitHub Actions and GitHub Pages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gIQ-JCUZXHaixfwVXQBVw.png" /></figure><h3><strong>Introduction:</strong></h3><p>Compodoc is a powerful documentation tool that generates documentation for your TypeScript projects. In this article, we’ll explore how to integrate Compodoc documentation into a NestJS project, build the documentation using GitHub Actions, and display it in GitHub Pages.</p><h3><strong>Install Compodoc in Your NestJS Project:</strong></h3><p>The first step is to install Compodoc in your NestJS project. You can do this using npm:</p><pre>npm install --save-dev @compodoc/compodoc</pre><h3><strong>Generate Documentation with Compodoc:</strong></h3><p>Once you have Compodoc installed, you can generate the documentation for your NestJS project. To do this, add a new script to your package.json file:</p><pre>{<br>// ...<br>&quot;docs&quot;: &quot;compodoc -p compodoc.tsconfig.json -d docs&quot;<br>}</pre><p>This script runs Compodoc with the compodoc.tsconfig.json configuration file to generate the documentation.</p><h3><strong>Add Compodoc Configuration:</strong></h3><p>Compodoc uses a configuration file to define how the documentation should be generated. Create a new file called compodoc.config.json in the root of your project with the following content:</p><pre>{<br>    &quot;include&quot;: [<br>        &quot;src/**/*&quot;<br>    ],<br>    &quot;exclude&quot;: [<br>        &quot;node_modules/&quot;,<br>        &quot;src/migrations/*&quot;,<br>        &quot;src/migrations/**/*&quot;,<br>        &quot;docs/&quot;,<br>        &quot;dist/&quot;,<br>        &quot;coverage/&quot;,<br>        &quot;**/*.spec.ts&quot;<br>    ]<br>}</pre><p>This configuration file sets the title of the documentation, the output directory, the theme to use, and other options. You can modify these settings to suit your needs.</p><h3><strong>Set up GitHub Actions Workflow:</strong></h3><p>To build the documentation automatically using GitHub Actions, you’ll need to set up a workflow that runs the docs script and deploys the documentation to GitHub Pages. Create a new file called .github/workflows/documentation.yml in the root of your project with the following content:</p><pre>name: Documentation<br><br>on:<br>  push:<br>    branches:<br>      - master<br><br>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v2<br><br>      - name: Install dependencies<br>        run: npm install<br><br>      - name: Generate documentation<br>        run: npm run docs<br><br>      - name: Deploy documentation<br>        uses: peaceiris/actions-gh-pages@v3<br>        with:<br>          github_token: ${{ secrets.GITHUB_TOKEN }}<br>          publish_dir: ./docs</pre><p>This configuration sets up a workflow that runs the docs script when you push changes to the master branch. The documentation is generated using Compodoc and deployed to GitHub Pages using the peaceiris/actions-gh-pages action.</p><h3><strong>Configure GitHub Pages:</strong></h3><p>To display the documentation in GitHub Pages, you’ll need to configure your repository to use GitHub Pages. Here’s how:</p><ol><li>Go to your repository’s Settings page on GitHub.</li><li>Scroll down to the GitHub Pages section.</li><li>Select the master branch as the source.</li><li>Set the root directory to /docs.</li><li>Click the Save button.</li></ol><p><strong><em>Note: Make sure your github actions have read and write permission under the project settings =&gt; actions =&gt; general, it won’t work otherwise</em></strong></p><h3><strong>View the Documentation:</strong></h3><p>Now that you’ve set up everything, you can view the documentation by going to the URL https://&lt;username&gt;.github.io/&lt;repository-name&gt;/. Replace &lt;username&gt; with your GitHub username and &lt;repository-name&gt; with the name of your repository.</p><h3><strong>Conclusion:</strong></h3><p>Integrating Compodoc documentation into a NestJS project is a great way to provide documentation for your project’s APIs and components. By automating the documentation generation process with GitHub Actions and deploying it to GitHub Pages, you can ensure that your documentation is always up-to-date and easily accessible. By following the steps outlined in this article, you can quickly and easily set up Compodoc in your NestJS project and start generating documentation today.</p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35b9127c6019" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-integrating-compodoc-documentation-in-nestjs-project-with-github-actions-and-35b9127c6019">Marketplace Backend: Integrating Compodoc Documentation in NestJS Project with GitHub Actions and…</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Marketplace Backend: Building a NestJS Application Using GitHub Actions]]></title>
            <link>https://mobileappcircular.com/marketplace-backend-building-a-nestjs-application-using-github-actions-b1181a52d918?source=rss-796971487192------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1181a52d918</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Dejan Radmanović]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 22:29:52 GMT</pubDate>
            <atom:updated>2023-04-12T09:13:20.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3j7_T57sVI9X2LK5JMS8Zw.png" /></figure><h3><strong>Introduction:</strong></h3><p>NestJS is a popular framework for building scalable and maintainable Node.js applications. However, setting up a build process for your NestJS application can be time-consuming and error-prone. That’s where GitHub Actions comes in. GitHub Actions is a powerful automation tool that can help you automate the build process for your NestJS application. In this article, we’ll walk through the steps of building a NestJS application using GitHub Actions.</p><h3><strong>Setting Up Your NestJS Application:</strong></h3><p>Before we get started with GitHub Actions, we need to set up a new NestJS application. If you’re new to NestJS, you can follow my instructions i already went through in <a href="https://medium.com/@office_61934/marketplace-backend-baby-steps-setting-up-your-environment-for-nestjs-app-development-5797201f0d6e">this post</a>. Once you have your NestJS application up and running, you’re ready to move on to the next step.</p><h3><strong>Creating a GitHub Repository for Your NestJS Application:</strong></h3><p>The next step is to create a new GitHub repository for your NestJS application. If you don’t already have a GitHub account, you’ll need to create one. Once you’re logged in to GitHub, follow these steps to create a new repository:</p><ol><li>Click the “New” button on the top left corner of your GitHub dashboard.</li><li>Give your repository a name and description.</li><li>Choose whether you want your repository to be public or private.</li><li>Click the “Create repository” button.</li></ol><p>Once you have your GitHub repository set up, you can add your NestJS application to it. You can do this by cloning your NestJS application to your local machine, and then pushing it to your GitHub repository using the following commands:</p><pre>git clone https://github.com/your-username/your-repository.git<br>cd your-repository<br>git remote add origin https://github.com/your-username/your-repository.git<br>git push -u origin master</pre><h3><strong>Configuring GitHub Actions for Your NestJS App:</strong></h3><p>Now that your NestJS application is set up in a GitHub repository, it’s time to configure GitHub Actions. GitHub Actions is a powerful automation tool that allows you to automate the build process for your NestJS application. To get started, follow these steps:</p><ol><li>Click the “Actions” tab on your GitHub repository.</li><li>Click the “Set up a workflow yourself” button.</li><li>Copy and paste the following code into the editor:</li></ol><pre>name: Node.js CI<br><br>on:<br>  push:<br>    branches: [ &quot;master&quot; ]<br>  pull_request:<br>    branches: [ &quot;master&quot; ]<br><br>jobs:<br>  build:<br><br>    runs-on: ubuntu-latest<br><br>    strategy:<br>      matrix:<br>        node-version: [18.x]<br><br>    steps:<br>    - uses: actions/checkout@v3<br>    - name: Use Node.js ${{ matrix.node-version }}<br>      uses: actions/setup-node@v3<br>      with:<br>        node-version: ${{ matrix.node-version }}<br>        cache: &#39;npm&#39;<br>    - run: npm install<br>    - run: npm run build --if-present<br>    - run: npm run test<br>    - run: npm run test:e2e</pre><p>4. Click the “Start commit” button, and then click the “Commit new file” button.</p><p>This GitHub Action will run whenever you push changes to the master branch of your GitHub repository. It will install the necessary dependencies, build your NestJS application, and run tests.</p><h3><strong>Testing and Deploying Your NestJS Application:</strong></h3><p>Now that your GitHub Action is set up, it’s time to test and deploy your NestJS application. To test your application, simply push your changes to the master branch of your GitHub repository. GitHub Actions will automatically run the tests and provide feedback on whether they passed or failed.</p><p>To deploy your application, you can use another GitHub Action that deploys your application to a server. There are many third-party GitHub Actions available for deploying Node.js applications to different hosting providers, such as AWS, Heroku, and DigitalOcean. You can find a list of available actions in the GitHub Marketplace.</p><p>But me personally i’m going to dockerize my application and that i will cover in another post</p><h3><strong>Displaying status badge in README:</strong></h3><p>Next we will want to display the status badge on our README.md page, to let our users whether build of our application is failing or not. In order to do so we will need to complete next steps.</p><ol><li>Go to actions page of our GitHub Repository</li><li>Select Node.js CI from the list on the left menu</li><li>Select … from the right side of the page</li><li>Choose the option to create status badge</li><li>Pick the default master branch</li><li>Hit the copy status badge markdown</li><li>Paste that markdown code anywhere inside the README.md file</li></ol><h3><strong>Conclusion:</strong></h3><p>In this article, we walked through the steps of building a NestJS application using GitHub Actions. We started by setting up a new NestJS application, and then created a new GitHub repository for it. Then we configured a GitHub Action to automate the build process for our NestJS application, and tested it. With GitHub Actions, you can easily automate the build process for your NestJS application and focus on writing code.</p><p><strong><em>Godspeed</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1181a52d918" width="1" height="1" alt=""><hr><p><a href="https://mobileappcircular.com/marketplace-backend-building-a-nestjs-application-using-github-actions-b1181a52d918">Marketplace Backend: Building a NestJS Application Using GitHub Actions</a> was originally published in <a href="https://mobileappcircular.com/">Mobile App Circular</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>