{"id":22266025,"url":"https://github.com/muhdhanish/learning-nestjs","last_synced_at":"2026-05-08T01:37:12.019Z","repository":{"id":212307728,"uuid":"730993242","full_name":"MuhdHanish/Learning-NestJs","owner":"MuhdHanish","description":"Welcome to the Nest.js Learning Hub! 🚀 This repository serves as a comprehensive resource for mastering Nest.js, the powerful and extensible Node.js framework. ","archived":false,"fork":false,"pushed_at":"2024-06-30T11:27:00.000Z","size":357,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-30T13:13:15.974Z","etag":null,"topics":["decorators","mongodb","nestjs","nestjs-backend","rest-api"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MuhdHanish.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-12-13T05:57:29.000Z","updated_at":"2024-06-30T11:27:03.000Z","dependencies_parsed_at":"2023-12-13T15:53:01.979Z","dependency_job_id":"88e9ec46-9307-41e9-a772-8ff641d9f8ff","html_url":"https://github.com/MuhdHanish/Learning-NestJs","commit_stats":null,"previous_names":["muhdhanish/learning-nestjs"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MuhdHanish%2FLearning-NestJs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MuhdHanish%2FLearning-NestJs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MuhdHanish%2FLearning-NestJs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MuhdHanish%2FLearning-NestJs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MuhdHanish","download_url":"https://codeload.github.com/MuhdHanish/Learning-NestJs/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245476701,"owners_count":20621699,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decorators","mongodb","nestjs","nestjs-backend","rest-api"],"created_at":"2024-12-03T10:17:30.257Z","updated_at":"2026-05-08T01:37:11.967Z","avatar_url":"https://github.com/MuhdHanish.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NestJS Notes\n\n## 1. Modules\n\n- Each application has at least one module - the root module, which serves as the starting point.\n- Modules effectively organize components based on closely related capabilities (e.g., per feature).\n- It's a good practice to have a folder per module, containing the module's components.\n- Modules are singletons, meaning a module can be imported by multiple other modules.\n\n### Defining a Module\n\nTo define a module in NestJS, use the `@Module` decorator. This decorator provides metadata that NestJS uses to organize the application structure.\n\n#### @Module Decorator Properties\n\n- **providers**: Array of providers available within the module via dependency injection.\n- **controllers**: Array of controllers instantiated within the module.\n- **exports**: Array of providers to export to other modules.\n- **imports**: List of modules required by this module. Any exported provider by these modules will now be available in our module via dependency injection.\n\nExample of a basic module definition:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { SomeService } from './some.service';\nimport { SomeController } from './some.controller';\n\n@Module({\n  imports: [],                       // List of imported modules\n  controllers: [SomeController],     // List of controllers\n  providers: [SomeService],          // List of providers\n  exports: [SomeService],            // List of providers to be exported for other modules to use\n})\nexport class SomeModule {}\n```\n\n## 2. Controllers\n\n- Responsible for handling incoming requests and returning responses to the client.\n- Bound to a specific path (e.g., \"/tasks\" for the task resource).\n- Contain handlers, which manage endpoints and request methods (GET, POST, DELETE...).\n- Can take advantage of dependency injection to consume providers within the same module.\n\n### Defining a Controller\n\nTo define a controller in NestJS, use the `@Controller` decorator. This decorator accepts a string, which is the path to be handled by the controller.\n\nExample of a basic controller definition:\n\n```typescript\nimport { Controller } from '@nestjs/common';\n\n@Controller('/example')\nexport class SomeController {\n  // ...\n}\n```\n\nThis `SomeController` handles requests at the \"/example\" endpoint.\n\n### Defining a Handler\n\nHandlers are methods within the controller class, decorated with decorators such as `@Get`, `@Post`, `@Delete`...\n\nExample of a basic handler definition:\n\n```typescript\nimport { Controller, Get, Post } from '@nestjs/common';\n\n@Controller('/example')\nexport class SomeController {\n  @Get()\n  getSomething() {\n    return ...;\n  }\n  @Post()\n  createSomething() {\n    return ...;\n  }\n}\n```\n\n### HTTP Request Incoming Diagram\n\n- **First Request**: When a request comes in, it is routed to the appropriate controller based on the defined routes.\n- **Controller**: The controller receives the request and passes it to the appropriate handler method.\n- **Handler**: The handler method is called with any required arguments. NestJS parses the relevant request data, making it available in the handler.\n- **Handler Processing**: The handler processes the request, which may involve interactions with services such as retrieving data from a database.\n- **Response**: Once the handler has completed its operations, it returns a response. This response can be of any type, including an exception. NestJS wraps the return value as an HTTP response and sends it back to the client.\n```\n                                      +---------------------------+\n                                      |                           |\n                                      |   Incoming HTTP Request   |\n                                      |                           |\n                                      +--------------+------------+\n                                                     |\n                                                     v\n                                     +---------------+--------------+\n                                     |                              |\n                                     |        Route Resolution      |\n                                     |                              |\n                                     |  - Determine appropriate     |\n                                     |    controller and handler    |\n                                     |    based on defined routes   |\n                                     +---------------+--------------+\n                                                     |\n                                                     v\n                                     +---------------+--------------+\n                                     |                              |\n                                     |        Controller            |\n                                     |                              |\n                                     |  - Receive request           |\n                                     |  - Pass request to handler   |\n                                     +---------------+--------------+\n                                                     |\n                                                     v\n                                     +---------------+--------------+\n                                     |                              |\n                                     |        Handler Method        |\n                                     |                              |\n                                     |   - Parse Request Data       |\n                                     |   - Execute Business Logic   |\n                                     |   - Retrieve Data            |\n                                     |   - Return Response          |\n                                     |   - Handle Exceptions        |\n                                     |                              |\n                                     +---------------+--------------+\n                                                     |\n                                                     v\n                                     +---------------+--------------+\n                                     |                              |\n                                     |      Request Processing      |\n                                     |                              |\n                                     |  - Handler processes         |\n                                     |    the request               |\n                                     +---------------+--------------+\n                                                     |\n                                                     v\n                                     +---------------+--------------+\n                                     |                              |\n                                     |       Response Sent          |\n                                     |                              |\n                                     |  - Handler returns response  |\n                                     +------------------------------+\n```\n\n## 3. Providers\n\n- Can be injected into constructors if decorated as an `@Injectable`, via dependency injection.\n- Can be a plain value, a class, sync/async fatctor etc.\n- Provider must be provided to a module for them to be usable.\n- Can be exported from a module - and then be available to other modules that import it.\n\n### What is a Service ?\n\n- Defined as a provider. **Not all providers are services**.\n- Common concept within software development and are not exclusive NestJS, JavaScript or back-end development.\n- Singleton when wrapped with `@Injectable()` are provided to a module. That means, the same instance will be the shared across the application acting as a single source of truth.\n- The services are the main source of business logic. For example, a service will be called from a controller to validate data, create an item in the database and return a response.\n\nExample of Providers in Modules:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { SampleOneService, SampleTwoService } from './some.service';\nimport { SomeController } from './some.controller';\n\n@Module({\n  controllers: [SomeController],  \n  providers: [SampleOneService, SampleTwoService],  \n})\nexport class SomeModule {}\n```\n\n## 4. Dependency Injection In NestJS\n\n- Any component within the NestJS ecosystem can inject a provider that is decorated with the `@Injectable`.\n- We define the dependencies in the constructor of the class. NestJS will take care of the injection for us, and it will then be available as a class property.\n\nExample demonstrating the usage of dependency injection in a NestJS controller:\n\n```typescript\nimport { Controller, Get, Post } from '@nestjs/common';\nimport { SomeService } from './some.service';\n\n@Controller('/example')\nexport class SomeController {\n  constructor(private someService: SomeService){}\n  @Get()\n  getSomething() {\n    return await this.someService.someting();\n  }\n}\n```\n\nIn this example:\n- The `SomeController` class has a dependency on the `SomeService`, which is injected into its constructor.\n- The `SomeService` instance is then available as a property (`this.someService`) within the `SomeController`.\n- We can now call methods or access properties of the `SomeService` instance from within the `SomeController`, such as in the `getSomething` method.\n\n\n## 5. Data Transfer Object (DTO)\n\n- Common concept in software development that is not specific to NestJS.\n- Result in more bulletproof code, as it can be used as a TypeScript type.\n- Do not have any behavior except for storage, retrieval, serialization, and deserialization of their own data.\n- Result in increased performance (although negligible in small applications).\n- Can be useful for data validation.\n- A DTO is *not* a model definition. It defines the shape of the data for a specific case, for example, creating a task.\n- Can be defined using an interface or a class.\n\n### Definitions\n\n- A Data Transfer Object (DTO) is an object that carries data between processes (Wikipedia).\n- A DTO is used to encapsulate data and transfer it from one subsystem of an application to another (StackOverflow).\n- A DTO defines how data will be sent over the network (NestJS Documentation).\n\n### Class VS Interface for DTO's\n\n- Data Transfer Object's (DTO's) can be defined as classes or interfaces.\n- The recommended approach is to use classes, also clearly documented in the NestJS documentation.\n- The reason is that interfaces are a part of TypeScript and therefore are not preserved post-compilation.\n- Classes allow us to do more, and since they are a part of JavaScript, they will be preserved post-compilation.\n- NestJS cannot refer interfaces in run-time, but can refer to classes.\n\n\n### Important Note!\n\n- Data Transfer Objects are **NOT** mandatory.\n- You can still develop application without using DTO's.\n- However, the value they add makes it worthwhile to use them when applicable.\n- Applying the DTO pattern as soon as possible will make it easy for you to maintain and refractor your code.\n\n## 6. NestJS Pipes\n\nPipes in NestJS operate on the **arguments** that are to be processed by the route handler, right before the handler is called. Pipes can perform two primary functions:\n\n1. **Data Transformation:** Transforming the data into the desired format.\n2. **Data Validation:** Validating the data against certain criteria.\n\nPipes can return either the original or modified data to be passed on to the route handler. If the data is invalid or an error occurs, pipes can throw exceptions, which are handled by NestJS and turned into appropriate error responses. Notably, pipes can also be asynchronous.\n\n### Default Pipes in NestJS\n\nNestJS provides several useful pipes within the `@nestjs/common` module:\n\n#### ValidationPipe\n\nThis pipe validates an entire object against a class, making it especially useful with Data Transfer Objects (DTOs). If any property cannot be properly mapped (e.g., due to a type mismatch), the validation will fail. This built-in validation pipe is highly beneficial for common use cases.\n\n#### ParseIntPipe\n\nSince arguments are strings by default, this pipe validates that an argument is a number. If successful, the argument is transformed into a **Number** and passed on to the handler.\n\n### Custom Pipe Implementation\n\nTo create a custom pipe in NestJS:\n\n1. **Class and Decorator:** Pipes are classes annotated with the `@Injectable()` decorator.\n2. **Implement `PipeTransform`:** Pipes must implement the `PipeTransform` generic interface, requiring a **transform()** method.\n3. **Parameters of `transform()`:** The `transform()` method takes two parameters:\n   - **value:** The value of the processed argument.\n   - **metadata** (optional): An object containing metadata about the argument.\n4. **Return Value or Exception:** The `transform()` method returns data to be passed to the route handler or throws an exception to be sent back to the client.\n\n### Using Pipes\n\nPipes can be applied in different ways:\n\n#### Handler-Level Pipes\n\nDefined at the handler level using the `@UsePipes()` decorator. These pipes process all parameters for the incoming request.\n\n```typescript\nimport { Post, UsePipes, Body } from '@nestjs/common';\n\n@Post()\n@UsePipes(SomePipe)\ncreateSomething(\n  @Body('something') something\n) {\n  // ...\n}\n```\n\n#### Parameter-Level Pipes\n\nDefined at the parameter level. Only the specific parameter for which the pipe is specified will be processed.\n\n```typescript\nimport { Post, Body } from '@nestjs/common';\n\n@Post()\ncreateSomething(\n  @Body('something', SomePipe) something\n) {\n  // ...\n}\n```\n\n#### Global Pipes\n\nDefined at the application level and applied to all incoming requests.\n\n```typescript\nimport { NestFactory } from '@nestjs/core';\nimport { ValidationPipe } from '@nestjs/common';\nimport { AppModule } from './app.module';\n\nasync function bootstrap(){\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n#### Parameter-Level vs. Handler-Level Pipes: Which One?\n\n**It depends**.\n\n**Parameter-level pipes** tend to be slimmer and cleaner. However, they often result in extra code added to handlers, which can get messy and hard to maintain.\n\n**Handler-level pipes** require some more code but provide some great benefits:\n\n- They do not require extra code at the parameter level.\n- They are easier to maintain and expand. If the shape of the data changes, it is easy to make the necessary changes within the pipe only.\n- The responsibility of identifying the arguments to process is shifted to one central file - the pipe file.\n- They promote the usage of DTOs (Data Transfer Objects), which is a very good practice.\n```\n                            +------------------------------+\n                            |                              |\n                            |   Incoming HTTP Request      |\n                            |   Method - POST              |\n                            |   Body - {                   |\n                            |    \"title\": \"example\"        |\n                            |   }                          |\n                            |                              |\n                            +----------------+-------------+\n                                            |\n                                            v\n                            +---------------+--------------+\n                            |                              |\n                            |     Handler is identified    |\n                            |                              |\n                            +---------------+--------------+\n                                            |\n                                            v\n                            +---------------+--------------+\n                            |                              |\n                            |            Pipe              |\n                            |                              |\n                            |  - Validates arguments       |\n                            |  - Transforms data           |\n                            |                              |\n                            +---------------+--------------+\n                                            |\n                                            v\n               +----------------------------+-------------------------+\n               |                                                      |\n               v                                                      v\n +-------------+------------------+                      +------------+---------------+\n |                                |                      |                            | \n |         Validation             |                      |        Validation          |\n |         Successful             |                      |        Failed              |\n |                                |                      |                            |\n +-------------+------------------+                      +------------+---------------+\n               |                                                      |\n               v                                                      v\n +-------------+------------------+                      +------------+---------------+\n |                                |                      |                            |\n |    Handler is called           |                      |    BadRequestException     |\n |    SomeController.create()     |                      |    is thrown               |\n |                                |                      |                            |\n +-------------+------------------+                      +------------+---------------+\n               |                                                      |\n               v                                                      v\n +-------------+------------------+                      +------------+---------------+\n |                                |                      |                            |\n |     HTTP Response Sent         |                      |     HTTP Response Sent     |\n |     Status: 201                |                      |     Status: 400            |\n |                                |                      |                            |\n +--------------------------------+                      +----------------------------+\n```","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmuhdhanish%2Flearning-nestjs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmuhdhanish%2Flearning-nestjs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmuhdhanish%2Flearning-nestjs/lists"}