[Nest.js] 4 - Provider

[Nest.js] 4 - Provider

Contents

1. Provider?

2. Dependency Injection

3. Service?

4. Create Service

1. Provider

- Many of the basic classes may be treated as Provider

-> Services, Repotories, Factories, Helpers, and so on.

https://docs.nestjs.com/providers

- Controllers should handle HTTP requests and responses.

- Provider should be assigned more complex tasks from Controller.

- Providers are plain JavaScript classes that are declared as providers in a module.

- Providers have a lifetime("Scope") synchronized with the application lifecycle.

-> ways to make provider lifetime request-scoped as well -> https://docs.nestjs.com/fundamentals/injection-scopes

2. Dependency Injection(DI)

- Main Idea is Dependency Injection(DI)

-> Objects can create various relationship with each other, and the function of

"Wiring up"("Connecting") instances of objects can largely be delegated to the Nest runtime system.

- In Nest, based on TypeScript capabilities, it is easy to manage dependendies because they are resolved by Type.

- Nest will resolve BoardsService by creating and returning an instance of BoardsService

-> or, in the normal case of a singleton, returning the existing instance if it has already been requested elsewhere

// board.controller.ts constructor(private boardsService: BoardsService){} // Constructor-based Injection

3. Service

- @Injectable() decorator attaches metadata,

which delares that a service is a class that can be managed by the Nest IoC Container

- Service instance can be used in everywhere of application.

- Service may be used for validatiing data or item creation into database.

4. Create Service using CLI

1 . CLI

$ nest g service boards // // "boards" is the name of service, // create BoardsService in boards.service.ts or $ nest g service boards --no-spec // --no-spec optio : exclude unit-test file

2. Look for a "boards" folder

3. Created "boards.service.ts" in the folder

4. Imported and Registerd the controller in its module "boards.module.ts" automatically

from http://jinseo-copy-and-paste.tistory.com/10 by ccl(A) rewrite - 2021-09-08 16:27:31