-
ProvidersNode.js/Nest 2023. 9. 8. 16:54
Nest.js의 Providers에 대해 정리하였습니다.
< Providers >
The main idea of a provider is that it can be injected as a dependency; this means objects can create various relationships with each other, and the function of "wiring up" these objects can largely be delegated to the Nest runtime system.
Many of the basic Nest classes may be treated as a provider – services, repositories, factories, helpers, and so on.
< Services >
Service will be responsible for data storage and retrieval.
Ex)
cats.service.ts
import { Injectable } from '@nestjs/common'; import { Cat } from './interfaces/cat.interface'; @Injectable() export class CatsService { private readonly cats: Cat[] = []; create(cat: Cat) { this.cats.push(cat); } findAll(): Cat[] { return this.cats; } }
: The @Injectable( ) decorator attaches metadata, which declares that CatsService is a class that can be managed by the Nest IoC container.
cats.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common'; import { CreateCatDto } from './dto/create-cat.dto'; import { CatsService } from './cats.service'; import { Cat } from './interfaces/cat.interface'; @Controller('cats') export class CatsController { constructor(private catsService: CatsService) {} @Post() async create(@Body() createCatDto: CreateCatDto) { this.catsService.create(createCatDto); } @Get() async findAll(): Promise<Cat[]> { return this.catsService.findAll(); } }
: The CatsService is injected through the class constructor. Notice the use of the private syntax. This shorthand allows us to both declare and initialize the CatsService member immediately in the same location.
< Scopes >
Providers normally have a lifetime ("scope") synchronized with the application lifecycle. When the application is bootstrapped, every dependency must be resolved, and therefore every provider has to be instantiated. Similarly, when the application shuts down, each provider will be destroyed. However, there are ways to make your provider lifetime request-scoped as well. You can read more about these techniques here.
< Providers Registration >
we need to register the service with Nest so that it can perform the injection. We do this by editing our module file (app.module.ts) and adding the service to the providers array of the @Module( ) decorator.
Ex)
import { Module } from '@nestjs/common'; import { CatsController } from './cats/cats.controller'; import { CatsService } from './cats/cats.service'; @Module({ controllers: [CatsController], providers: [CatsService], }) export class AppModule {}
References : https://docs.nestjs.com/providers
'Node.js > Nest' 카테고리의 다른 글
Exception Filters (0) 2023.10.30 Middlewares (0) 2023.10.18 Modules (0) 2023.09.26 Controllers (0) 2023.08.23 Nest (0) 2023.08.19