Skip to content

Instantly share code, notes, and snippets.

@karthikkoruvada09
Last active January 30, 2025 19:37
Show Gist options
  • Select an option

  • Save karthikkoruvada09/f77f22bb9171a9d8a4ffb7d0250c34cb to your computer and use it in GitHub Desktop.

Select an option

Save karthikkoruvada09/f77f22bb9171a9d8a4ffb7d0250c34cb to your computer and use it in GitHub Desktop.
NestJs DI and core decorators overview 😇
NestJs:
- [ ] DI
- [ ] NestJS uses the IoC container
What are decorators:
- The Nest framework uses TypeScript decorators extensively to improve its modularity and code maintainability.
- Decorators then allow you to inject code into the actual definition of a class even before the class instance is created.
- In NestJS, Decorators are used to annotate and modify classes during design time. They also define metadata that NestJS uses to organize the application structure and dependencies.
Some core decorators that nestJs provides:
1) @Injectable() decorator is used in NestJS to mark a class as a provider that can be managed by the NestJS DI system
NestJs uses ‘reflect-metadata’ library to add metadata for provider classes
- This metadata includes the information about the class, its constructor params (dependencies), and methods that the DI system uses to resolve and inject required dependencies at runtime
2)  @Module() decorator provides metadata that NestJS uses to organize the application structure. @Module() decorator takes an object that can have properties like imports, controllers, providers, and exports.
3)  @Controller() decorator in NestJS is used to define and organize the routes and requests handling logic in your app. 
- When you decorate a class with @Controller(), you are providing metadata to NestJS which indicates that the class serves as a controller. Nest, in turn, will inspect the methods within the controllers and look for HTTP method decorators like @Get(), @Post() etc.
@Module takes these parameters:
- imports(only in app module I see), providers and controllers
Modules (@Module decorator)
Modules help organize your application into smaller parts. Each module groups related code, like controllers and services, making it easier to manage the codebase.
Services (@Injectable decorator)
The service classes are annotated with the @Injectable decorator so that they can be injected into controllers or other services using the dependency injection system.
Providers (@Injectable decorator)
- Providers are defined as classes with the @Injectable decorator, just like services.
- In order to make a provider available in the module, we need to import it into the module file. This is because we created the provider by hand and not by a NestJS CLI command as with the service we created earlier. CLI commands are available only for modules, services, and controllers.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment