[
  {
    "path": ".gitignore",
    "content": ".idea\n"
  },
  {
    "path": "README.md",
    "content": "# NestJS 한국어 메뉴얼\n\n## NestJS 프레임워크\n\nNestJS는 Typescript 에서 사용할 수 있는 가장 모던하고 세련된 프레임워크이며, 유연하고 세련된 기능을 제공합니다. NestJS는 Typescript개발이 즐겁고 좀더 창의적일 수 있도록 하기 위해서 만들어졌습니다. NestJS를 사용하면 Typescript를 사용한 웹 개발에 있어서, 보다 중요한 비지니스 로직을 구현하는데 집중할 수 있습니다.\n\n## 기여방법\n\nNestJS의 한글 매뉴얼은 많은 분들의 기여를 필요로합니다. 계속해서 업데이트를 해나갈 예정이며, 자유로운 번역을 통해 한국어 메뉴얼을 더욱 완성도 있는 형태로 만들어 나갈것입니다.\n\n* 오타나 수정사항에 대해서는 `Pull Request`를 보내주시면 리뷰를 통해 반영됩니다.\n* 새로운 번역도 자유롭게 `Pull Request`를 보내주시면 리뷰를 통해 반영됩니다.\n\n### 1. Issue\n\n이 레포지토리 `Issue` 에 수정 요청사항을 등록해주시면 됩니다.\n\n### 2. Pull Request\n\n`Pull Request`의 경우 규칙에 따라 등록을 해주셔야 합니다. 자세한 사항은 [Discussions](https://github.com/nestjskr/docs.nestjs.kr/discussions) 를 참조해 주시기 바랍니다.\n\n## 기여자 보상\n\n* 매뉴얼 레포지터리의 `README.md` 하단에 기여자 리스트를 표시할 예정입니다.\n\n## 라이센스\n\nNestJS 한국어 매뉴얼은 영문 매뉴얼과 동일하게 `MIT 라이센스`를 따릅니다.\n\n## 커뮤니티\n\nNestJS 번역에 관련된 커뮤니티는 이 레포지토리의 [Discussions](https://github.com/nestjskr/docs.nestjs.kr/discussions) 을 활용합니다.\n\n* [NestJS Korea 슬랙 참여하기](https://join.slack.com/t/nestjskorea/shared_invite/zt-1i1rac8s3-EOHU_8SKjNsgtoeHtnS1Hg)\n* [NestJS Korea 카카오톡 오픈 채팅방](https://open.kakao.com/o/ggLiN79c)\n* [NestJS 한국어 메뉴얼 번역 Discussions](https://github.com/nestjskr/docs.nestjs.kr/discussions)\n"
  },
  {
    "path": "content/application-context.md",
    "content": "### Standalone applications\n\nThere are several ways of mounting a Nest application. You can create a web app, a microservice or just a bare Nest **standalone application** (without any network listeners). The Nest standalone application is a wrapper around the Nest **IoC container**, which holds all instantiated classes. We can obtain a reference to any existing instance from within any imported module directly using the standalone application object. Thus, you can take advantage of the Nest framework anywhere, including, for example, scripted **CRON** jobs. You can even build a **CLI** on top of it.\n\n#### Getting started\n\nTo create a Nest standalone application, use the following construction:\n\n```typescript\n@@filename()\nasync function bootstrap() {\n  const app = await NestFactory.createApplicationContext(AppModule);\n  // application logic...\n}\nbootstrap();\n```\n\nThe standalone application object allows you to obtain a reference to any instance registered within the Nest application. Let's imagine that we have a `TasksService` in the `TasksModule`. This class provides a set of methods that we want to call from within a CRON job.\n\n```typescript\n@@filename()\nconst app = await NestFactory.createApplicationContext(AppModule);\nconst tasksService = app.get(TasksService);\n```\n\nTo access the `TasksService` instance we use the `get()` method. The `get()` method acts like a **query** that searches for an instance in each registered module. Alternatively, for strict context checking, pass an options object with the `strict: true` property. With this option in effect, you have to navigate through specific modules to obtain a particular instance from the selected context.\n\n```typescript\n@@filename()\nconst app = await NestFactory.createApplicationContext(AppModule);\nconst tasksService = app.select(TasksModule).get(TasksService, { strict: true });\n```\n\nFollowing is a summary of the methods available for retrieving instance references from the standalone application object.\n\n<table>\n  <tr>\n    <td>\n      <code>get()</code>\n    </td>\n    <td>\n      Retrieves an instance of a controller or provider (including guards, filters, and so on) available in the application context.\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>select()</code>\n    </td>\n    <td>\n      Navigates through the modules graph to pull out a specific instance from the selected module (used together with strict mode as described above).\n    </td>\n  </tr>\n</table>\n\n> info **Hint** In non-strict mode, the root module is selected by default. To select any other module, you need to navigate the modules graph manually, step by step.\n\nIf you want the node application to close after the script finishes (e.g., for a script running CRON jobs), add `await app.close()` to the end of your `bootstrap` function:\n\n```typescript\n@@filename()\nasync function bootstrap() {\n  const app = await NestFactory.createApplicationContext(AppModule);\n  // application logic...\n  await app.close();\n}\nbootstrap();\n```\n\n#### Example \n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/18-context).\n"
  },
  {
    "path": "content/cli/libraries.md",
    "content": "### Libraries\n\n많은 애플리케이션들은 동일한 일반적인 문제들을 해결하거나, 몇몇 다른 컨텍스트에서 모듈러 컴포넌트들을 재사용할 필요가 있습니다. Nest는 이러한 문제를 해결하는 몇 가지 방법이 있지만, 각 방법들은 다른 구조적, 조직적 목표를 충족시키는데 도움을 주는 방식으로 해당 문제를 해결하기 위해 서로 다른 수준에서 동작합니다.\n\nNest [모듈](/modules)들은 하나의 애플리케이션 내에서 컴포넌트들을 공유를 가능하게하는 실행 컨텍스트를 제공하는데 유용합니다. 모듈들은 또한 다른 프로젝트에 설치할 수 있는 재사용가능한 라이브러리를 생성하기 위해 [npm](https://npmjs.com)으로 패키징될 수 있습니다. 이것은 서로 다르거나, 느슨하게 연결되거나 독립적인 조직에서 사용되는 설정가능하고, 재사용가능한 라이브러리를 배포하는데 효과적인 방법이 될 수 있습니다 (예: 서드파티 라이브러리 배포/설치).\n\n밀접하게 조직된 그룹들 사이에서(예: 회사/프로젝트 경계 내에서) 코드를 공유하기 위해서, 컴포넌트 공유에 대해 더 가볍게 접근하는 것은 유용할 수 있습니다. Monorepos는 이것을 가능하게 하는 구조로 생겨났고, Monorepo 내에서 **라이브러리**는 코드를 쉽고, 가벼운 방식으로 공유하는 방법을 제공합니다. Nest monorepo에서, 라이브러리를 사용하는 것은 컴포넌트를 공유하는 애플리케이션의 쉬운 조립을 가능하게 합니다. 실제로, 이것은 모듈러 컴포넌트들을 구축하고 구성하는데 초점을 맞추기 위해 모놀리식 애플리케이션과 개발 프로세스의 분해를 권장합니다.\n\n#### Nest libraries\n\nA Nest library is a Nest project that differs from an application in that it cannot run on its own. A library must be imported into a containing application in order for its code to execute. The built-in support for libraries described in this section is only available for **monorepos** (standard mode projects can achieve similar functionality using npm packages).\n\nFor example, an organization may develop an `AuthModule` that manages authentication by implementing company policies that govern all internal applications. Rather than build that module separately for each application, or physically packaging the code with npm and requiring each project to install it, a monorepo can define this module as a library. When organized this way, all consumers of the library module can see an up-to-date version of the `AuthModule` as it is committed. This can have significant benefits for coordinating component development and assembly, and simplifying end-to-end testing.\n\n#### Creating libraries\n\nAny functionality that is suitable for re-use is a candidate for being managed as a library. Deciding what should be a library, and what should be part of an application, is an architectural design decision. Creating libraries involves more than simply copying code from an existing application to a new library. When packaged as a library, the library code must be decoupled from the application. This may require **more** time up front and force some design decisions that you may not face with more tightly coupled code. But this additional effort can pay off when the library can be used to enable more rapid application assembly across multiple applications.\n\nTo get started with creating a library, run the following command:\n\n```bash\nnest g library my-library\n```\n\nWhen you run the command, the `library` schematic prompts you for a prefix (AKA alias) for the library:\n\n```bash\nWhat prefix would you like to use for the library (default: @app)?\n```\n\nThis creates a new project in your workspace called `my-library`.\nA library-type project, like an application-type project, is generated into a named folder using a schematic. Libraries are managed under the `libs` folder of the monorepo root. Nest creates the `libs` folder the first time a library is created.\n\nThe files generated for a library are slightly different from those generated for an application. Here is the contents of the `libs` folder after executing the command above:\n\n<div class=\"file-tree\">\n  <div class=\"item\">libs</div>\n  <div class=\"children\">\n    <div class=\"item\">my-library</div>\n    <div class=\"children\">\n      <div class=\"item\">src</div>\n      <div class=\"children\">\n        <div class=\"item\">index.ts</div>\n        <div class=\"item\">my-library.module.ts</div>\n        <div class=\"item\">my-library.service.ts</div>\n      </div>\n      <div class=\"item\">tsconfig.lib.json</div>\n    </div>\n  </div>\n</div>\n\nThe `nest-cli.json` file will have a new entry for the library under the `\"projects\"` key:\n\n```javascript\n...\n{\n    \"my-library\": {\n      \"type\": \"library\",\n      \"root\": \"libs/my-library\",\n      \"entryFile\": \"index\",\n      \"sourceRoot\": \"libs/my-library/src\",\n      \"compilerOptions\": {\n        \"tsConfigPath\": \"libs/my-library/tsconfig.lib.json\"\n      }\n}\n...\n```\n\nThere are two differences in `nest-cli.json` metadata between libraries and applications:\n\n- the `\"type\"` property is set to `\"library\"` instead of `\"application\"`\n- the `\"entryFile\"` property is set to `\"index\"` instead of `\"main\"`\n\nThese differences key the build process to handle libraries appropriately. For example, a library exports its functions through the `index.js` file.\n\nAs with application-type projects, libraries each have their own `tsconfig.lib.json` file that extends the root (monorepo-wide) `tsconfig.json` file. You can modify this file, if necessary, to provide library-specific compiler options.\n\nYou can build the library with the CLI command:\n\n```bash\nnest build my-library\n```\n\n#### Using libraries\n\nWith the automatically generated configuration files in place, using libraries is straightforward. How would we import `MyLibraryService` from the `my-library` library into the `my-project` application?\n\nFirst, note that using library modules is the same as using any other Nest module. What the monorepo does is manage paths in a way that importing libraries and generating builds is now transparent. To use `MyLibraryService`, we need to import its declaring module. We can modify `my-project/src/app.module.ts` as follows to import `MyLibraryModule`.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { MyLibraryModule } from '@app/my-library';\n\n@Module({\n  imports: [MyLibraryModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\nNotice above that we've used a path alias of `@app` in the ES module `import` line, which was the `prefix` we supplied with the `nest g library` command above. Under the covers, Nest handles this through tsconfig path mapping. When adding a library, Nest updates the global (monorepo) `tsconfig.json` file's `\"paths\"` key like this:\n\n```javascript\n\"paths\": {\n    \"@app/my-library\": [\n        \"libs/my-library/src\"\n    ],\n    \"@app/my-library/*\": [\n        \"libs/my-library/src/*\"\n    ]\n}\n```\n\nSo, in a nutshell, the combination of the monorepo and library features has made it easy and intuitive to include library modules into applications.\n\nThis same mechanism enables building and deploying applications that compose libraries. Once you've imported the `MyLibraryModule`, running `nest build` handles all the module resolution automatically and bundles the app along with any library dependencies, for deployment. The default compiler for a monorepo is **webpack**, so the resulting distribution file is a single file that bundles all of the transpiled JavaScript files into a single file. You can also switch to `tsc` as described <a href=\"https://docs.nestjs.com/cli/monorepo#global-compiler-options\">here</a>.\n"
  },
  {
    "path": "content/cli/overview.md",
    "content": "### 시작하기\n\n[Nest CLI](https://github.com/nestjs/nest-cli) 는 Nest application 초기화, 개발 및 유지보수 하는데 도움이 되는 명령줄-인터페이스 도구입니다. 프로젝트 스케폴딩, 개발모드 제공, 빌드 및 번들링 도구 등 다양한 방법을 지원 합니다. 이 도구는 잘 구성된 아키텍쳐 패턴들을 구현하여 여러분의 애플리케이션이 견고한 구조를 가질 수 있도록 합니다.\n\n#### 설치\n\n**참고**: 이 가이드에서는 [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 을 사용하여 Nest CLI를 포함한 패키지를 설치하는 방법에 대해 설명합니다. 선호하는 다른 패키지 매니저를 사용해도 좋습니다. npm 을 사용하면 OS 명령줄에서 `nest` CLI 바이너리 파일의 위치를 찾는 데 몇 가지 옵션을 사용할 수 있습니다. 여기서는 `-g`옵션을 사용하여 `nest` 바이너리를 전역으로 설치하는 방법을 설명합니다. 이는 어느정도의 편의성을 제공하며, 해당 설치 방법을 전제로 문서를 작성 하였습니다. **어떠한** `npm` 패키지를 전역으로 설치하면 올바른 버전이 실행되고 있는지 확인하는 책임은 사용자에게 있습니다. 또한 다른 프로젝트 이더라도 **같은** 버전의 CLI 를 실행 한다는 걸 의미합니다. 합리적인 대안은 [npx](https://github.com/npm/npx) 프로그램(또는 다른 패키지 매니저와 유사한 기능)을 사용하여 Nest CLI의 **managed version**을(를) 실행하는 것입니다. 자세한 내용은 [npx 설명서](https://github.com/npm/npx) 및/또는 DevOps 지원 담당자에게 문의하세요.\n\n`npm install -g` 명령을 사용하여 CLI를 전역으로 설치합니다. (전역 설치에 대한 자세한 내용은 위의 **참고** 항목을 참조하세요).\n\n```bash\n$ npm install -g @nestjs/cli\n```\n\n#### 기본 흐름\n\n설치되면 `nest` 실행 파일을 통해 OS 명령줄에서 직접 CLI 명령을 호출할 수 있습니다. 다음을 입력하여 사용 가능한 `nest` 명령을 확인해 보세요\n\n```bash\n$ nest --help\n```\n\n다음과 같은 구문을 사용하여 개별적인 명령어에 대한 도움말을 볼 수 있습니다. `new`, `add`등과 같은 명령어에 대한 자세한 도움말을 보려면 아래의 예에서 `generate` 자리에 명령어를 입력하면 됩니다.\n\n```bash\n$ nest generate --help\n```\n\n개발 모드에서 새로운 Nest 프로젝트를 생성하거나 빌드, 실행 시키려면 프로젝트의 상위 폴더로 이동한 후 다음 명령어를 실행합니다.\n\n```bash\n$ nest new my-nest-project\n$ cd my-nest-project\n$ npm run start:dev\n```\n\n브라우저에서 [http://localhost:3000](http://localhost:3000)을 열어 실행 중인 애플리케션을 확인합니다. 소스 파일을 변경하면 앱이 자동으로 다시 컴파일하고 로드합니다.\n\n#### 프로젝트 구조\n\n`nest new` 를 실행하면 Nest는 새 폴더를 만들고 초기 설정파일들을 만들어 boilerplate 애플리케이션 구조를 생성합니다. 이 문서의 설명에 따라 기본 구조에서 새 컴포넌트를 추가하면서 작업을 이어나가면 됩니다. 우리는 `nest new` 로 생성한 프로젝트의 구조를 **standard mode** 라고 부릅니다. 또한 Nest는 **monorepo mode** 라고 하는 여러 프로젝트 및 라이브러리를 관리하기위한 대체 구조를 지원합니다.\n\n**build** 프로세스가 작동하는 방식과 내장 [라이브러리](/cli/library) 지원에 대한 몇 가지 구체적인 고려 사항 외에도(기본적으로 monorepo mode 는 monorepo-style의 프로젝트 구조에서 발생할 수 있는 빌드 복잡성을 단순화합니다), 나머지 Nest 기능 과 이 문서는 standard mode 및 monorepo mode 프로젝트 구조 모두에 동일하게 적용됩니다. 나중에 언제든지 standard mode에서 monorepo mode로 쉽게 전환할 수 있으므로 Nest에 대해 배우는 동안 이 결정을 하지 않아도 괜찮습니다.\n\n두 모드 중 하나를 사용하여 여러 프로젝트를 관리할 수 있습니다. 다음은 각 모드의 차이점을 간단히 요약한 것입니다.\n\n| Feature                                               | Standard Mode                                                      | Monorepo Mode                                              |\n| ----------------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------- |\n| Multiple projects                                     | Separate file system structure                                     | Single file system structure                               |\n| `node_modules` & `package.json`                       | Separate instances                                                 | Shared across monorepo                                     |\n| Default compiler                                      | `tsc`                                                              | webpack                                                    |\n| Compiler settings                                     | Specified separately                                               | Monorepo defaults that can be overridden per project       |\n| Config files like `.eslintrc.js`, `.prettierrc`, etc. | Specified separately                                               | Shared across monorepo                                     |\n| `nest build` and `nest start` commands                | Target defaults automatically to the (only) project in the context | Target defaults to the **default project** in the monorepo |\n| Libraries                                             | Managed manually, usually via npm packaging                        | Built-in support, including path management and bundling   |\n\n가장 적합한 모드를 결정하는 데 도움이 되는 자세한 내용은 [Workspaces](/cli/monorepo) 및 [Libraries](/cli/libraries) 섹션을 참조하세요.\n\n<app-banner-courses></app-banner-courses>\n\n#### CLI 명령어 문법\n\n모든 `nest` 명령어들은 동일한 형식을 따릅니다\n\n```bash\nnest commandOrAlias requiredArg [optionalArg] [options]\n```\n\n예시:\n\n```bash\n$ nest new my-nest-project --dry-run\n```\n\n여기서 `new` 는 _commandOrAlias_ 입니다.`new` 의 별칭은 `n` 입니다. `my-nest-project` 는 _requiredArg_ 입니다. _requiredArg_ 가 입력되지 않은 경우, `nest` 에서 이를 입력하라고 합니다. 또한, `--dry-run` 의 약식 표현은 `-d` 입니다. 이 점을 참고하면, 다음 명령은 위의 명령과 동일합니다.\n\n```bash\n$ nest n my-nest-project -d\n```\n\n대부분의 명령과 일부 옵션에는 별칭이 있습니다. `nest new --help` 를 실행하여 이러한 옵션과 별칭들을 보고 위의 구조에 대해 이해했는지 확인하세요.\n\n#### 명령어 정리\n\n명령별 옵션을 보려면 다음 명령어들 중 하나에 대해 `nest <command> --help` 를 실행하세요.\n\n각 명령에 대한 자세한 내용은 [usage](/cli/uses)를 참조하세요.\n\n| Command    | Alias | Description                                                                                           |\n| ---------- | ----- | ----------------------------------------------------------------------------------------------------- |\n| `new`      | `n`   | Scaffolds a new _standard mode_ application with all boilerplate files needed to run.                 |\n| `generate` | `g`   | Generates and/or modifies files based on a schematic.                                                 |\n| `build`    |       | Compiles an application or workspace into an output folder.                                           |\n| `start`    |       | Compiles and runs an application (or default project in a workspace).                                 |\n| `add`      |       | Imports a library that has been packaged as a **nest library**, running its install schematic.        |\n| `update`   | `u`   | Update `@nestjs` dependencies in the `package.json` `\"dependencies\"` list to their `@latest` version. |\n| `info`     | `i`   | Displays information about installed nest packages and other helpful system info.                     |\n"
  },
  {
    "path": "content/cli/scripts.md",
    "content": "### Nest CLI and scripts\n\nThis section provides additional background on how the `nest` command interacts with compilers and scripts to help DevOps personnel manage the development environment.\n\nA Nest application is a **standard** TypeScript application that needs to be compiled to JavaScript before it can be executed. There are various ways to accomplish the compilation step, and developers/teams are free to choose a way that works best for them. With that in mind, Nest provides a set of tools out-of-the-box that seek to do the following:\n\n- Provide a standard build/execute process, available at the command line, that \"just works\" with reasonable defaults.\n- Ensure that the build/execute process is **open**, so developers can directly access the underlying tools to customize them using native features and options.\n- Remain a completely standard TypeScript/Node.js framework, so that the entire compile/deploy/execute pipeline can be managed by any external tools that the development team chooses to use.\n\nThis goal is accomplished through a combination of the `nest` command, a locally installed TypeScript compiler, and `package.json` scripts. We describe how these technologies work together below. This should help you understand what's happening at each step of the build/execute process, and how to customize that behavior if necessary.\n\n#### The nest binary\n\nThe `nest` command is an OS level binary (i.e., runs from the OS command line). This command actually encompasses 3 distinct areas, described below. We recommend that you run the build (`nest build`) and execution (`nest start`) sub-commands via the `package.json` scripts provided automatically when a project is scaffolded (see [typescript starter](https://github.com/nestjs/typescript-starter) if you wish to start by cloning a repo, instead of running `nest new`).\n\n#### Build\n\n`nest build` is a wrapper on top of the standard `tsc` compiler (for [standard projects](https://docs.nestjs.com/cli/overview#project-structure)) or the webpack compiler (for [monorepos](https://docs.nestjs.com/cli/overview#project-structure)). It does not add any other compilation features or steps except for handling `tsconfig-paths` out of the box. The reason it exists is that most developers, especially when starting out with Nest, do not need to adjust compiler options (e.g., `tsconfig.json` file) which can sometimes be tricky.\n\nSee the [nest build](https://docs.nestjs.com/cli/usages#nest-build) documentation for more details.\n\n#### Execution\n\n`nest start` simply ensures the project has been built (same as `nest build`), then invokes the `node` command in a portable, easy way to execute the compiled application. As with builds, you are free to customize this process as needed, either using the `nest start` command and its options, or completely replacing it. The entire process is a standard TypeScript application build and execute pipeline, and you are free to manage the process as such.\n\nSee the [nest start](https://docs.nestjs.com/cli/usages#nest-start) documentation for more details.\n\n#### Generation\n\nThe `nest generate` commands, as the name implies, generate new Nest projects, or components within them.\n\n#### Package scripts\n\nRunning the `nest` commands at the OS command level requires that the `nest` binary be installed globally. This is a standard feature of npm, and outside of Nest's direct control. One consequence of this is that the globally installed `nest` binary is **not** managed as a project dependency in `package.json`. For example, two different developers can be running two different versions of the `nest` binary. The standard solution for this is to use package scripts so that you can treat the tools used in the build and execute steps as development dependencies.\n\nWhen you run `nest new`, or clone the [typescript starter](https://github.com/nestjs/typescript-starter), Nest populates the new project's `package.json` scripts with commands like `build` and `start`. It also installs the underlying compiler tools (such as `typescript`) as **dev dependencies**.\n\nYou run the build and execute scripts with commands like:\n\n```bash\n$ npm run build\n```\n\nand\n\n```bash\n$ npm run start\n```\n\nThese commands use npm's script running capabilities to execute `nest build` or `nest start` using the **locally installed** `nest` binary. By using these built-in package scripts, you have full dependency management over the Nest CLI commands\\*. This means that, by following this **recommended** usage, all members of your organization can be assured of running the same version of the commands.\n\n\\*This applies to the `build` and `start` commands. The `nest new` and `nest generate` commands aren't part of the build/execute pipeline, so they operate in a different context, and do not come with built-in `package.json` scripts.\n\nFor most developers/teams, it is recommended to utilize the package scripts for building and executing their Nest projects. You can fully customize the behavior of these scripts via their options (`--path`, `--webpack`, `--webpackPath`) and/or customize the `tsc` or webpack compiler options files (e.g., `tsconfig.json`) as needed. You are also free to run a completely custom build process to compile the TypeScript (or even to execute TypeScript directly with `ts-node`).\n\n#### Backward compatibility\n\nBecause Nest applications are pure TypeScript applications, previous versions of the Nest build/execute scripts will continue to operate. You are not required to upgrade them. You can choose to take advantage of the new `nest build` and `nest start` commands when you are ready, or continue running previous or customized scripts.\n\n#### Migration\n\nWhile you are not required to make any changes, you may want to migrate to using the new CLI commands instead of using tools such as `tsc-watch` or `ts-node`. In this case, simply install the latest version of the `@nestjs/cli`, both globally and locally:\n\n```bash\n$ npm install -g @nestjs/cli\n$ cd  /some/project/root/folder\n$ npm install -D @nestjs/cli\n```\n\nYou can then replace the `scripts` defined in `package.json` with the following ones:\n\n```typescript\n\"build\": \"nest build\",\n\"start\": \"nest start\",\n\"start:dev\": \"nest start --watch\",\n\"start:debug\": \"nest start --debug --watch\",\n```\n"
  },
  {
    "path": "content/cli/usages.md",
    "content": "### CLI command reference\n\n#### nest new\n\nCreates a new (standard mode) Nest project.\n\n```bash\n$ nest new <name> [options]\n$ nest n <name> [options]\n```\n\n##### Description\n\nCreates and initializes a new Nest project. Prompts for package manager.\n\n- Creates a folder with the given `<name>`\n- Populates the folder with configuration files\n- Creates sub-folders for source code (`/src`) and end-to-end tests (`/test`)\n- Populates the sub-folders with default files for app components and tests\n\n##### Arguments\n\n| Argument | Description                 |\n| -------- | --------------------------- |\n| `<name>` | The name of the new project |\n\n##### Options\n\n| Option                                | Description                                                                                                     |\n| ------------------------------------- | --------------------------------------------------------------------------------------------------------------- |\n| `--dry-run`                           | Reports changes that would be made, but does not change the filesystem.<br/> Alias: `-d`                        |\n| `--skip-git`                          | Skip git repository initialization.<br/> Alias: `-g`                                                            |\n| `--skip-install`                      | Skip package installation.<br/> Alias: `-s`                                                                     |\n| `--package-manager [package-manager]` | Specify package manager. Use `npm`, `yarn`, or `pnpm`. Package manager must be installed globally.<br/> Alias: `-p`      |\n| `--language [language]`               | Specify programming language (`TS` or `JS`).<br/> Alias: `-l`                                                   |\n| `--collection [collectionName]`       | Specify schematics collection. Use package name of installed npm package containing schematic.<br/> Alias: `-c` |\n\n#### nest generate\n\nGenerates and/or modifies files based on a schematic\n\n```bash\n$ nest generate <schematic> <name> [options]\n$ nest g <schematic> <name> [options]\n```\n\n##### Arguments\n\n| Argument      | Description                                                                                              |\n| ------------- | -------------------------------------------------------------------------------------------------------- |\n| `<schematic>` | The `schematic` or `collection:schematic` to generate. See the table below for the available schematics. |\n| `<name>`      | The name of the generated component.                                                                     |\n\n##### Schematics\n\n| Name          | Alias | Description                                                                                         |\n| ------------- | ----- | --------------------------------------------------------------------------------------------------- |\n| `app`         |       | Generate a new application within a monorepo (converting to monorepo if it's a standard structure). |\n| `library`     | `lib` | Generate a new library within a monorepo (converting to monorepo if it's a standard structure).     |\n| `class`       | `cl`  | Generate a new class.                                                                               |\n| `controller`  | `co`  | Generate a controller declaration.                                                                  |\n| `decorator`   | `d`   | Generate a custom decorator.                                                                        |\n| `filter`      | `f`   | Generate a filter declaration.                                                                      |\n| `gateway`     | `ga`  | Generate a gateway declaration.                                                                     |\n| `guard`       | `gu`  | Generate a guard declaration.                                                                       |\n| `interface`   |       | Generate an interface.                                                                              |\n| `interceptor` | `in`  | Generate an interceptor declaration.                                                                |\n| `middleware`  | `mi`  | Generate a middleware declaration.                                                                  |\n| `module`      | `mo`  | Generate a module declaration.                                                                      |\n| `pipe`        | `pi`  | Generate a pipe declaration.                                                                        |\n| `provider`    | `pr`  | Generate a provider declaration.                                                                    |\n| `resolver`    | `r`   | Generate a resolver declaration.\n| `resource`    | `res` | Generate a new CRUD resource. See the [CRUD (resource) generator](/recipes/crud-generator) for more details.                                                                    |\n| `service`     | `s`   | Generate a service declaration.                                                                    |\n\n##### Options\n\n| Option                          | Description                                                                                                     |\n| ------------------------------- | --------------------------------------------------------------------------------------------------------------- |\n| `--dry-run`                     | Reports changes that would be made, but does not change the filesystem.<br/> Alias: `-d`                        |\n| `--project [project]`           | Project that element should be added to.<br/> Alias: `-p`                                                       |\n| `--flat`                        | Do not generate a folder for the element.                                                                       |\n| `--collection [collectionName]` | Specify schematics collection. Use package name of installed npm package containing schematic.<br/> Alias: `-c` |\n| `--spec`                        | Enforce spec files generation (default)                                                                         |\n| `--no-spec`                     | Disable spec files generation                                                                                   |\n\n#### nest build\n\nCompiles an application or workspace into an output folder.\n\n```bash\n$ nest build <name> [options]\n```\n\n##### Arguments\n\n| Argument | Description                       |\n| -------- | --------------------------------- |\n| `<name>` | The name of the project to build. |\n\n##### Options\n\n| Option            | Description                                            |\n| ----------------- | ------------------------------------------------------ |\n| `--path [path]`   | Path to `tsconfig` file. <br/>Alias `-p`               |\n| `--config [path]` | Path to `nest-cli` configuration file. <br/>Alias `-c` |\n| `--watch`         | Run in watch mode (live-reload) <br/>Alias `-w`        |\n| `--webpack`       | Use webpack for compilation.                           |\n| `--webpackPath`   | Path to webpack configuration.                         |\n| `--tsc`           | Force use `tsc` for compilation.                       |\n\n#### nest start\n\nCompiles and runs an application (or default project in a workspace).\n\n```bash\n$ nest start <name> [options]\n```\n\n##### Arguments\n\n| Argument | Description                     |\n| -------- | ------------------------------- |\n| `<name>` | The name of the project to run. |\n\n##### Options\n\n| Option                  | Description                                                                                                          |\n| ----------------------- | -------------------------------------------------------------------------------------------------------------------- |\n| `--path [path]`         | Path to `tsconfig` file. <br/>Alias `-p`                                                                             |\n| `--config [path]`       | Path to `nest-cli` configuration file. <br/>Alias `-c`                                                               |\n| `--watch`               | Run in watch mode (live-reload) <br/>Alias `-w`                                                                      |\n| `--preserveWatchOutput` | Keep outdated console output in watch mode instead of clearing the screen. (`tsc` watch mode only)                   |\n| `--watchAssets`         | Run in watch mode (live-reload), watching non-TS files (assets). See [Assets](cli/monorepo#assets) for more details. |\n| `--debug [hostport]`    | Run in debug mode (with --inspect flag) <br/>Alias `-d`                                                              |\n| `--webpack`             | Use webpack for compilation.                                                                                         |\n| `--webpackPath`         | Path to webpack configuration.                                                                                       |\n| `--tsc`                 | Force use `tsc` for compilation.                                                                                     |\n| `--exec [binary]`       | Binary to run (default: `node`). <br/>Alias `-e`                                                                     |\n\n#### nest add\n\nImports a library that has been packaged as a **nest library**, running its install schematic.\n\n```bash\n$ nest add <name> [options]\n```\n\n##### Arguments\n\n| Argument | Description                        |\n| -------- | ---------------------------------- |\n| `<name>` | The name of the library to import. |\n\n#### nest update\n\nUpdates `@nestjs` dependencies in the `package.json` `\"dependencies\"` list to their `@latest` version.\n\n##### Options\n\n| Option    | Description                                                              |\n| --------- | ------------------------------------------------------------------------ |\n| `--force` | Do **upgrade** instead of update <br/>Alias `-f`                         |\n| `--tag`   | Update to tagged version (use `@latest`, `@<tag>`, etc) <br/>Alias `-t` |  |\n\n#### nest info\n\nDisplays information about installed nest packages and other helpful system info. For example:\n\n```bash\n$ nest info\n```\n\n```bash\n _   _             _      ___  _____  _____  _     _____\n| \\ | |           | |    |_  |/  ___|/  __ \\| |   |_   _|\n|  \\| |  ___  ___ | |_     | |\\ `--. | /  \\/| |     | |\n| . ` | / _ \\/ __|| __|    | | `--. \\| |    | |     | |\n| |\\  ||  __/\\__ \\| |_ /\\__/ //\\__/ /| \\__/\\| |_____| |_\n\\_| \\_/ \\___||___/ \\__|\\____/ \\____/  \\____/\\_____/\\___/\n\n[System Information]\nOS Version : macOS High Sierra\nNodeJS Version : v8.9.0\nYARN Version : 1.5.1\n[Nest Information]\nmicroservices version : 6.0.0\nwebsockets version : 6.0.0\ntesting version : 6.0.0\ncommon version : 6.0.0\ncore version : 6.0.0\n```\n"
  },
  {
    "path": "content/cli/workspaces.md",
    "content": "### Workspaces\n\nNest has two modes for organizing code:\n\n- **standard mode**: useful for building individual project-focused applications that have their own dependencies and settings, and don't need to optimize for sharing modules, or optimizing complex builds. This is the default mode.\n- **monorepo mode**: this mode treats code artifacts as part of a lightweight **monorepo**, and may be more appropriate for teams of developers and/or multi-project environments. It automates parts of the build process to make it easy to create and compose modular components, promotes code re-use, makes integration testing easier, makes it easy to share project-wide artifacts like `eslint` rules and other configuration policies, and is easier to use than alternatives like github submodules. Monorepo mode employs the concept of a **workspace**, represented in the `nest-cli.json` file, to coordinate the relationship between the components of the monorepo.\n\nIt's important to note that virtually all of Nest's features are independent of your code organization mode. The **only** affect of this choice is how your projects are composed and how build artifacts are generated. All other functionality, from the CLI to core modules to add-on modules work the same in either mode.\n\nAlso, you can easily switch from **standard mode** to **monorepo mode** at any time, so you can delay this decision until the benefits of one or the other approach become more clear.\n\n#### Standard mode\n\nWhen you run `nest new`, a new **project** is created for you using a built-in schematic. Nest does the following:\n\n1. Create a new folder, corresponding to the `name` argument you provide to `nest new`\n2. Populate that folder with default files corresponding to a minimal base-level Nest application. You can examine these files at the [typescript-starter](https://github.com/nestjs/typescript-starter) repository.\n3. Provide additional files such as `nest-cli.json`, `package.json` and `tsconfig.json` that configure and enable various tools for compiling, testing and serving your application.\n\nFrom there, you can modify the starter files, add new components, add dependencies (e.g., `npm install`), and otherwise develop your application as covered in the rest of this documentation.\n\n#### Monorepo mode\n\nTo enable monorepo mode, you start with a _standard mode_ structure, and add **projects**. A project can be a full **application** (which you add to the workspace with the command `nest generate app`) or a **library** (which you add to the workspace with the command `nest generate library`). We'll discuss the details of these specific types of project components below. The key point to note now is that it is the **act of adding a project** to an existing standard mode structure that **converts it** to monorepo mode. Let's look at an example.\n\nIf we run:\n\n```bash\nnest new my-project\n```\n\nWe've constructed a _standard mode_ structure, with a folder structure that looks like this:\n\n<div class=\"file-tree\">\n  <div class=\"item\">node_modules</div>\n  <div class=\"item\">src</div>\n  <div class=\"children\">\n    <div class=\"item\">app.controller.ts</div>\n    <div class=\"item\">app.module.ts</div>\n    <div class=\"item\">app.service.ts</div>\n    <div class=\"item\">main.ts</div>\n  </div>\n  <div class=\"item\">nest-cli.json</div>\n  <div class=\"item\">package.json</div>\n  <div class=\"item\">tsconfig.json</div>\n  <div class=\"item\">.eslintrc.js</div>\n</div>\n\nWe can convert this to a monorepo mode structure as follows:\n\n```bash\ncd my-project\nnest generate app my-app\n```\n\nAt this point, `nest` converts the existing structure to a **monorepo mode** structure. This results in a few important changes. The folder structure now looks like this:\n\n<div class=\"file-tree\">\n  <div class=\"item\">apps</div>\n    <div class=\"children\">\n      <div class=\"item\">my-app</div>\n      <div class=\"children\">\n        <div class=\"item\">src</div>\n        <div class=\"children\">\n          <div class=\"item\">app.controller.ts</div>\n          <div class=\"item\">app.module.ts</div>\n          <div class=\"item\">app.service.ts</div>\n          <div class=\"item\">main.ts</div>\n        </div>\n        <div class=\"item\">tsconfig.app.json</div>\n      </div>\n      <div class=\"item\">my-project</div>\n      <div class=\"children\">\n        <div class=\"item\">src</div>\n        <div class=\"children\">\n          <div class=\"item\">app.controller.ts</div>\n          <div class=\"item\">app.module.ts</div>\n          <div class=\"item\">app.service.ts</div>\n          <div class=\"item\">main.ts</div>\n        </div>\n        <div class=\"item\">tsconfig.app.json</div>\n      </div>\n    </div>\n  <div class=\"item\">nest-cli.json</div>\n  <div class=\"item\">package.json</div>\n  <div class=\"item\">tsconfig.json</div>\n  <div class=\"item\">.eslintrc.js</div>\n</div>\n\nThe `generate app` schematic has reorganized the code - moving each **application** project under the `apps` folder, and adding a project-specific `tsconfig.app.json` file in each project's root folder. Our original `my-project` app has become the **default project** for the monorepo, and is now a peer with the just-added `my-app`, located under the `apps` folder. We'll cover default projects below.\n\n> error **Warning** The conversion of a standard mode structure to monorepo only works for projects that have followed the canonical Nest project structure. Specifically, during conversion, the schematic attempts to relocate the `src` and `test` folders in a project folder beneath the `apps` folder in the root. If a project does not use this structure, the conversion will fail or produce unreliable results.\n\n#### Workspace projects\n\nA monorepo uses the concept of a workspace to manage its member entities. Workspaces are composed of **projects**. A project may be either:\n\n- an **application**: a full Nest application including a `main.ts` file to bootstrap the application. Aside from compile and build considerations, an application-type project within a workspace is functionally identical to an application within a _standard mode_ structure.\n- a **library**: a library is a way of packaging a general purpose set of features (modules, providers, controllers, etc.) that can be used within other projects. A library cannot run on its own, and has no `main.ts` file. Read more about libraries [here](/cli/libraries).\n\nAll workspaces have a **default project** (which should be an application-type project). This is defined by the top-level `\"root\"` property in the `nest-cli.json` file, which points at the root of the default project (see [CLI properties](/cli/monorepo#cli-properties) below for more details). Usually, this is the **standard mode** application you started with, and later converted to a monorepo using `nest generate app`. When you follow these steps, this property is populated automatically.\n\nDefault projects are used by `nest` commands like `nest build` and `nest start` when a project name is not supplied.\n\nFor example, in the above monorepo structure, running\n\n```bash\n$ nest start\n```\n\nwill start up the `my-project` app. To start `my-app`, we'd use:\n\n```bash\n$ nest start my-app\n```\n\n#### Applications\n\nApplication-type projects, or what we might informally refer to as just \"applications\", are complete Nest applications that you can run and deploy. You generate an application-type project with `nest generate app`.\n\nThis command automatically generates a project skeleton, including the standard `src` and `test` folders from the [typescript starter](https://github.com/nestjs/typescript-starter). Unlike standard mode, an application project in a monorepo does not have any of the package dependency (`package.json`) or other project configuration artifacts like `.prettierrc` and `.eslintrc.js`. Instead, the monorepo-wide dependencies and config files are used.\n\nHowever, the schematic does generate a project-specific `tsconfig.app.json` file in the root folder of the project. This config file automatically sets appropriate build options, including setting the compilation output folder properly. The file extends the top-level (monorepo) `tsconfig.json` file, so you can manage global settings monorepo-wide, but override them if needed at the project level.\n\n#### Libraries\n\nAs mentioned, library-type projects, or simply \"libraries\", are packages of Nest components that need to be composed into applications in order to run. You generate a library-type project with `nest generate library`. Deciding what belongs in a library is an architectural design decision. We discuss libraries in depth in the [libraries](/cli/libraries) chapter.\n\n#### CLI properties\n\nNest keeps the metadata needed to organize, build and deploy both standard and monorepo structured projects in the `nest-cli.json` file. Nest automatically adds to and updates this file as you add projects, so you usually do not have to think about it or edit its contents. However, there are some settings you may want to change manually, so it's helpful to have an overview understanding of the file.\n\nAfter running the steps above to create a monorepo, our `nest-cli.json` file looks like this:\n\n```javascript\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"apps/my-project/src\",\n  \"monorepo\": true,\n  \"root\": \"apps/my-project\",\n  \"compilerOptions\": {\n    \"webpack\": true,\n    \"tsConfigPath\": \"apps/my-project/tsconfig.app.json\"\n  },\n  \"projects\": {\n    \"my-project\": {\n      \"type\": \"application\",\n      \"root\": \"apps/my-project\",\n      \"entryFile\": \"main\",\n      \"sourceRoot\": \"apps/my-project/src\",\n      \"compilerOptions\": {\n        \"tsConfigPath\": \"apps/my-project/tsconfig.app.json\"\n      }\n    },\n    \"my-app\": {\n      \"type\": \"application\",\n      \"root\": \"apps/my-app\",\n      \"entryFile\": \"main\",\n      \"sourceRoot\": \"apps/my-app/src\",\n      \"compilerOptions\": {\n        \"tsConfigPath\": \"apps/my-app/tsconfig.app.json\"\n      }\n    }\n  }\n}\n```\n\nThe file is divided into sections:\n\n- a global section with top-level properties controlling standard and monorepo-wide settings\n- a top level property (`\"projects\"`) with metadata about each project. This section is present only for monorepo-mode structures.\n\nThe top-level properties are as follows:\n\n- `\"collection\"`: points at the collection of schematics used to generate components; you generally should not change this value\n- `\"sourceRoot\"`: points at the root of the source code for the single project in standard mode structures, or the _default project_ in monorepo mode structures\n- `\"compilerOptions\"`: a map with keys specifying compiler options and values specifying the option setting; see details below\n- `\"generateOptions\"`: a map with keys specifying global generate options and values specifying the option setting; see details below\n- `\"monorepo\"`: (monorepo only) for a monorepo mode structure, this value is always `true`\n- `\"root\"`: (monorepo only) points at the project root of the _default project_\n\n#### Global compiler options\n\nThese properties specify the compiler to use as well as various options that affect **any** compilation step, whether as part of `nest build` or `nest start`, and regardless of the compiler, whether `tsc` or webpack.\n\n| Property Name       | Property Value Type | Description                                                                                                                                                                                                                           |\n| ------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `webpack`           | boolean             | If `true`, use [webpack compiler](https://webpack.js.org/). If `false` or not present, use `tsc`. In monorepo mode, the default is `true` (use webpack), in standard mode, the default is `false` (use `tsc`). See below for details. |\n| `tsConfigPath`      | string              | (**monorepo only**) Points at the file containing the `tsconfig.json` settings that will be used when `nest build` or `nest start` is called without a `project` option (e.g., when the default project is built or started).         |\n| `webpackConfigPath` | string              | Points at a webpack options file. If not specified, Nest looks for the file `webpack.config.js`. See below for more details.                                                                                                          |\n| `deleteOutDir`      | boolean             | If `true`, whenever the compiler is invoked, it will first remove the compilation output directory (as configured in `tsconfig.json`, where the default is `./dist`).                                                                 |\n| `assets`            | array               | Enables automatically distributing non-TypeScript assets whenever a compilation step begins (asset distribution does **not** happen on incremental compiles in `--watch` mode). See below for details.                                |\n| `watchAssets`       | boolean             | If `true`, run in watch-mode, watching **all** non-TypeScript assets. (For more fine-grained control of the assets to watch, see [Assets](cli/monorepo#assets) section below).                                                        |\n\n#### Global generate options\n\nThese properties specify the default generate options to be used by the `nest generate` command.\n\n| Property Name | Property Value Type | Description                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n| ------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `spec`        | boolean _or_ object | If the value is boolean, a value of `true` enables `spec` generation by default and a value of `false` disables it. A flag passed on the CLI command line overrides this setting, as does a project-specific `generateOptions` setting (more below). If the value is an object, each key represents a schematic name, and the boolean value determines whether the default spec generation is enabled / disabled for that specific schematic. |\n\nThe following example uses a boolean value to specify that spec file generation should be disabled by default for all projects:\n\n```javascript\n{\n  \"generateOptions\": {\n    \"spec\": false\n  },\n  ...\n}\n```\n\nIn the following example, `spec` file generation is disabled only for `service` schematics (e.g., `nest generate service...`):\n\n```javascript\n{\n  \"generateOptions\": {\n    \"spec\": {\n      \"service\": false\n    }\n  },\n  ...\n}\n```\n\n> warning **Warning** When specifying the `spec` as an object, the key for the generation schematic does not currently support automatic alias handling. This means that specifying a key as for example `service: false` and trying to generate a service via the alias `s`, the spec would still be generated. To make sure both the normal schematic name and the alias work as intended, specify both the normal command name as well as the alias, as seen below.\n>\n> ```javascript\n> {\n>   \"generateOptions\": {\n>     \"spec\": {\n>       \"service\": false,\n>       \"s\": false\n>     }\n>   },\n>   ...\n> }\n> ```\n\n#### Project-specific generate options\n\nIn addition to providing global generate options, you may also specify project-specific generate options. The project specific generate options follow the exact same format as the global generate options, but are specified directly on each project.\n\nProject-specific generate options override global generate options.\n\n```javascript\n{\n  \"projects\": {\n    \"cats-project\": {\n      \"generateOptions\": {\n        \"spec\": {\n          \"service\": false\n        }\n      },\n      ...\n    }\n  },\n  ...\n}\n```\n\n> warning **Warning** The order of precedence for generate options is as follows. Options specified on the CLI command line take precedence over project-specific options. Project-specific options override global options.\n\n#### Specified compiler\n\nThe reason for the different default compilers is that for larger projects (e.g., more typical in a monorepo) webpack can have significant advantages in build times and in producing a single file bundling all project components together. If you wish to generate individual files, set `\"webpack\"` to `false`, which will cause the build process to use `tsc`.\n\n#### Webpack options\n\nThe webpack options file can contain standard [webpack configuration options](https://webpack.js.org/configuration/). For example, to tell webpack to bundle `node_modules` (which are excluded by default), add the following to `webpack.config.js`:\n\n```javascript\nmodule.exports = {\n  externals: [],\n};\n```\n\nSince the webpack config file is a JavaScript file, you can even expose a function that takes default options and returns a modified object:\n\n```javascript\nmodule.exports = function(options) {\n  return {\n    ...options,\n    externals: [],\n  };\n};\n```\n\n#### Assets\n\nTypeScript compilation automatically distributes compiler output (`.js` and `.d.ts` files) to the specified output directory. It can also be convenient to distribute non-TypeScript files, such as `.graphql` files, `images`, `.html` files and other assets. This allows you to treat `nest build` (and any initial compilation step) as a lightweight **development build** step, where you may be editing non-TypeScript files and iteratively compiling and testing.\nThe assets should be located in the `src` folder otherwise they will not be copied.\n\nThe value of the `assets` key should be an array of elements specifying the files to be distributed. The elements can be simple strings with `glob`-like file specs, for example:\n\n```typescript\n\"assets\": [\"**/*.graphql\"],\n\"watchAssets\": true,\n```\n\nFor finer control, the elements can be objects with the following keys:\n\n- `\"include\"`: `glob`-like file specifications for the assets to be distributed\n- `\"exclude\"`: `glob`-like file specifications for assets to be **excluded** from the `include` list\n- `\"outDir\"`: a string specifying the path (relative to the root folder) where the assets should be distributed. Defaults to the same output directory configured for compiler output.\n- `\"watchAssets\"`: boolean; if `true`, run in watch mode watching specified assets\n\nFor example:\n\n```typescript\n\"assets\": [\n  { \"include\": \"**/*.graphql\", \"exclude\": \"**/omitted.graphql\", \"watchAssets\": true },\n]\n```\n\n> warning **Warning** Setting `watchAssets` in a top-level `compilerOptions` property overrides any `watchAssets` settings within the `assets` property.\n\n#### Project properties\n\nThis element exists only for monorepo-mode structures. You generally should not edit these properties, as they are used by Nest to locate projects and their configuration options within the monorepo.\n"
  },
  {
    "path": "content/components.md",
    "content": "### Providers\n\n프로바이더는 Nest의 기본 개념입니다. 기본 Nest 클래스의 대부분은 서비스, 리포지토리, 팩토리, 헬퍼 등 프로바이더로 취급될 수 있습니다. 프로바이더의 주요 아이디어는 종속성으로 **주입**할 수 있다는 것입니다. 즉, 객체는 서로 다양한 관계를 생성할 수 있으며 객체의 인스턴스를 \"연결\"하는 기능은 대부분 Nest 런타임 시스템에 위임될 수 있습니다.\n\n<figure><img src=\"/assets/Components_1.png\" /></figure>\n\n이전 장에서 우리는 간단한 `CatsController`를 만들었습니다. 컨트롤러는 HTTP 요청을 처리하고 더 복잡한 작업을 **프로바이더**에 위임해야 합니다. 공급자는 [모듈](/modules)에서 `프로바이더'로 선언된 일반 자바스크립트 클래스입니다.\n\n> 정보 **힌트** Nest를 사용하면 종속성을 보다 OO-방식으로 설계하고 구성할 수 있으므로 [SOLID](https://en.wikipedia.org/wiki/SOLID) 원칙을 따르는 것이 좋습니다.\n\n#### Services\n\n간단한 'CatsService'를 만드는 것으로 시작하겠습니다. 이 서비스는 데이터 저장 및 검색을 담당하며 `CatsController`에서 사용하도록 설계되었으므로 프로바이더로 정의하기에 좋은 후보입니다.\n\n```typescript\n@@filename(cats.service)\nimport { Injectable } from '@nestjs/common';\nimport { Cat } from './interfaces/cat.interface';\n\n@Injectable()\nexport class CatsService {\n  private readonly cats: Cat[] = [];\n\n  create(cat: Cat) {\n    this.cats.push(cat);\n  }\n\n  findAll(): Cat[] {\n    return this.cats;\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class CatsService {\n  constructor() {\n    this.cats = [];\n  }\n\n  create(cat) {\n    this.cats.push(cat);\n  }\n\n  findAll() {\n    return this.cats;\n  }\n}\n```\n\n> 정보 **힌트** CLI를 사용하여 서비스를 생성하려면 `$ nest g service cats` 명령을 실행하면 됩니다.\n\n우리의 `CatsService`는 하나의 속성과 두 개의 메소드가 있는 기본 클래스입니다. 유일한 새로운 기능은 `@Injectable()` 데코레이터를 사용한다는 것입니다. `@Injectable()` 데코레이터는 `CatsService`가 Nest IoC 컨테이너에서 관리할 수 있는 클래스임을 선언하는 메타데이터를 첨부합니다. 그런데 이 예제는 'Cat' 인터페이스도 사용됩니다:\n\n```typescript\n@@filename(interfaces/cat.interface)\nexport interface Cat {\n  name: string;\n  age: number;\n  breed: string;\n}\n```\n\n이제 고양이를 검색하는 서비스 클래스가 있으므로 `CatsController` 내부에서 사용하겠습니다.\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get, Post, Body } from '@nestjs/common';\nimport { CreateCatDto } from './dto/create-cat.dto';\nimport { CatsService } from './cats.service';\nimport { Cat } from './interfaces/cat.interface';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(private catsService: CatsService) {}\n\n  @Post()\n  async create(@Body() createCatDto: CreateCatDto) {\n    this.catsService.create(createCatDto);\n  }\n\n  @Get()\n  async findAll(): Promise<Cat[]> {\n    return this.catsService.findAll();\n  }\n}\n@@switch\nimport { Controller, Get, Post, Body, Bind, Dependencies } from '@nestjs/common';\nimport { CatsService } from './cats.service';\n\n@Controller('cats')\n@Dependencies(CatsService)\nexport class CatsController {\n  constructor(catsService) {\n    this.catsService = catsService;\n  }\n\n  @Post()\n  @Bind(Body())\n  async create(createCatDto) {\n    this.catsService.create(createCatDto);\n  }\n\n  @Get()\n  async findAll() {\n    return this.catsService.findAll();\n  }\n}\n```\n\n`CatsService`는 클래스 생성자를 통해 **주입**됩니다. `private` 클래스 필드를 사용하는 것에 주목해야합니다. 이 약식을 사용하면 같은 위치에서 즉시 `catsService` 멤버를 선언하고 초기화할 수 있습니다.\n\n#### Dependency injection\n\nNest is built around the strong design pattern commonly known as **Dependency injection**. We recommend reading a great article about this concept in the official [Angular](https://angular.io/guide/dependency-injection) documentation.\n\nIn Nest, thanks to TypeScript capabilities, it's extremely easy to manage dependencies because they are resolved just by type. In the example below, Nest will resolve the `catsService` by creating and returning an instance of `CatsService` (or, in the normal case of a singleton, returning the existing instance if it has already been requested elsewhere). This dependency is resolved and passed to your controller's constructor (or assigned to the indicated property):\n\n```typescript\nconstructor(private catsService: CatsService) {}\n```\n\n#### Scopes\n\nProviders 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](/fundamentals/injection-scopes).\n\n<app-banner-courses></app-banner-courses>\n\n#### Custom providers\n\nNest has a built-in inversion of control (\"IoC\") container that resolves relationships between providers. This feature underlies the dependency injection feature described above, but is in fact far more powerful than what we've described so far.  There are several ways to define a provider: you can use plain values, classes, and either asynchronous or synchronous factories. More examples are provided [here](/fundamentals/dependency-injection).\n\n#### Optional providers\n\nOccasionally, you might have dependencies which do not necessarily have to be resolved. For instance, your class may depend on a **configuration object**, but if none is passed, the default values should be used. In such a case, the dependency becomes optional, because lack of the configuration provider wouldn't lead to errors.\n\nTo indicate a provider is optional, use the `@Optional()` decorator in the constructor's signature.\n\n```typescript\nimport { Injectable, Optional, Inject } from '@nestjs/common';\n\n@Injectable()\nexport class HttpService<T> {\n  constructor(@Optional() @Inject('HTTP_OPTIONS') private httpClient: T) {}\n}\n```\n\nNote that in the example above we are using a custom provider, which is the reason we include the `HTTP_OPTIONS` custom **token**. Previous examples showed constructor-based injection indicating a dependency through a class in the constructor. Read more about custom providers and their associated tokens [here](/fundamentals/custom-providers).\n\n#### Property-based injection\n\nThe technique we've used so far is called constructor-based injection, as providers are injected via the constructor method. In some very specific cases, **property-based injection** might be useful. For instance, if your top-level class depends on either one or multiple providers, passing them all the way up by calling `super()` in sub-classes from the constructor can be very tedious. In order to avoid this, you can use the `@Inject()` decorator at the property level.\n\n```typescript\nimport { Injectable, Inject } from '@nestjs/common';\n\n@Injectable()\nexport class HttpService<T> {\n  @Inject('HTTP_OPTIONS')\n  private readonly httpClient: T;\n}\n```\n\n> warning **Warning** If your class doesn't extend another provider, you should always prefer using **constructor-based** injection.\n\n#### Provider registration\n\nNow that we have defined a provider (`CatsService`), and we have a consumer of that service (`CatsController`), 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.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats/cats.controller';\nimport { CatsService } from './cats/cats.service';\n\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n})\nexport class AppModule {}\n```\n\nNest will now be able to resolve the dependencies of the `CatsController` class.\n\nThis is how our directory structure should look now:\n\n<div class=\"file-tree\">\n<div class=\"item\">src</div>\n<div class=\"children\">\n<div class=\"item\">cats</div>\n<div class=\"children\">\n<div class=\"item\">dto</div>\n<div class=\"children\">\n<div class=\"item\">create-cat.dto.ts</div>\n</div>\n<div class=\"item\">interfaces</div>\n<div class=\"children\">\n<div class=\"item\">cat.interface.ts</div>\n</div>\n<div class=\"item\">cats.controller.ts</div>\n<div class=\"item\">cats.service.ts</div>\n</div>\n<div class=\"item\">app.module.ts</div>\n<div class=\"item\">main.ts</div>\n</div>\n</div>\n\n#### Manual instantiation\n\nThus far, we've discussed how Nest automatically handles most of the details of resolving dependencies.  In certain circumstances, you may need to step outside of the built-in Dependency Injection system and manually retrieve or instantiate providers. We briefly discuss two such topics below.\n\n To get existing instances, or instantiate providers dynamically, you can use [Module reference](https://docs.nestjs.com/fundamentals/module-ref).\n \n To get providers within the `bootstrap()` function (for example for standalone applications without controllers, or to utilize a configuration service during bootstrapping) see [Standalone applications](https://docs.nestjs.com/standalone-applications).\n"
  },
  {
    "path": "content/controllers.md",
    "content": "### Controllers\n\n컨트롤러는 들어오는 **요청**을 적절히 핸들링하고 **응답**을 클라이언트로 리턴해주는 책임을 지니고 있습니다.\n\n<figure><img src=\"/assets/Controllers_1.png\" /></figure>\n\n컨트롤러의 목적은 application을 위한 요청을 받아오는 데 있습니다. **routing** 메커니즘은 어떤 컨트롤러가 어떤 요청을 받아오는지를 제어합니다.\n많은 경우, 각각의 컨트롤러는 하나 이상의 라우트를 가지고, 각각의 라우트는 고유한 목적을 가지고 동작합니다.\n\n기본적 형태의 컨트롤러를 만들기 위해, 클래스와 데코레이터를 사용합니다. 데코레이터는 클래스와 클래스가 필요한 메타데이터를 연결시키고, 네스트가 라우팅 맵을 만들 수 있도록 합니다(요청과 적절한 컨트롤러를 연결시켜줍니다).\n\n> info **힌트** [밸리데이션](https://docs.nestjs.kr/techniques/validation)이 포함된 CRUD 컨트롤러를 간편하게 만들기 위해 CLI의 [CRUD generator](https://docs.nestjs.kr/recipes/crud-generator#crud-generator): `nest g resource [이름]`을 사용할 수 있습니다.\n\n#### 라우팅\n\n다음의 예제에서 기본적인 컨트롤러를 정의하기 위해 필요한 `@Controller()` 데코레이터를 사용해봅니다. 우리는 앞으로 `cats`라는 이름의 접두사를 가진 라우트를 만들 것입니다. `@Controller()` 데코레이터에서 접두사를 이용하는 것은 연관된 라우트들을 그룹화하기 쉽게 만들어주고 코드의 중복을 최소화할 수 있습니다. 예를 들어, `/customers`라는 이름의 접두사 하에서 고객 엔티티와 상호작용하는 라우트 그룹을 다룰 것이라 생각할 수 있습니다. 이런 경우, 한 파일 안에서 각각의 라우트마다 반복하여 접두사를 기입할 필요가 없도록 `@Controller()` 데코레이터에 `customers`를 명시해놓을 수 있습니다.\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Get()\n  findAll(): string {\n    return 'This action returns all cats';\n  }\n}\n@@switch\nimport { Controller, Get } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Get()\n  findAll() {\n    return 'This action returns all cats';\n  }\n}\n```\n\n> info **힌트** CLI를 이용해 컨트롤러를 만들기 위해서는 `$ nest g controller cats` 명령어를 입력하세요.\n\nThe `@Get()` HTTP request method decorator before the `findAll()` method tells Nest to create a handler for a specific endpoint for HTTP requests. The endpoint corresponds to the HTTP request method (GET in this case) and the route path. What is the route path? The route path for a handler is determined by concatenating the (optional) prefix declared for the controller, and any path specified in the method's decorator. Since we've declared a prefix for every route ( `cats`), and haven't added any path information in the decorator, Nest will map `GET /cats` requests to this handler. As mentioned, the path includes both the optional controller path prefix **and** any path string declared in the request method decorator. For example, a path prefix of `customers` combined with the decorator `@Get('profile')` would produce a route mapping for requests like `GET /customers/profile`.\n\nIn our example above, when a GET request is made to this endpoint, Nest routes the request to our user-defined `findAll()` method. Note that the method name we choose here is completely arbitrary. We obviously must declare a method to bind the route to, but Nest doesn't attach any significance to the method name chosen.\n\nThis method will return a 200 status code and the associated response, which in this case is just a string. Why does that happen? To explain, we'll first introduce the concept that Nest employs two **different** options for manipulating responses:\n\n<table>\n  <tr>\n    <td>Standard (recommended)</td>\n    <td>\n      Using this built-in method, when a request handler returns a JavaScript object or array, it will <strong>automatically</strong>\n      be serialized to JSON. When it returns a JavaScript primitive type (e.g., <code>string</code>, <code>number</code>, <code>boolean</code>), however, Nest will send just the value without attempting to serialize it. This makes response handling simple: just return the value, and Nest takes care of the rest.\n      <br />\n      <br /> Furthermore, the response's <strong>status code</strong> is always 200 by default, except for POST\n      requests which use 201. We can easily change this behavior by adding the <code>@HttpCode(...)</code>\n      decorator at a handler-level (see <a href='controllers#status-code'>Status codes</a>).\n    </td>\n  </tr>\n  <tr>\n    <td>Library-specific</td>\n    <td>\n      We can use the library-specific (e.g., Express) <a href=\"https://expressjs.com/en/api.html#res\" rel=\"nofollow\" target=\"_blank\">response object</a>, which can be injected using the <code>@Res()</code> decorator in the method handler signature (e.g., <code>findAll(@Res() response)</code>).  With this approach, you have the ability to use the native response handling methods exposed by that object.  For example, with Express, you can construct responses using code like <code>response.status(200).send()</code>.\n    </td>\n  </tr>\n</table>\n\n> warning **Warning** Nest detects when the handler is using either `@Res()` or `@Next()`, indicating you have chosen the library-specific option. If both approaches are used at the same time, the Standard approach is **automatically disabled** for this single route and will no longer work as expected. To use both approaches at the same time (for example, by injecting the response object to only set cookies/headers but still leave the rest to the framework), you must set the `passthrough` option to `true` in the `@Res({{ '{' }} passthrough: true {{ '}' }})` decorator.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Request object\n\nHandlers often need access to the client **request** details. Nest provides access to the [request object](https://expressjs.com/en/api.html#req) of the underlying platform (Express by default). We can access the request object by instructing Nest to inject it by adding the `@Req()` decorator to the handler's signature.\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get, Req } from '@nestjs/common';\nimport { Request } from 'express';\n\n@Controller('cats')\nexport class CatsController {\n  @Get()\n  findAll(@Req() request: Request): string {\n    return 'This action returns all cats';\n  }\n}\n@@switch\nimport { Controller, Bind, Get, Req } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Get()\n  @Bind(Req())\n  findAll(request) {\n    return 'This action returns all cats';\n  }\n}\n```\n\n> info **Hint** In order to take advantage of `express` typings (as in the `request: Request` parameter example above), install `@types/express` package.\n\nThe request object represents the HTTP request and has properties for the request query string, parameters, HTTP headers, and body (read more [here](https://expressjs.com/en/api.html#req)). In most cases, it's not necessary to grab these properties manually. We can use dedicated decorators instead, such as `@Body()` or `@Query()`, which are available out of the box. Below is a list of the provided decorators and the plain platform-specific objects they represent.\n\n<table>\n  <tbody>\n    <tr>\n      <td><code>@Request(), @Req()</code></td>\n      <td><code>req</code></td></tr>\n    <tr>\n      <td><code>@Response(), @Res()</code><span class=\"table-code-asterisk\">*</span></td>\n      <td><code>res</code></td>\n    </tr>\n    <tr>\n      <td><code>@Next()</code></td>\n      <td><code>next</code></td>\n    </tr>\n    <tr>\n      <td><code>@Session()</code></td>\n      <td><code>req.session</code></td>\n    </tr>\n    <tr>\n      <td><code>@Param(key?: string)</code></td>\n      <td><code>req.params</code> / <code>req.params[key]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Body(key?: string)</code></td>\n      <td><code>req.body</code> / <code>req.body[key]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Query(key?: string)</code></td>\n      <td><code>req.query</code> / <code>req.query[key]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Headers(name?: string)</code></td>\n      <td><code>req.headers</code> / <code>req.headers[name]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Ip()</code></td>\n      <td><code>req.ip</code></td>\n    </tr>\n    <tr>\n      <td><code>@HostParam()</code></td>\n      <td><code>req.hosts</code></td>\n    </tr>\n  </tbody>\n</table>\n\n<sup>\\* </sup>For compatibility with typings across underlying HTTP platforms (e.g., Express and Fastify), Nest provides `@Res()` and `@Response()` decorators. `@Res()` is simply an alias for `@Response()`. Both directly expose the underlying native platform `response` object interface. When using them, you should also import the typings for the underlying library (e.g., `@types/express`) to take full advantage. Note that when you inject either `@Res()` or `@Response()` in a method handler, you put Nest into **Library-specific mode** for that handler, and you become responsible for managing the response. When doing so, you must issue some kind of response by making a call on the `response` object (e.g., `res.json(...)` or `res.send(...)`), or the HTTP server will hang.\n\n> info **Hint** To learn how to create your own custom decorators, visit [this](/custom-decorators) chapter.\n\n#### Resources\n\nEarlier, we defined an endpoint to fetch the cats resource (**GET** route). We'll typically also want to provide an endpoint that creates new records. For this, let's create the **POST** handler:\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get, Post } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  create(): string {\n    return 'This action adds a new cat';\n  }\n\n  @Get()\n  findAll(): string {\n    return 'This action returns all cats';\n  }\n}\n@@switch\nimport { Controller, Get, Post } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  create() {\n    return 'This action adds a new cat';\n  }\n\n  @Get()\n  findAll() {\n    return 'This action returns all cats';\n  }\n}\n```\n\nIt's that simple. Nest provides decorators for all of the standard HTTP methods: `@Get()`, `@Post()`, `@Put()`, `@Delete()`, `@Patch()`, `@Options()`, and `@Head()`. In addition, `@All()` defines an endpoint that handles all of them.\n\n#### Route wildcards\n\nPattern based routes are supported as well. For instance, the asterisk is used as a wildcard, and will match any combination of characters.\n\n```typescript\n@Get('ab*cd')\nfindAll() {\n  return 'This route uses a wildcard';\n}\n```\n\nThe `'ab*cd'` route path will match `abcd`, `ab_cd`, `abecd`, and so on. The characters `?`, `+`, `*`, and `()` may be used in a route path, and are subsets of their regular expression counterparts. The hyphen ( `-`) and the dot (`.`) are interpreted literally by string-based paths.\n\n#### Status code\n\nAs mentioned, the response **status code** is always **200** by default, except for POST requests which are **201**. We can easily change this behavior by adding the `@HttpCode(...)` decorator at a handler level.\n\n```typescript\n@Post()\n@HttpCode(204)\ncreate() {\n  return 'This action adds a new cat';\n}\n```\n\n> info **Hint** Import `HttpCode` from the `@nestjs/common` package.\n\nOften, your status code isn't static but depends on various factors. In that case, you can use a library-specific **response** (inject using `@Res()`) object (or, in case of an error, throw an exception).\n\n#### Headers\n\nTo specify a custom response header, you can either use a `@Header()` decorator or a library-specific response object (and call `res.header()` directly).\n\n```typescript\n@Post()\n@Header('Cache-Control', 'none')\ncreate() {\n  return 'This action adds a new cat';\n}\n```\n\n> info **Hint** Import `Header` from the `@nestjs/common` package.\n\n#### Redirection\n\nTo redirect a response to a specific URL, you can either use a `@Redirect()` decorator or a library-specific response object (and call `res.redirect()` directly).\n\n`@Redirect()` takes two arguments, `url` and `statusCode`, both are optional. The default value of `statusCode` is `302` (`Found`) if omitted.\n\n```typescript\n@Get()\n@Redirect('https://nestjs.com', 301)\n```\n\nSometimes you may want to determine the HTTP status code or the redirect URL dynamically. Do this by returning an object from the route handler method with the shape:\n\n```json\n{\n  \"url\": string,\n  \"statusCode\": number\n}\n```\n\nReturned values will override any arguments passed to the `@Redirect()` decorator. For example:\n\n```typescript\n@Get('docs')\n@Redirect('https://docs.nestjs.com', 302)\ngetDocs(@Query('version') version) {\n  if (version && version === '5') {\n    return { url: 'https://docs.nestjs.com/v5/' };\n  }\n}\n```\n\n#### Route parameters\n\nRoutes with static paths won't work when you need to accept **dynamic data** as part of the request (e.g., `GET /cats/1` to get cat with id `1`). In order to define routes with parameters, we can add route parameter **tokens** in the path of the route to capture the dynamic value at that position in the request URL. The route parameter token in the `@Get()` decorator example below demonstrates this usage. Route parameters declared in this way can be accessed using the `@Param()` decorator, which should be added to the method signature.\n\n```typescript\n@@filename()\n@Get(':id')\nfindOne(@Param() params): string {\n  console.log(params.id);\n  return `This action returns a #${params.id} cat`;\n}\n@@switch\n@Get(':id')\n@Bind(Param())\nfindOne(params) {\n  console.log(params.id);\n  return `This action returns a #${params.id} cat`;\n}\n```\n\n`@Param()` is used to decorate a method parameter (`params` in the example above), and makes the **route** parameters available as properties of that decorated method parameter inside the body of the method. As seen in the code above, we can access the `id` parameter by referencing `params.id`. You can also pass in a particular parameter token to the decorator, and then reference the route parameter directly by name in the method body.\n\n> info **Hint** Import `Param` from the `@nestjs/common` package.\n\n```typescript\n@@filename()\n@Get(':id')\nfindOne(@Param('id') id: string): string {\n  return `This action returns a #${id} cat`;\n}\n@@switch\n@Get(':id')\n@Bind(Param('id'))\nfindOne(id) {\n  return `This action returns a #${id} cat`;\n}\n```\n\n#### Sub-Domain Routing\n\nThe `@Controller` decorator can take a `host` option to require that the HTTP host of the incoming requests matches some specific value.\n\n```typescript\n@Controller({ host: 'admin.example.com' })\nexport class AdminController {\n  @Get()\n  index(): string {\n    return 'Admin page';\n  }\n}\n```\n\n> **Warning** Since **Fastify** lacks support for nested routers, when using sub-domain routing, the (default) Express adapter should be used instead.\n\nSimilar to a route `path`, the `hosts` option can use tokens to capture the dynamic value at that position in the host name. The host parameter token in the `@Controller()` decorator example below demonstrates this usage. Host parameters declared in this way can be accessed using the `@HostParam()` decorator, which should be added to the method signature.\n\n```typescript\n@Controller({ host: ':account.example.com' })\nexport class AccountController {\n  @Get()\n  getInfo(@HostParam('account') account: string) {\n    return account;\n  }\n}\n```\n\n#### Scopes\n\nFor people coming from different programming language backgrounds, it might be unexpected to learn that in Nest, almost everything is shared across incoming requests. We have a connection pool to the database, singleton services with global state, etc. Remember that Node.js doesn't follow the request/response Multi-Threaded Stateless Model in which every request is processed by a separate thread. Hence, using singleton instances is fully **safe** for our applications.\n\nHowever, there are edge-cases when request-based lifetime of the controller may be the desired behavior, for instance per-request caching in GraphQL applications, request tracking or multi-tenancy. Learn how to control scopes [here](/fundamentals/injection-scopes).\n\n#### Asynchronicity\n\nWe love modern JavaScript and we know that data extraction is mostly **asynchronous**. That's why Nest supports and works well with `async` functions.\n\n> info **Hint** Learn more about `async / await` feature [here](https://kamilmysliwiec.com/typescript-2-1-introduction-async-await)\n\nEvery async function has to return a `Promise`. This means that you can return a deferred value that Nest will be able to resolve by itself. Let's see an example of this:\n\n```typescript\n@@filename(cats.controller)\n@Get()\nasync findAll(): Promise<any[]> {\n  return [];\n}\n@@switch\n@Get()\nasync findAll() {\n  return [];\n}\n```\n\nThe above code is fully valid. Furthermore, Nest route handlers are even more powerful by being able to return RxJS [observable streams](http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html). Nest will automatically subscribe to the source underneath and take the last emitted value (once the stream is completed).\n\n```typescript\n@@filename(cats.controller)\n@Get()\nfindAll(): Observable<any[]> {\n  return of([]);\n}\n@@switch\n@Get()\nfindAll() {\n  return of([]);\n}\n```\n\nBoth of the above approaches work and you can use whatever fits your requirements.\n\n#### Request payloads\n\nOur previous example of the POST route handler didn't accept any client params. Let's fix this by adding the `@Body()` decorator here.\n\nBut first (if you use TypeScript), we need to determine the **DTO** (Data Transfer Object) schema. A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using **TypeScript** interfaces, or by simple classes. Interestingly, we recommend using **classes** here. Why? Classes are part of the JavaScript ES6 standard, and therefore they are preserved as real entities in the compiled JavaScript. On the other hand, since TypeScript interfaces are removed during the transpilation, Nest can't refer to them at runtime. This is important because features such as **Pipes** enable additional possibilities when they have access to the metatype of the variable at runtime.\n\nLet's create the `CreateCatDto` class:\n\n```typescript\n@@filename(create-cat.dto)\nexport class CreateCatDto {\n  name: string;\n  age: number;\n  breed: string;\n}\n```\n\nIt has only three basic properties. Thereafter we can use the newly created DTO inside the `CatsController`:\n\n```typescript\n@@filename(cats.controller)\n@Post()\nasync create(@Body() createCatDto: CreateCatDto) {\n  return 'This action adds a new cat';\n}\n@@switch\n@Post()\n@Bind(Body())\nasync create(createCatDto) {\n  return 'This action adds a new cat';\n}\n```\n\n> info **Hint** Our `ValidationPipe` can filter out properties that should not be received by the method handler. In this case, we can whitelist the acceptable properties, and any property not included in the whitelist is automatically stripped from the resulting object. In the `CreateCatDto` example, our whitelist is the `name`, `age`, and `breed` properties. Learn more [here](https://docs.nestjs.com/techniques/validation#stripping-properties).\n\n#### Handling errors\n\nThere's a separate chapter about handling errors (i.e., working with exceptions) [here](/exception-filters).\n\n#### Full resource sample\n\nBelow is an example that makes use of several of the available decorators to create a basic controller. This controller exposes a couple of methods to access and manipulate internal data.\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';\nimport { CreateCatDto, UpdateCatDto, ListAllEntities } from './dto';\n\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  create(@Body() createCatDto: CreateCatDto) {\n    return 'This action adds a new cat';\n  }\n\n  @Get()\n  findAll(@Query() query: ListAllEntities) {\n    return `This action returns all cats (limit: ${query.limit} items)`;\n  }\n\n  @Get(':id')\n  findOne(@Param('id') id: string) {\n    return `This action returns a #${id} cat`;\n  }\n\n  @Put(':id')\n  update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto) {\n    return `This action updates a #${id} cat`;\n  }\n\n  @Delete(':id')\n  remove(@Param('id') id: string) {\n    return `This action removes a #${id} cat`;\n  }\n}\n@@switch\nimport { Controller, Get, Query, Post, Body, Put, Param, Delete, Bind } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  @Bind(Body())\n  create(createCatDto) {\n    return 'This action adds a new cat';\n  }\n\n  @Get()\n  @Bind(Query())\n  findAll(query) {\n    console.log(query);\n    return `This action returns all cats (limit: ${query.limit} items)`;\n  }\n\n  @Get(':id')\n  @Bind(Param('id'))\n  findOne(id) {\n    return `This action returns a #${id} cat`;\n  }\n\n  @Put(':id')\n  @Bind(Param('id'), Body())\n  update(id, updateCatDto) {\n    return `This action updates a #${id} cat`;\n  }\n\n  @Delete(':id')\n  @Bind(Param('id'))\n  remove(id) {\n    return `This action removes a #${id} cat`;\n  }\n}\n```\n\n> info **Hint** Nest CLI provides a generator (schematic) that automatically generates **all the boilerplate code** to help us avoid doing all of this, and make the developer experience much simpler. Read more about this feature [here](/recipes/crud-generator).\n\n#### Getting up and running\n\nWith the above controller fully defined, Nest still doesn't know that `CatsController` exists and as a result won't create an instance of this class.\n\nControllers always belong to a module, which is why we include the `controllers` array within the `@Module()` decorator. Since we haven't yet defined any other modules except the root `AppModule`, we'll use that to introduce the `CatsController`:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats/cats.controller';\n\n@Module({\n  controllers: [CatsController],\n})\nexport class AppModule {}\n```\n\nWe attached the metadata to the module class using the `@Module()` decorator, and Nest can now easily reflect which controllers have to be mounted.\n\n<app-banner-shop></app-banner-shop>\n\n#### Library-specific approach\n\nSo far we've discussed the Nest standard way of manipulating responses. The second way of manipulating the response is to use a library-specific [response object](https://expressjs.com/en/api.html#res). In order to inject a particular response object, we need to use the `@Res()` decorator. To show the differences, let's rewrite the `CatsController` to the following:\n\n```typescript\n@@filename()\nimport { Controller, Get, Post, Res, HttpStatus } from '@nestjs/common';\nimport { Response } from 'express';\n\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  create(@Res() res: Response) {\n    res.status(HttpStatus.CREATED).send();\n  }\n\n  @Get()\n  findAll(@Res() res: Response) {\n     res.status(HttpStatus.OK).json([]);\n  }\n}\n@@switch\nimport { Controller, Get, Post, Bind, Res, Body, HttpStatus } from '@nestjs/common';\n\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  @Bind(Res(), Body())\n  create(res, createCatDto) {\n    res.status(HttpStatus.CREATED).send();\n  }\n\n  @Get()\n  @Bind(Res())\n  findAll(res) {\n     res.status(HttpStatus.OK).json([]);\n  }\n}\n```\n\nThough this approach works, and does in fact allow for more flexibility in some ways by providing full control of the response object (headers manipulation, library-specific features, and so on), it should be used with care. In general, the approach is much less clear and does have some disadvantages. The main disadvantage is that your code becomes platform-dependent (as underlying libraries may have different APIs on the response object), and harder to test (you'll have to mock the response object, etc.).\n\nAlso, in the example above, you lose compatibility with Nest features that depend on Nest standard response handling, such as Interceptors and `@HttpCode()` / `@Header()` decorators. To fix this, you can set the `passthrough` option to `true`, as follows:\n\n```typescript\n@@filename()\n@Get()\nfindAll(@Res({ passthrough: true }) res: Response) {\n  res.status(HttpStatus.OK);\n  return [];\n}\n@@switch\n@Get()\n@Bind(Res({ passthrough: true }))\nfindAll(res) {\n  res.status(HttpStatus.OK);\n  return [];\n}\n```\n\nNow you can interact with the native response object (for example, set cookies or headers depending on certain conditions), but leave the rest to the framework.\n"
  },
  {
    "path": "content/custom-decorators.md",
    "content": "### 사용자 정의 라우트 데코레이터\n\nNest는 **데코레이터**라는 언어 기능을 활용하여 구축됩니다. 데코레이터는 많은 프로그래밍 언어들에서는 잘 알려진 개념이지만, 자바스크립트 세계에서는 아직까지는 상대적으로 신기능입니다. 데코레이터가 어떻게 동작하는지 더 잘 이해하고 싶다면, [이 자료](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841)를 읽어보기를 추천합니다. 데코레이터에 대해 간단하게 정의하자면 이렇습니다.\n\n<blockquote class=\"external\">\n  ES2016 데코레이터는 특정 대상이나 이름, 프로퍼티 설명자를 인자로 받으며 함수를 반환하는 표현식입니다. 데코레이터를 적용할 때는 <code>@</code>문자를 데코레이터의 접두사로 붙이고, 적용할 대상의 바로 위에 위치시킵니다. 데코레이터는 클래스나 메서드, 프로퍼티를 적용 대상으로 삼을 수 있습니다.\n</blockquote>\n\n#### 매개변수 데코레이터\n\nNest는 HTTP 라우트 핸들러와 함께 유용하게 사용할 수 있는 유용한 **매개변수 데코레이터**들을 제공합니다. 다음은 제공되는 데코레이터들의 종류와 각 데코레이터들이 나타내는 Express(또는 Fastify) 객체입니다.\n\n<table>\n  <tbody>\n    <tr>\n      <td><code>@Request(), @Req()</code></td>\n      <td><code>req</code></td>\n    </tr>\n    <tr>\n      <td><code>@Response(), @Res()</code></td>\n      <td><code>res</code></td>\n    </tr>\n    <tr>\n      <td><code>@Next()</code></td>\n      <td><code>next</code></td>\n    </tr>\n    <tr>\n      <td><code>@Session()</code></td>\n      <td><code>req.session</code></td>\n    </tr>\n    <tr>\n      <td><code>@Param(param?: string)</code></td>\n      <td><code>req.params</code> / <code>req.params[param]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Body(param?: string)</code></td>\n      <td><code>req.body</code> / <code>req.body[param]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Query(param?: string)</code></td>\n      <td><code>req.query</code> / <code>req.query[param]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Headers(param?: string)</code></td>\n      <td><code>req.headers</code> / <code>req.headers[param]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Ip()</code></td>\n      <td><code>req.ip</code></td>\n    </tr>\n    <tr>\n      <td><code>@HostParam()</code></td>\n      <td><code>req.hosts</code></td>\n    </tr>\n  </tbody>\n</table>\n\n추가적으로, **사용자 정의 데코레이터**를 작성할 수도 있습니다. 이게 왜 유용할까요?\n\nnode.js 세계에서는 **요청**객체에 프로퍼티들을 붙이는 경험을 흔하게 합니다. 그러고는 아래처럼 각 라우트 핸들러에서 코드를 통해 해당 프로퍼티들을 추출할 수 있습니다.\n\n```typescript\nconst user = req.user;\n```\n\n코드의 가독성을 높이고 더욱 투명하게 만들기 위해, `@User()` 데코레이터를 작성하여 모든 컨트롤러에서 재사용할 수 있습니다.\n\n```typescript\n@@filename(user.decorator)\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return request.user;\n  },\n);\n```\n\n그러고나서 필요하다면 어디서든 간단하게 이 데코레이터를 사용할 수 있습니다.\n\n```typescript\n@@filename()\n@Get()\nasync findOne(@User() user: UserEntity) {\n  console.log(user);\n}\n@@switch\n@Get()\n@Bind(User())\nasync findOne(user) {\n  console.log(user);\n}\n```\n\n#### 데이터 넘겨주기\n\n작성한 데코레이터가 특정 조건에 의존하여 동작해야 한다면, 데코레이터를 만드는 팩토리 함수에 넘겨주기 위한 `data` 매개변수를 사용할 수 있습니다. 사용 사례로는 요청 객체에서 특정 키로 프로퍼티를 가져오는 사용자 정의 데코레이터가 있습니다. 예를 들어, <a href=\"techniques/authentication#implementing-passport-strategies\">인증 계층</a>에서는 요청 내용에 대해 유효성 검사를 실시한 후에 요청 객체 속에 사용자 정의 정보를 붙입니다. 인증에 성공한 사용자 정의 정보는 다음과 같을 것입니다:\n\n```json\n{\n  \"id\": 101,\n  \"firstName\": \"Alan\",\n  \"lastName\": \"Turing\",\n  \"email\": \"alan@email.com\",\n  \"roles\": [\"admin\"]\n}\n```\n\n이제 키를 통해 이 프로퍼티를 가져와서 값이 있다면 그 값을 반환하는 데코레이터를 작성해 봅시다. (`user`객체가 없거나 객체에 값이 없다면 undefined를 반환합니다.)\n\n```typescript\n@@filename(user.decorator)\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const User = createParamDecorator(\n  (data: string, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    const user = request.user;\n\n    return data ? user?.[data] : user;\n  },\n);\n@@switch\nimport { createParamDecorator } from '@nestjs/common';\n\nexport const User = createParamDecorator((data, ctx) => {\n  const request = ctx.switchToHttp().getRequest();\n  const user = request.user;\n\n  return data ? user && user[data] : user;\n});\n```\n\n이제 컨트롤러에서 `@User()`데코레이터를 통해 특정 프로퍼티에 접근할 수 있습니다.\n\n```typescript\n@@filename()\n@Get()\nasync findOne(@User('firstName') firstName: string) {\n  console.log(`Hello ${firstName}`);\n}\n@@switch\n@Get()\n@Bind(User('firstName'))\nasync findOne(firstName) {\n  console.log(`Hello ${firstName}`);\n}\n```\n\n다른 프로퍼티에 접근하기 위해서는 똑같은 데코레이터에 다른 키를 사용하면 됩니다. 만약 `user`객체의 깊이가 깊거나 복잡하다면, 이 방법은 요청 핸들러를 더욱 쉽고 가독성 높게 구현하도록 만들어줄 수 있습니다.\n\n> info **힌트** 타입스크립트 사용자 정의들은 `createParamDecorator<T>()`함수가 제네릭 타입을 취한다는 것을 염두해 두시길 바랍니다. 예를 들어 `createParamDecorator<string>((data, ctx) => ...)`와 같이 사용하여 명시적으로 Type Safety를 강제할 수 있습니다. 또한 `createParamDecorator((data: string, ctx) => ...)`와 같이 팩토리 함수의 매개변수 타입을 정할 수도 있습니다. 두 군데 모두 타입을 명시하지 않으면 `data`의 타입은 `any`가 됩니다.\n\n#### 파이프와 함께 사용\n\nNest는 사용자 정의 파라미터 데코레이터를 이미 구현되어 있는 파라미터 데코레이터들(`@Body()`와 `@Param()`, `@Query()`)과 똑같은 방식으로 처리합니다. 즉, 파이프는 사용자 정의 데코레이터가 붙은 인자(아래 예제에서는 `user`)에 대해서도 실행됩니다. 게다가 사용자 정의 데코레이터에 직접적으로 파이프를 적용시킬 수도 있습니다:\n\n```typescript\n@@filename()\n@Get()\nasync findOne(\n  @User(new ValidationPipe({ validateCustomDecorators: true }))\n  user: UserEntity,\n) {\n  console.log(user);\n}\n@@switch\n@Get()\n@Bind(User(new ValidationPipe({ validateCustomDecorators: true })))\nasync findOne(user) {\n  console.log(user);\n}\n```\n\n> info **힌트** `validateCustomDecorators` 옵션을 꼭 true로 지정해야 합니다. `ValidationPipe`는 기본적으로 사용자 정의 데코레이터가 붙은 인자에 대해 유효성 검사를 수행하지 않습니다.\n\n#### 데코레이터 조합\n\nNest는 여러 데코레이터를 조합하는 헬퍼 메서드를 제공합니다. 예를 들어, 인증과 관련된 모든 데코레이터들을 모아 하나의 데코레이터로 사용하고 싶다면 다음과 같이 구성할 수 있습니다:\n\n```typescript\n@@filename(auth.decorator)\nimport { applyDecorators } from '@nestjs/common';\n\nexport function Auth(...roles: Role[]) {\n  return applyDecorators(\n    SetMetadata('roles', roles),\n    UseGuards(AuthGuard, RolesGuard),\n    ApiBearerAuth(),\n    ApiUnauthorizedResponse({ description: 'Unauthorized' }),\n  );\n}\n@@switch\nimport { applyDecorators } from '@nestjs/common';\n\nexport function Auth(...roles) {\n  return applyDecorators(\n    SetMetadata('roles', roles),\n    UseGuards(AuthGuard, RolesGuard),\n    ApiBearerAuth(),\n    ApiUnauthorizedResponse({ description: 'Unauthorized' }),\n  );\n}\n```\n\n그 다음엔 아래와 같이 `@Auth()`라는 사용자 정의 데코레이터를 사용합니다:\n\n```typescript\n@Get('users')\n@Auth('admin')\nfindAllUsers() {}\n```\n\n이렇게 하면 하나의 데코레이터로 네 개의 데코레이터를 모두 적용시킬 수 있는 효과를 얻을 수 있습니다.\n\n> warning **주의** `@nestjs/swagger` 패키지의 `@ApiHideProperty()` 데코레이터는 조합할 수 없으며 `applyDecorators` 함수와 함께 사용하면 제대로 동작하지 않습니다.\n"
  },
  {
    "path": "content/discover/who-uses.json",
    "content": "{\n  \"Header\": [\n    {\n      \"logo\": \"/assets/logo/roche-logo.png\",\n      \"url\": \"https://roche.com\",\n      \"width\": \"90px\"\n    },\n    {\n      \"logo\": \"/assets/logo/adidas.svg\",\n      \"url\": \"https://adidas.com\",\n      \"width\": \"80px\"\n    },\n    {\n      \"logo\": \"/assets/logo/capgemini.svg\",\n      \"url\": \"https://capgemini.com\"\n    },\n    {\n      \"logo\": \"/assets/logo/societe-generale-logo.png\",\n      \"url\": \"https://www.societegenerale.fr/\"\n    },\n    {\n      \"logo\": \"/assets/logo/rewe.svg\",\n      \"url\": \"https://rewe-digital.com/\",\n      \"width\": \"180px\"\n    },\n    {\n      \"logo\": \"/assets/logo/decathlon.png\",\n      \"url\": \"https://www.decathlon.com/\"\n    },\n    {\n      \"logo\": \"/assets/logo/autodesk.png\",\n      \"url\": \"https://www.autodesk.com/\"\n    },\n    {\n      \"logo\": \"/assets/logo/neo4j.png\",\n      \"url\": \"https://www.neo4j.com/\"\n    },\n    {\n      \"logo\": \"/assets/logo/shipt.png\",\n      \"url\": \"https://www.shipt.com/\"\n    },\n    {\n      \"logo\": \"/assets/logo/sanofi.png\",\n      \"url\": \"https://github.com/Sanofi-IADC\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/valor-software.png\",\n      \"url\": \"https://valor-software.com/\"\n    },\n    {\n      \"logo\": \"/assets/logo/sitepen.svg\",\n      \"url\": \"https://sitepen.com\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/gojob-logo.png\",\n      \"url\": \"https://gojob.com/\",\n      \"width\": \"100px\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/neoteric.png\",\n      \"url\": \"https://neoteric.eu/\"\n    },\n    {\n      \"logo\": \"/assets/logo/trellis.png\",\n      \"url\": \"https://trellis.org/\",\n      \"width\": \"70px\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/scalio-logo.svg\",\n      \"url\": \"https://scal.io\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/swingdev-logo.svg\",\n      \"url\": \"https://swingdev.io/\"\n    },\n    {\n      \"logo\": \"/assets/logo/cultura-colectiva.png\",\n      \"url\": \"https://culturacolectiva.com\",\n      \"width\": \"90px\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/trilon.png\",\n      \"url\": \"https://trilon.io\"\n    },\n    {\n      \"logo\": \"/assets/logo/architectnow.png\",\n      \"url\": \"http://architectnow.net\",\n      \"width\": \"150px\"\n    },\n    {\n      \"logo\": \"/assets/logo/iflix.svg\",\n      \"url\": \"https://www.iflix.com\",\n      \"width\": \"70px\"\n    },\n    {\n      \"logo\": \"https://nestjs.com/img/genuinebee.svg\",\n      \"url\": \"https://genuinebee.com/\"\n    },\n    {\n      \"logo\": \"/assets/logo/run-players-league.png\",\n      \"url\": \"https://runplayersleague.com\",\n      \"width\": \"80px\"\n    },\n    {\n      \"logo\": \"/assets/logo/yanrongyun.svg\",\n      \"url\": \"http://www.yanrongyun.com\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"/assets/logo/sclable.svg\",\n      \"url\": \"https://sclable.com\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"/assets/logo/dozto.png\",\n      \"url\": \"https://www.dozto.com\",\n      \"width\": \"117px\"\n    },\n    {\n      \"logo\": \"/assets/logo/qingtui.png\",\n      \"url\": \"https://www.qingtui.cn/\",\n      \"width\": \"90px\"\n    },\n    {\n      \"logo\": \"/assets/logo/crowdlinker.svg\",\n      \"url\": \"https://crowdlinker.com/\",\n      \"width\": \"110px\"\n    },\n    {\n      \"logo\": \"/assets/logo/nothing.svg\",\n      \"url\": \"https://nothing.ch/\",\n      \"width\": \"110px\"\n    },\n    {\n      \"logo\": \"/assets/logo/swissdevjobs-devops-logo.png\",\n      \"url\": \"https://swissdevjobs.ch/jobs/Dev-Ops/All\",\n      \"width\": \"65px\"\n    },\n    {\n      \"logo\": \"/assets/logo/zeoagency.svg\",\n      \"url\": \"https://zeo.org/tr/\",\n      \"width\": \"80px\"\n    },\n    {\n      \"logo\": \"/assets/logo/valueadd.png\",\n      \"url\": \"https://valueadd.pl/\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"/assets/logo/bedu.svg\",\n      \"url\": \"https://bedu.org\",\n      \"width\": \"100px\"\n    },\n    {\n      \"logo\": \"/assets/logo/shopback.png\",\n      \"url\": \"https://shopback.com\",\n      \"width\": \"100px\"\n    },\n    {\n      \"logo\": \"/assets/logo/facile.png\",\n      \"url\": \"https://www.facile.it\",\n      \"width\": \"100px\"\n    },\n    {\n      \"logo\": \"/assets/logo/interfacewerk.png\",\n      \"url\": \"https://interfacewerk.de\",\n      \"width\": \"130px\"\n    },\n    {\n      \"logo\": \"/assets/logo/ottonova.png\",\n      \"url\": \"https://www.ottonova.de\",\n      \"width\": \"130px\"\n    },\n    {\n      \"logo\": \"/assets/logo/radity.png\",\n      \"url\": \"https://radity.com\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"/assets/logo/global-cto-forum.png\",\n      \"url\": \"https://globalctoforum.org/\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"/assets/logo/rivvy.png\",\n      \"url\": \"https://rivvy.app\",\n      \"width\": \"120px\"\n    },\n    {\n      \"logo\": \"/assets/logo/vue-storefront.png\",\n      \"url\": \"https://www.vuestorefront.io/\"\n    }\n  ],\n  \"Body\": [\n    \"https://gorrion.io/\",\n    \"http://balticdatascience.com/\",\n    \"https://prohabits.com/\",\n    \"https://komed-health.com/\",\n    \"https://kerberus.com.co/\",\n    \"http://xtremis.com/\",\n    \"https://notadd.com/\",\n    \"http://jsdaddy.io/\",\n    \"https://yumpingo.com/\",\n    \"https://analytics-importer.cz/\",\n    \"https://dayzim.com/\",\n    \"https://wizkids.co.uk/\",\n    \"https://pilvia.com/\",\n    \"https://wi-q.com/\",\n    \"http://agrofel.com.br\",\n    \"https://societegenerale.com/\",\n    \"https://trashpanda.hulan.nl/\",\n    \"https://bytedance.com/\",\n    \"https://votercircle.com\",\n    \"https://erento.com\",\n    \"https://ideas.manticore-labs.com/\",\n    \"https://smartexlab.com/\",\n    \"https://automama.ru/\",\n    \"https://iflix.com/\",\n    \"https://frontendwatch.com/\",\n    \"https://mobilejazz.com/\",\n    \"https://cgiandi.com/\",\n    \"https://www.titlex.com.au/\",\n    \"https://codengage.com/\",\n    \"https://budacode.com/\",\n    \"https://blueanchor.io/\",\n    \"https://www.easymetrics.com/\",\n    \"https://getapollo.io/\",\n    \"https://big-bench.com/\",\n    \"https://www.qingtui.cn/\",\n    \"https://www.rosebayconsult.com/\",\n    \"https://www.patrocinium.com/\",\n    \"https://creatorsdaily.com\",\n    \"https://autoscar.com.br\",\n    \"https://www.mediktiv.com\",\n    \"https://harmonize.health\",\n    \"https://accerlery.be\",\n    \"https://www.facile.it\",\n    \"https://shopback.com\",\n    \"https://www.ottonova.de\",\n    \"https://www.radity.com\",\n    \"https://globalctoforum.org\",\n    \"https://halojasa.com\",\n    \"https://hexito.com\",\n    \"https://rivvy.app\",\n    \"https://padfever.com/\",\n    \"https://datenlotse.org\",\n    \"https://bemum.co\",\n    \"https://weoptimeye.ai\",\n    \"https://nemovote.com\",\n    \"https://selleo.com\",\n    \"https://pchas.ir\",\n    \"https://tayeh.ir\",\n    \"https://forwardigital.co.uk\",\n    \"https://rozetka.com.ua\",\n    \"https://www.itrio.net\",\n    \"https://dyrector.io\",\n    \"https://stijlbreuk.nl\"\n  ]\n}\n"
  },
  {
    "path": "content/discover/who-uses.md",
    "content": "### Who is using Nest?\n\nWe are proudly helping various companies building their products at scale.\nIf you are using Nest and would you like to be listed here, see this [thread](https://github.com/nestjs/nest/issues/1006).\nWe are willing to put your logo here!\n\n#### Companies\n\nAccording to our knowledge, all the following companies have built awesome projects on top of our framework:\n"
  },
  {
    "path": "content/enterprise.md",
    "content": "### Official NestJS Consulting\n\nOur goal is to ensure that your developers are successful and productive with NestJS as well as other modern technologies in today's ever-changing tech world.\n\n### Official Support\n\nWith official support, get expert help directly from the NestJS core team. We tackle your toughest challenges, and collaborate with your team on many levels such as:\n\n- Providing technical guidance & architectural reviews\n- **Mentoring** team members\n- Advising best practices\n- Solving design decisions\n- Addressing security & performance concerns\n- Performing **in-depth** code reviews\n\n<div class=\"row\">\n  <div class=\"content\">\n    <h4>Team Augmentation & Development</h4>\n    <p>\n      With team augmentation, NestJS core team members can work directly with your team on a daily basis to help take your project to the next-level. Consider us “part of your team”, tackling the most ambitious projects - right by your side.\n    </p>\n  </div>\n  <div class=\"thumbnail p-l-30\">\n    <img src=\"/assets/enterprise/help.svg\" />\n  </div>\n</div>\n\n<div class=\"row\">\n<div class=\"thumbnail p-r-30\">\n    <img src=\"/assets/enterprise/contact.svg\" />\n  </div>\n  <div class=\"content\">\n    <h4>NestJS Best Practices</h4>\n    <p>\n      Frequent code reviews can eliminate potentially hazardous bugs & issues at an early stage and help enforce best practices. Let us perform PR reviews & audits to ensure your code quality, performance, and security.\n    </p>\n  </div>\n</div>\n\n#### First-hand access\n\nDirect communication channel will boost team velocity, giving a quick access to discuss and solve problems.\n\n#### NestJS Workshops and Trainings\n\nWe provide solid kick-off training as well as more advanced ones that give teams an in-depth understanding of NestJS. We offer on-site workshops and remote intensive sessions which help get you up and running _quickly_ within the NestJS ecosystem.\n\n<div class=\"contact-us\">\n  <div class=\"column column-text\">\n    <h5>Contact us!</h5>\n    <p>\n    Let's talk how we can help you become successful with NestJS.\n    </p> \n  </div>\n   <div class=\"column column-action\">\n     <a href=\"mailto:support@nestjs.com\">CONTACT US</a>\n   </div>\n</div>\n\nReach out to us at [support@nestjs.com](mailto:support@nestjs.com), and let’s talk about your project & teams needs!\n"
  },
  {
    "path": "content/exception-filters.md",
    "content": "### Exception filters\n\nNest comes with a built-in **exceptions layer** which is responsible for processing all unhandled exceptions across an application. When an exception is not handled by your application code, it is caught by this layer, which then automatically sends an appropriate user-friendly response.\n\n<figure>\n  <img src=\"/assets/Filter_1.png\" />\n</figure>\n\nOut of the box, this action is performed by a built-in **global exception filter**, which handles exceptions of type `HttpException` (and subclasses of it). When an exception is **unrecognized** (is neither `HttpException` nor a class that inherits from `HttpException`), the built-in exception filter generates the following default JSON response:\n\n```json\n{\n  \"statusCode\": 500,\n  \"message\": \"Internal server error\"\n}\n```\n\n> info **Hint** The global exception filter partially supports the `http-errors` library. Basically, any thrown exception containing the `statusCode` and `message` property will be properly populated and send back as a response (instead of the default `InternalServerErrorException` for unrecognized exceptions).\n\n#### Throwing standard exceptions\n\nNest provides a built-in `HttpException` class, exposed from the `@nestjs/common` package. For typical HTTP REST/GraphQL API based applications, it's best practice to send standard HTTP response objects when certain error conditions occur.\n\nFor example, in the `CatsController`, we have a `findAll()` method (a `GET` route handler). Let's assume that this route handler throws an exception for some reason. To demonstrate this, we'll hard-code it as follows:\n\n```typescript\n@@filename(cats.controller)\n@Get()\nasync findAll() {\n  throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);\n}\n```\n\n> info **Hint** We used the `HttpStatus` here. This is a helper enum imported from the `@nestjs/common` package.\n\nWhen the client calls this endpoint, the response looks like this:\n\n```json\n{\n  \"statusCode\": 403,\n  \"message\": \"Forbidden\"\n}\n```\n\nThe `HttpException` constructor takes two required arguments which determine the\nresponse:\n\n- The `response` argument defines the JSON response body. It can be a `string`\n  or an `object` as described below.\n- The `status` argument defines the [HTTP status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).\n\nBy default, the JSON response body contains two properties:\n\n- `statusCode`: defaults to the HTTP status code provided in the `status` argument\n- `message`: a short description of the HTTP error based on the `status`\n\nTo override just the message portion of the JSON response body, supply a string\nin the `response` argument. To override the entire JSON response body, pass an object in the `response` argument. Nest will serialize the object and return it as the JSON response body.\n\nThe second constructor argument - `status` - should be a valid HTTP status code.\nBest practice is to use the `HttpStatus` enum imported from `@nestjs/common`.\n\nHere's an example overriding the entire response body:\n\n```typescript\n@@filename(cats.controller)\n@Get()\nasync findAll() {\n  throw new HttpException({\n    status: HttpStatus.FORBIDDEN,\n    error: 'This is a custom message',\n  }, HttpStatus.FORBIDDEN);\n}\n```\n\nUsing the above, this is how the response would look:\n\n```json\n{\n  \"status\": 403,\n  \"error\": \"This is a custom message\"\n}\n```\n\n#### Custom exceptions\n\nIn many cases, you will not need to write custom exceptions, and can use the built-in Nest HTTP exception, as described in the next section. If you do need to create customized exceptions, it's good practice to create your own **exceptions hierarchy**, where your custom exceptions inherit from the base `HttpException` class. With this approach, Nest will recognize your exceptions, and automatically take care of the error responses. Let's implement such a custom exception:\n\n```typescript\n@@filename(forbidden.exception)\nexport class ForbiddenException extends HttpException {\n  constructor() {\n    super('Forbidden', HttpStatus.FORBIDDEN);\n  }\n}\n```\n\nSince `ForbiddenException` extends the base `HttpException`, it will work seamlessly with the built-in exception handler, and therefore we can use it inside the `findAll()` method.\n\n```typescript\n@@filename(cats.controller)\n@Get()\nasync findAll() {\n  throw new ForbiddenException();\n}\n```\n\n#### Built-in HTTP exceptions\n\nNest provides a set of standard exceptions that inherit from the base `HttpException`. These are exposed from the `@nestjs/common` package, and represent many of the most common HTTP exceptions:\n\n- `BadRequestException`\n- `UnauthorizedException`\n- `NotFoundException`\n- `ForbiddenException`\n- `NotAcceptableException`\n- `RequestTimeoutException`\n- `ConflictException`\n- `GoneException`\n- `HttpVersionNotSupportedException`\n- `PayloadTooLargeException`\n- `UnsupportedMediaTypeException`\n- `UnprocessableEntityException`\n- `InternalServerErrorException`\n- `NotImplementedException`\n- `ImATeapotException`\n- `MethodNotAllowedException`\n- `BadGatewayException`\n- `ServiceUnavailableException`\n- `GatewayTimeoutException`\n- `PreconditionFailedException`\n\n#### Exception filters\n\nWhile the base (built-in) exception filter can automatically handle many cases for you, you may want **full control** over the exceptions layer. For example, you may want to add logging or use a different JSON schema based on some dynamic factors. **Exception filters** are designed for exactly this purpose. They let you control the exact flow of control and the content of the response sent back to the client.\n\nLet's create an exception filter that is responsible for catching exceptions which are an instance of the `HttpException` class, and implementing custom response logic for them. To do this, we'll need to access the underlying platform `Request` and `Response` objects. We'll access the `Request` object so we can pull out the original `url` and include that in the logging information. We'll use the `Response` object to take direct control of the response that is sent, using the `response.json()` method.\n\n```typescript\n@@filename(http-exception.filter)\nimport { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';\nimport { Request, Response } from 'express';\n\n@Catch(HttpException)\nexport class HttpExceptionFilter implements ExceptionFilter {\n  catch(exception: HttpException, host: ArgumentsHost) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse<Response>();\n    const request = ctx.getRequest<Request>();\n    const status = exception.getStatus();\n\n    response\n      .status(status)\n      .json({\n        statusCode: status,\n        timestamp: new Date().toISOString(),\n        path: request.url,\n      });\n  }\n}\n@@switch\nimport { Catch, HttpException } from '@nestjs/common';\n\n@Catch(HttpException)\nexport class HttpExceptionFilter {\n  catch(exception, host) {\n    const ctx = host.switchToHttp();\n    const response = ctx.getResponse();\n    const request = ctx.getRequest();\n    const status = exception.getStatus();\n\n    response\n      .status(status)\n      .json({\n        statusCode: status,\n        timestamp: new Date().toISOString(),\n        path: request.url,\n      });\n  }\n}\n```\n\n> info **Hint** All exception filters should implement the generic `ExceptionFilter<T>` interface. This requires you to provide the `catch(exception: T, host: ArgumentsHost)` method with its indicated signature. `T` indicates the type of the exception.\n\nThe `@Catch(HttpException)` decorator binds the required metadata to the exception filter, telling Nest that this particular filter is looking for exceptions of type `HttpException` and nothing else. The `@Catch()` decorator may take a single parameter, or a comma-separated list. This lets you set up the filter for several types of exceptions at once.\n\n#### Arguments host\n\nLet's look at the parameters of the `catch()` method. The `exception` parameter is the exception object currently being processed. The `host` parameter is an `ArgumentsHost` object. `ArgumentsHost` is a powerful utility object that we'll examine further in the [execution context chapter](/fundamentals/execution-context)\\*. In this code sample, we use it to obtain a reference to the `Request` and `Response` objects that are being passed to the original request handler (in the controller where the exception originates). In this code sample, we've used some helper methods on `ArgumentsHost` to get the desired `Request` and `Response` objects. Learn more about `ArgumentsHost` [here](/fundamentals/execution-context).\n\n\\*The reason for this level of abstraction is that `ArgumentsHost` functions in all contexts (e.g., the HTTP server context we're working with now, but also Microservices and WebSockets). In the execution context chapter we'll see how we can access the appropriate <a href=\"https://docs.nestjs.com/fundamentals/execution-context#host-methods\">underlying arguments</a> for **any** execution context with the power of `ArgumentsHost` and its helper functions. This will allow us to write generic exception filters that operate across all contexts.\n\n<app-banner-courses></app-banner-courses>\n\n#### Binding filters\n\nLet's tie our new `HttpExceptionFilter` to the `CatsController`'s `create()` method.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@UseFilters(new HttpExceptionFilter())\nasync create(@Body() createCatDto: CreateCatDto) {\n  throw new ForbiddenException();\n}\n@@switch\n@Post()\n@UseFilters(new HttpExceptionFilter())\n@Bind(Body())\nasync create(createCatDto) {\n  throw new ForbiddenException();\n}\n```\n\n> info **Hint** The `@UseFilters()` decorator is imported from the `@nestjs/common` package.\n\nWe have used the `@UseFilters()` decorator here. Similar to the `@Catch()` decorator, it can take a single filter instance, or a comma-separated list of filter instances. Here, we created the instance of `HttpExceptionFilter` in place. Alternatively, you may pass the class (instead of an instance), leaving responsibility for instantiation to the framework, and enabling **dependency injection**.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@UseFilters(HttpExceptionFilter)\nasync create(@Body() createCatDto: CreateCatDto) {\n  throw new ForbiddenException();\n}\n@@switch\n@Post()\n@UseFilters(HttpExceptionFilter)\n@Bind(Body())\nasync create(createCatDto) {\n  throw new ForbiddenException();\n}\n```\n\n> info **Hint** Prefer applying filters by using classes instead of instances when possible. It reduces **memory usage** since Nest can easily reuse instances of the same class across your entire module.\n\nIn the example above, the `HttpExceptionFilter` is applied only to the single `create()` route handler, making it method-scoped. Exception filters can be scoped at different levels: method-scoped, controller-scoped, or global-scoped. For example, to set up a filter as controller-scoped, you would do the following:\n\n```typescript\n@@filename(cats.controller)\n@UseFilters(new HttpExceptionFilter())\nexport class CatsController {}\n```\n\nThis construction sets up the `HttpExceptionFilter` for every route handler defined inside the `CatsController`.\n\nTo create a global-scoped filter, you would do the following:\n\n```typescript\n@@filename(main)\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalFilters(new HttpExceptionFilter());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n> warning **Warning** The `useGlobalFilters()` method does not set up filters for gateways or hybrid applications.\n\nGlobal-scoped filters are used across the whole application, for every controller and every route handler. In terms of dependency injection, global filters registered from outside of any module (with `useGlobalFilters()` as in the example above) cannot inject dependencies since this is done outside the context of any module. In order to solve this issue, you can register a global-scoped filter **directly from any module** using the following construction:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { APP_FILTER } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_FILTER,\n      useClass: HttpExceptionFilter,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n> info **Hint** When using this approach to perform dependency injection for the filter, note that regardless of the module where this construction is employed, the filter is, in fact, global. Where should this be done? Choose the module where the filter (`HttpExceptionFilter` in the example above) is defined. Also, `useClass` is not the only way of dealing with custom provider registration. Learn more [here](/fundamentals/custom-providers).\n\nYou can add as many filters with this technique as needed; simply add each to the providers array.\n\n#### Catch everything\n\nIn order to catch **every** unhandled exception (regardless of the exception type), leave the `@Catch()` decorator's parameter list empty, e.g., `@Catch()`.\n\nIn the example below we have a code that is platform-agnostic because it uses the [HTTP adapter](./faq/http-adapter) to deliver the response, and doesn't use any of the platform-specific objects (`Request` and `Response`) directly:\n\n```typescript\nimport {\n  ExceptionFilter,\n  Catch,\n  ArgumentsHost,\n  HttpException,\n  HttpStatus,\n} from '@nestjs/common';\nimport { HttpAdapterHost } from '@nestjs/core';\n\n@Catch()\nexport class AllExceptionsFilter implements ExceptionFilter {\n  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}\n\n  catch(exception: unknown, host: ArgumentsHost): void {\n    // In certain situations `httpAdapter` might not be available in the\n    // constructor method, thus we should resolve it here.\n    const { httpAdapter } = this.httpAdapterHost;\n\n    const ctx = host.switchToHttp();\n\n    const httpStatus =\n      exception instanceof HttpException\n        ? exception.getStatus()\n        : HttpStatus.INTERNAL_SERVER_ERROR;\n\n    const responseBody = {\n      statusCode: httpStatus,\n      timestamp: new Date().toISOString(),\n      path: httpAdapter.getRequestUrl(ctx.getRequest()),\n    };\n\n    httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);\n  }\n}\n```\n\n#### Inheritance\n\nTypically, you'll create fully customized exception filters crafted to fulfill your application requirements. However, there might be use-cases when you would like to simply extend the built-in default **global exception filter**, and override the behavior based on certain factors.\n\nIn order to delegate exception processing to the base filter, you need to extend `BaseExceptionFilter` and call the inherited `catch()` method.\n\n```typescript\n@@filename(all-exceptions.filter)\nimport { Catch, ArgumentsHost } from '@nestjs/common';\nimport { BaseExceptionFilter } from '@nestjs/core';\n\n@Catch()\nexport class AllExceptionsFilter extends BaseExceptionFilter {\n  catch(exception: unknown, host: ArgumentsHost) {\n    super.catch(exception, host);\n  }\n}\n@@switch\nimport { Catch } from '@nestjs/common';\nimport { BaseExceptionFilter } from '@nestjs/core';\n\n@Catch()\nexport class AllExceptionsFilter extends BaseExceptionFilter {\n  catch(exception, host) {\n    super.catch(exception, host);\n  }\n}\n```\n\n> warning **Warning** Method-scoped and Controller-scoped filters that extend the `BaseExceptionFilter` should not be instantiated with `new`. Instead, let the framework instantiate them automatically.\n\nThe above implementation is just a shell demonstrating the approach. Your implementation of the extended exception filter would include your tailored **business** logic (e.g., handling various conditions).\n\nGlobal filters **can** extend the base filter. This can be done in either of two ways.\n\nThe first method is to inject the `HttpServer` reference when instantiating the custom global filter:\n\n```typescript\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const { httpAdapter } = app.get(HttpAdapterHost);\n  app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nThe second method is to use the `APP_FILTER` token <a href=\"exception-filters#binding-filters\">as shown here</a>.\n"
  },
  {
    "path": "content/faq/errors.md",
    "content": "### Common errors\n\nDuring your development with NestJS, you may encounter various errors as you learn the framework.\n\n#### \"Cannot resolve dependency\" error\n\nProbably the most common error message is about Nest not being able to resolve dependencies of a provider. The error message usually looks something like this:\n\n```bash\nNest can't resolve dependencies of the <provider> (?). Please make sure that the argument <unknown_token> at index [<index>] is available in the <module> context.\n\nPotential solutions:\n- If <unknown_token> is a provider, is it part of the current <module>?\n- If <unknown_token> is exported from a separate @Module, is that module imported within <module>?\n  @Module({\n    imports: [ /* the Module containing <unknown_token> */ ]\n  })\n```\n\n\nThe most common culprit of the error, is not having the `provider` in the module's `providers` array. Please make sure that the provider is indeed in the `providers` array and following [standard NestJS provider practices](/fundamentals/custom-providers#di-fundamentals).\n\nThere are a few gotchas, that are common. One is putting a provider in an `imports` array. If this is the case, the error will have the provider's name where `<module>` should be.\n\nIf you run across this error while developing, take a look at the module mentioned in the error message and look at its `providers`. For each provider in the `providers` array, make sure the module has access to all of the dependencies. Often times, `providers` are duplicated in a \"Feature Module\" and a \"Root Module\" which means Nest will try to instantiate the provider twice. More than likely, the module containing the `provider` being duplicated should be added in the \"Root Module\"'s `imports` array instead.\n\nIf the `unknown_token` above is the string `dependency`, you might have a circular file import. This is different from the [circular dependency](./errors.md#circular-dependency-error) below because instead of  having providers depend on each other in their constructors, it just means that two files end up importing each other. A common case would be a module file declaring a token and importing a provider, and the provider import the token constant from the module file. If you are using barrel files, ensure that your barrel imports do not end up creating these circular imports as well.\n\n#### \"Circular dependency\" error\n\nOccasionally you'll find it difficult to avoid [circular dependencies](/fundamentals/circular-dependency) in your application. You'll need to take some steps to help Nest resolve these. Errors that arise from circular dependencies look like this:\n\n```bash\nNest cannot create the <module> instance.\nThe module at index [<index>] of the <module> \"imports\" array is undefined.\n\nPotential causes:\n- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency\n- The module at index [<index>] is of type \"undefined\". Check your import statements and the type of the module.\n\nScope [<module_import_chain>]\n# example chain AppModule -> FooModule\n```\n\nCircular dependencies can arise from both providers depending on each other, or typescript files depending on each other for constants, such as exporting constants from a module file and importing them in a service file. In the latter case, it is advised to create a separate file for your constants. In the former case, please follow the guide on circular dependencies and make sure that both the modules **and** the providers are marked with `forwardRef`.\n\n#### Debugging dependency errors\n\nAlong with just manually verifying your dependencies are correct, as of Nest 8.1.0 you can set the `NEST_DEBUG` environment variable to a string that resolves as truthy, and get extra logging information while Nest is resolving all of the dependencies for the application. \n\n<figure><img src=\"/assets/injector_logs.png\" /></figure>\n\nIn the above image, the string in yellow is the host class of the dependency being injected, the string in blue is the name of the injected dependency, or its injection token, and the string in purple is the module in which the dependency is being searched for. Using this, you can usually trace back the dependency resolution for what's happening and why you're getting dependency injection problems.\n"
  },
  {
    "path": "content/faq/global-prefix.md",
    "content": "### Global prefix\n\nHTTP 어플리케이션에 등록된 **모든 경로에** 접두사(prefix)를 붙이기 위해서는, `INestApplication` 인스턴스의 `setGlobalPrefix()` 메서드를 사용합니다.\n\n```typescript\nconst app = await NestFactory.create(AppModule);\napp.setGlobalPrefix('v1');\n```\n\n다음 구성을 사용해 전역 접두사(prefix)에서 경로를 제외할 수 있습니다.\n\n```typescript\napp.setGlobalPrefix('v1', {\n  exclude: [{ path: 'health', method: RequestMethod.GET }],\n});\n```\n\n대안으로, 경로를 문자열로 지정할 수도 있습니다 (모든 요청 메서드에 적용됩니다).\n\n```typescript\napp.setGlobalPrefix('v1', { exclude: ['cats'] });\n```\n"
  },
  {
    "path": "content/faq/http-adapter.md",
    "content": "### HTTP adapter\n\nOccasionally, you may want to access the underlying HTTP server, either within the Nest application context or from the outside.\n\nEvery native (platform-specific) HTTP server/library (e.g., Express and Fastify) instance is wrapped in an **adapter**. The adapter is registered as a globally available provider that can be retrieved from the application context, as well as injected into other providers.\n\n#### Outside application context strategy\n\nTo get a reference to the `HttpAdapter` from outside of the application context, call the `getHttpAdapter()` method.\n\n```typescript\n@@filename()\nconst app = await NestFactory.create(AppModule);\nconst httpAdapter = app.getHttpAdapter();\n```\n\n#### In-context strategy\n\nTo get a reference to the `HttpAdapterHost` from within the application context, inject it using the same technique as any other existing provider (e.g., using constructor injection).\n\n```typescript\n@@filename()\nexport class CatsService {\n  constructor(private adapterHost: HttpAdapterHost) {}\n}\n@@switch\n@Dependencies(HttpAdapterHost)\nexport class CatsService {\n  constructor(adapterHost) {\n    this.adapterHost = adapterHost;\n  }\n}\n```\n\n> info **Hint** The `HttpAdapterHost` is imported from the `@nestjs/core` package.\n\nThe `HttpAdapterHost` is **not** an actual `HttpAdapter`. To get the actual `HttpAdapter` instance, simply access the `httpAdapter` property.\n\n```typescript\nconst adapterHost = app.get(HttpAdapterHost);\nconst httpAdapter = adapterHost.httpAdapter;\n```\n\nThe `httpAdapter` is the actual instance of the HTTP adapter used by the underlying framework. It is an instance of either `ExpressAdapter` or `FastifyAdapter` (both classes extend `AbstractHttpAdapter`).\n\nThe adapter object exposes several useful methods to interact with the HTTP server. However, if you want to access the library instance (e.g., the Express instance) directly, call the `getInstance()` method.\n\n```typescript\nconst instance = httpAdapter.getInstance();\n```\n"
  },
  {
    "path": "content/faq/hybrid-application.md",
    "content": "### Hybrid application\n\nA hybrid application is one that both listens for HTTP requests, as well as makes use of connected microservices. The `INestApplication` instance can be connected with `INestMicroservice` instances through the `connectMicroservice()` method.\n\n```typescript\nconst app = await NestFactory.create(AppModule);\nconst microservice = app.connectMicroservice({\n  transport: Transport.TCP,\n});\n\nawait app.startAllMicroservices();\nawait app.listen(3001);\n```\n\nTo connect multiple microservice instances, issue the call to `connectMicroservice()` for each microservice:\n\n```typescript\nconst app = await NestFactory.create(AppModule);\n// microservice #1\nconst microserviceTcp = app.connectMicroservice<MicroserviceOptions>({\n  transport: Transport.TCP,\n  options: {\n    port: 3001,\n  },\n});\n// microservice #2\nconst microserviceRedis = app.connectMicroservice<MicroserviceOptions>({\n  transport: Transport.REDIS,\n  options: {\n    url: 'redis://localhost:6379',\n  },\n});\n\nawait app.startAllMicroservices();\nawait app.listen(3001);\n```\n\nTo bind `@MessagePattern()` to only one transport strategy (for example, MQTT) in a hybrid application with multiple microservices, we can pass the second argument of type `Transport` which is an enum with all the built-in transport strategies defined.\n\n```typescript\n@@filename()\n@MessagePattern('time.us.*', Transport.NATS)\ngetDate(@Payload() data: number[], @Ctx() context: NatsContext) {\n  console.log(`Subject: ${context.getSubject()}`); // e.g. \"time.us.east\"\n  return new Date().toLocaleTimeString(...);\n}\n@MessagePattern({ cmd: 'time.us' }, Transport.TCP)\ngetTCPDate(@Payload() data: number[]) {\n  return new Date().toLocaleTimeString(...);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('time.us.*', Transport.NATS)\ngetDate(data, context) {\n  console.log(`Subject: ${context.getSubject()}`); // e.g. \"time.us.east\"\n  return new Date().toLocaleTimeString(...);\n}\n@Bind(Payload(), Ctx())\n@MessagePattern({ cmd: 'time.us' }, Transport.TCP)\ngetTCPDate(data, context) {\n  return new Date().toLocaleTimeString(...);\n}\n```\n\n> info **Hint** `@Payload()`, `@Ctx()`, `Transport` and `NatsContext` are imported from `@nestjs/microservices`.\n\n#### Sharing configuration\n\nBy default a hybrid application will not inherit global pipes, interceptors, guards and filters configured for the main (HTTP-based) application.\nTo inherit these configuration properties from the main application, set the `inheritAppConfig` property in the second argument (an optional options object) of the `connectMicroservice()` call, as follow:\n\n```typescript\nconst microservice = app.connectMicroservice({\n  transport: Transport.TCP\n}, { inheritAppConfig: true });\n```\n"
  },
  {
    "path": "content/faq/multiple-servers.md",
    "content": "### HTTPS\n\nTo create an application that uses the HTTPS protocol, set the `httpsOptions` property in the options object passed to the `create()` method of the `NestFactory` class:\n\n```typescript\nconst httpsOptions = {\n  key: fs.readFileSync('./secrets/private-key.pem'),\n  cert: fs.readFileSync('./secrets/public-certificate.pem'),\n};\nconst app = await NestFactory.create(AppModule, {\n  httpsOptions,\n});\nawait app.listen(3000);\n```\n\nIf you use the `FastifyAdapter`, create the application as follows:\n\n```typescript\nconst app = await NestFactory.create<NestFastifyApplication>(\n  AppModule,\n  new FastifyAdapter({ https: httpsOptions }),\n);\n```\n\n#### Multiple simultaneous servers\n\nThe following recipe shows how to instantiate a Nest application that listens on multiple ports (for example, on a non-HTTPS port and an HTTPS port) simultaneously.\n\n```typescript\nconst httpsOptions = {\n  key: fs.readFileSync('./secrets/private-key.pem'),\n  cert: fs.readFileSync('./secrets/public-certificate.pem'),\n};\n\nconst server = express();\nconst app = await NestFactory.create(\n  AppModule,\n  new ExpressAdapter(server),\n);\nawait app.init();\n\nhttp.createServer(server).listen(3000);\nhttps.createServer(httpsOptions, server).listen(443);\n```\n\n> info **Hint** The `ExpressAdapter` is imported from the `@nestjs/platform-express` package. The `http` and `https` packages are native Node.js packages.\n\n> **Warning** This recipe does not work with [GraphQL Subscriptions](/graphql/subscriptions).\n"
  },
  {
    "path": "content/faq/request-lifecycle.md",
    "content": "### Request lifecycle\n\nNest applications handle requests and produce responses in a sequence we refer to as the **request lifecycle**. With the use of middleware, pipes, guards, and interceptors, it can be challenging to track down where a particular piece of code executes during the request lifecycle, especially as global, controller level, and route level components come into play. In general, a request flows through middleware to guards, then to interceptors, then to pipes and finally back to interceptors on the return path (as the response is generated).\n\n#### Middleware\n\nMiddleware is executed in a particular sequence. First, Nest runs globally bound middleware (such as middleware bound with `app.use`) and then it runs [module bound middleware](/middleware), which are determined on paths. Middleware are run sequentially in the order they are bound, similar to the way middleware in Express works. In the case of middleware bound across different modules, the middleware bound to the root module will run first, and then middleware will run in the order that the modules are added to the imports array.\n\n#### Guards\n\nGuard execution starts with global guards, then proceeds to controller guards, and finally to route guards. As with middleware, guards run in the order in which they are bound. For example:\n\n```typescript\n@UseGuards(Guard1, Guard2)\n@Controller('cats')\nexport class CatsController {\n  constructor(private catsService: CatsService) {}\n\n  @UseGuards(Guard3)\n  @Get()\n  getCats(): Cats[] {\n    return this.catsService.getCats();\n  }\n}\n```\n\n`Guard1` will execute before `Guard2` and both will execute before `Guard3`.\n\n> info **Hint** When speaking about globally bound vs controller or locally bound, the difference is where the guard (or other component is bound). If you are using `app.useGlobalGuard()` or providing the component via a module, it is globally bound. Otherwise, it is bound to a controller if the decorator precedes a controller class, or to a route if the decorator proceeds a route declaration.\n\n#### Interceptors\n\nInterceptors, for the most part, follow the same pattern as guards, with one catch: as interceptors return [RxJS Observables](https://github.com/ReactiveX/rxjs), the observables will be resolved in a first in last out manner. So inbound requests will go through the standard global, controller, route level resolution, but the response side of the request (i.e., after returning from the controller method handler) will be resolved from route to controller to global. Also, any errors thrown by pipes, controllers, or services can be read in the `catchError` operator of an interceptor.\n\n#### Pipes\n\nPipes follow the standard global to controller to route bound sequence, with the same first in first out in regards to the `@usePipes()` parameters. However, at a route parameter level, if you have multiple pipes running, they will run in the order of the last parameter with a pipe to the first. This also applies to the route level and controller level pipes. For example, if we have the following controller:\n\n```typescript\n@UsePipes(GeneralValidationPipe)\n@Controller('cats')\nexport class CatsController {\n  constructor(private catsService: CatsService) {}\n\n  @UsePipes(RouteSpecificPipe)\n  @Patch(':id')\n  updateCat(\n    @Body() body: UpdateCatDTO,\n    @Param() params: UpdateCatParams,\n    @Query() query: UpdateCatQuery,\n  ) {\n    return this.catsService.updateCat(body, params, query);\n  }\n}\n```\n\nthen the `GeneralValidationPipe` will run for the `query`, then the `params`, and then the `body` objects before moving on to the `RouteSpecificPipe`, which follows the same order. If any parameter-specific pipes were in place, they would run (again, from the last to first parameter) after the controller and route level pipes.\n\n#### Filters\n\nFilters are the only component that do not resolve global first. Instead, filters resolve from the lowest level possible, meaning execution starts with any route bound filters and proceeding next to controller level, and finally to global filters. Note that exceptions cannot be passed from filter to filter; if a route level filter catches the exception, a controller or global level filter cannot catch the same exception. The only way to achieve an effect like this is to use inheritance between the filters.\n\n> info **Hint** Filters are only executed if any uncaught exception occurs during the request process. Caught exceptions, such as those caught with a `try/catch` will not trigger Exception Filters to fire. As soon as an uncaught exception is encountered, the rest of the lifecycle is ignored and the request skips straight to the filter.\n\n#### Summary\n\nIn general, the request lifecycle looks like the following:\n\n1. Incoming request\n2. Globally bound middleware\n3. Module bound middleware\n4. Global guards\n5. Controller guards\n6. Route guards\n7. Global interceptors (pre-controller)\n8. Controller interceptors (pre-controller)\n9. Route interceptors (pre-controller)\n10. Global pipes\n11. Controller pipes\n12. Route pipes\n13. Route parameter pipes\n14. Controller (method handler)\n15. Service (if exists)\n16. Route interceptor (post-request)\n17. Controller interceptor (post-request)\n18. Global interceptor (post-request)\n19. Exception filters (route, then controller, then global)\n20. Server response\n"
  },
  {
    "path": "content/faq/serverless.md",
    "content": "### Serverless\n\nServerless computing is a cloud computing execution model in which the cloud provider allocates machine resources on-demand, taking care of the servers on behalf of their customers. When an app is not in use, there are no computing resources allocated to the app. Pricing is based on the actual amount of resources consumed by an application ([source](https://en.wikipedia.org/wiki/Serverless_computing)).\n\nWith a **serverless architecture**, you focus purely on the individual functions in your application code. Services such as AWS Lambda, Google Cloud Functions, and Microsoft Azure Functions take care of all the physical hardware, virtual machine operating system, and web server software management.\n\n> info **Hint** This chapter does not cover the pros and cons of serverless functions nor dives into the specifics of any cloud providers.\n\n#### Cold start\n\nA cold start is the first time your code has been executed in a while. Depending on a cloud provider you use, it may span several different operations, from downloading the code and bootstrapping the runtime to eventually running your code.\nThis process adds **significant latency** depending on several factors, the language, the number of packages your application require, etc.\n\nThe cold start is important and although there are things which are beyond our control, there's still a lot of things we can do on our side to make it as short as possible.\n\nWhile you can think of Nest as a fully-fledged framework designed to be used in complex, enterprise applications,\nit is also **suitable for much \"simpler\" applications** (or scripts). For example, with the use of [Standalone applications](/standalone-applications) feature, you can take advantage of Nest's DI system in simple workers, CRON jobs, CLIs, or serverless functions.\n\n#### Benchmarks\n\nTo better understand what's the cost of using Nest or other, well-known libraries (like `express`) in the context of serverless functions, let's compare how much time Node runtime needs to run the following scripts:\n\n```typescript\n// #1 Express\nimport * as express from 'express';\n\nasync function bootstrap() {\n  const app = express();\n  app.get('/', (req, res) => res.send('Hello world!'));\n  await new Promise<void>((resolve) => app.listen(3000, resolve));\n}\nbootstrap();\n\n// #2 Nest (with @nestjs/platform-express)\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, { logger: ['error'] });\n  await app.listen(3000);\n}\nbootstrap();\n\n// #3 Nest as a Standalone application (no HTTP server)\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\nimport { AppService } from './app.service';\n\nasync function bootstrap() {\n  const app = await NestFactory.createApplicationContext(AppModule, {\n    logger: ['error'],\n  });\n  console.log(app.get(AppService).getHello());\n}\nbootstrap();\n\n// #4 Raw Node.js script\nasync function bootstrap() {\n  console.log('Hello world!');\n}\nbootstrap();\n```\n\nFor all these scripts, we used the `tsc` (TypeScript) compiler and so the code remains unbundled (`webpack` isn't used).\n\n|                                      |                   |\n| ------------------------------------ | ----------------- |\n| Express                              | 0.0079s (7.9ms)   |\n| Nest with `@nestjs/platform-express` | 0.1974s (197.4ms) |\n| Nest (standalone application)        | 0.1117s (111.7ms) |\n| Raw Node.js script                   | 0.0071s (7.1ms)   |\n\n> info **Note** Machine: MacBook Pro Mid 2014, 2.5 GHz Quad-Core Intel Core i7, 16 GB 1600 MHz DDR3, SSD.\n\nNow, let's repeat all benchmarks but this time, using `webpack` (if you have [Nest CLI](/cli/overview) installed, you can run `nest build --webpack`) to bundle our application into a single executable JavaScript file.\nHowever, instead of using the default `webpack` configuration that Nest CLI ships with, we'll make sure to bundle all dependencies (`node_modules`) together, as follows:\n\n```javascript\nmodule.exports = (options, webpack) => {\n  const lazyImports = [\n    '@nestjs/microservices/microservices-module',\n    '@nestjs/websockets/socket-module',\n  ];\n\n  return {\n    ...options,\n    externals: [],\n    plugins: [\n      ...options.plugins,\n      new webpack.IgnorePlugin({\n        checkResource(resource) {\n          if (lazyImports.includes(resource)) {\n            try {\n              require.resolve(resource);\n            } catch (err) {\n              return true;\n            }\n          }\n          return false;\n        },\n      }),\n    ],\n  };\n};\n```\n\n> info **Hint** To instruct Nest CLI to use this configuration, create a new `webpack.config.js` file in the root directory of your project.\n\nWith this configuration, we received the following results:\n\n|                                      |                  |\n| ------------------------------------ | ---------------- |\n| Express                              | 0.0068s (6.8ms)  |\n| Nest with `@nestjs/platform-express` | 0.0815s (81.5ms) |\n| Nest (standalone application)        | 0.0319s (31.9ms) |\n| Raw Node.js script                   | 0.0066s (6.6ms)  |\n\n> info **Note** Machine: MacBook Pro Mid 2014, 2.5 GHz Quad-Core Intel Core i7, 16 GB 1600 MHz DDR3, SSD.\n\n> info **Hint** You could optimize it even further by applying additional code minification & optimization techniques (using `webpack` plugins, etc.).\n\nAs you can see, the way you compile (and whether you bundle your code) is crucial and has a significant impact on the overall startup time. With `webpack`, you can get the bootstrap time of a standalone Nest application (starter project with one module, controller, and service) down to ~32ms on average, and down to ~81.5ms for a regular HTTP, express-based NestJS app.\n\nFor more complicated Nest applications, for example, with 10 resources (generated through `$ nest g resource` schematic = 10 modules, 10 controllers, 10 services, 20 DTO classes, 50 HTTP endpoints + `AppModule`), the overall startup on MacBook Pro Mid 2014, 2.5 GHz Quad-Core Intel Core i7, 16 GB 1600 MHz DDR3, SSD is approximately 0.1298s (129.8ms). Running a monolithic application as a serverless function typically doesn't make too much sense anyway, so think of this benchmark more as an example of how the bootstrap time may potentially increase as your application grows.\n\n#### Runtime optimizations\n\nThus far we covered compile-time optimizations. These are unrelated to the way you define providers and load Nest modules in your application, and that plays an essential role as your application gets bigger.\n\nFor example, imagine having a database connection defined as an [asynchronous provider](/fundamentals/async-providers). Async providers are designed to delay the application start until one or more asynchronous tasks are completed.\nThat means, if your serverless function on average requires 2s to connect to the database (on bootstrap), your endpoint will need at least two extra seconds (because it must wait till the connection is established) to send a response back (when it's a cold start and your application wasn't running already).\n\nAs you can see, the way you structure your providers is somewhat different in a **serverless environment** where bootstrap time is important.\nAnother good example is if you use Redis for caching, but only in certain scenarios. Perhaps, in this case, you should not define a Redis connection as an async provider, as it would slow down the bootstrap time, even if it's not required for this specific function invocation.\n\nAlso, sometimes you could lazy-load entire modules, using the `LazyModuleLoader` class, as described in [this chapter](/fundamentals/lazy-loading-modules). Caching is a great example here too.\nImagine that your application has, let's say, `CacheModule` which internally connects to Redis and also, exports the `CacheService` to interact with the Redis storage. If you don't need it for all potential function invocations,\nyou can just load it on-demand, lazily. This way you'll get a faster startup time (when a cold start occurs) for all invocations that don't require caching.\n\n```typescript\nif (request.method === RequestMethod[RequestMethod.GET]) {\n  const { CacheModule } = await import('./cache.module');\n  const moduleRef = await this.lazyModuleLoader.load(() => CacheModule);\n\n  const { CacheService } = await import('./cache.service');\n  const cacheService = moduleRef.get(CacheService);\n\n  return cacheService.get(ENDPOINT_KEY);\n}\n```\n\nAnother great example is a webhook or worker, which depending on some specific conditions (e.g., input arguments), may perform different operations.\nIn such a case, you could specify a condition inside your route handler that lazily loads an appropriate module for the specific function invocation, and just load every other module lazily.\n\n```typescript\nif (workerType === WorkerType.A) {\n  const { WorkerAModule } = await import('./worker-a.module');\n  const moduleRef = await this.lazyModuleLoader.load(() => WorkerAModule);\n  // ...\n} else if (workerType === WorkerType.B) {\n  const { WorkerBModule } = await import('./worker-b.module');\n  const moduleRef = await this.lazyModuleLoader.load(() => WorkerBModule);\n  // ...\n}\n```\n\n#### Example integration\n\nThe way your application's entry file (typically `main.ts` file) is supposed to look like **depends on several factors** and so **there's no single template** that just works for every scenario.\nFor example, the initialization file required to spin up your serverless function varies by cloud providers (AWS, Azure, GCP, etc.).\nAlso, depending on whether you want to run a typical HTTP application with multiple routes/endpoints or just provide a single route (or execute a specific portion of code),\nyour application's code will look different (for example, for the endpoint-per-function approach you could use the `NestFactory.createApplicationContext` instead of booting the HTTP server, setting up middleware, etc.).\n\nJust for illustration purposes, we'll integrate Nest (using `@nestjs/platform-express` and so spinning up the whole, fully functional HTTP router)\nwith the [Serverless](https://www.serverless.com/) framework (in this case, targetting AWS Lambda). As we've mentioned earlier, your code will differ depending on the cloud provider you choose, and many other factors.\n\nFirst, let's install the required packages:\n\n```bash\n$ npm i @vendia/serverless-express aws-lambda\n$ npm i -D @types/aws-lambda serverless-offline\n```\n\n> info **Hint** To speed up development cycles, we install the `serverless-offline` plugin which emulates AWS λ and API Gateway.\n\nOnce the installation process is complete, let's create the `serverless.yml` file to configure the Serverless framework:\n\n```yaml\nservice:\n  name: serverless-example\n\nplugins:\n  - serverless-offline\n\nprovider:\n  name: aws\n  runtime: nodejs12.x\n\nfunctions:\n  main:\n    handler: dist/main.handler\n    events:\n      - http:\n          method: ANY\n          path: /\n      - http:\n          method: ANY\n          path: '{proxy+}'\n```\n\n> info **Hint** To learn more about the Serverless framework, visit the [official documentation](https://www.serverless.com/framework/docs/).\n\nWith this place, we can now navigate to the `main.ts` file and update our bootstrap code with the required boilerplate:\n\n```typescript\nimport { NestFactory } from '@nestjs/core';\nimport serverlessExpress from '@vendia/serverless-express';\nimport { Callback, Context, Handler } from 'aws-lambda';\nimport { AppModule } from './app.module';\n\nlet server: Handler;\n\nasync function bootstrap(): Promise<Handler> {\n  const app = await NestFactory.create(AppModule);\n  await app.init();\n\n  const expressApp = app.getHttpAdapter().getInstance();\n  return serverlessExpress({ app: expressApp });\n}\n\nexport const handler: Handler = async (\n  event: any,\n  context: Context,\n  callback: Callback,\n) => {\n  server = server ?? (await bootstrap());\n  return server(event, context, callback);\n};\n```\n\n> info **Hint** For creating multiple serverless functions and sharing common modules between them, we recommend using the [CLI Monorepo mode](/cli/monorepo#monorepo-mode).\n\n> warning **Warning** If you use `@nestjs/swagger` package, there are a few additional steps required to make it work properly in the context of serverless function. Check out this [article](https://javascript.plainenglish.io/serverless-nestjs-document-your-api-with-swagger-and-aws-api-gateway-64a53962e8a2) for more information.\n\nNext, open up the `tsconfig.json` file and make sure to enable the `esModuleInterop` option to make the `@vendia/serverless-express` package load properly.\n\n```json\n{\n  \"compilerOptions\": {\n    ...\n    \"esModuleInterop\": true\n  }\n}\n```\n\nNow we can build our application (with `nest build` or `tsc`) and use the `serverless` CLI to start our lambda function locally:\n\n```bash\n$ npm run build\n$ npx serverless offline\n```\n\nOnce the application is running, open your browser and navigate to `http://localhost:3000/dev/[ANY_ROUTE]` (where `[ANY_ROUTE]` is any endpoint registered in your application).\n\nIn the sections above, we've shown that using `webpack` and bundling your app can have significant impact on the overall bootstrap time.\nHowever, to make it work with our example, there are a few additional configurations you must add in your `webpack.config.js` file. Generally,\nto make sure our `handler` function will be picked up, we must change the `output.libraryTarget` property to `commonjs2`.\n\n```javascript\nreturn {\n  ...options,\n  externals: [],\n  output: {\n    ...options.output,\n    libraryTarget: 'commonjs2',\n  },\n  // ... the rest of the configuration\n};\n```\n\nWith this in place, you can now use `$ nest build --webpack` to compile your function's code (and then `$ npx serverless offline` to test it).\n\nIt's also recommended (but **not required** as it will slow down your build process) to install the `terser-webpack-plugin` package and override its configuration to keep classnames intact when minifying your production build. Not doing so can result in incorrect behavior when using `class-validator` within your application.\n\n```javascript\nconst TerserPlugin = require('terser-webpack-plugin');\n\nreturn {\n  ...options,\n  externals: [],\n  optimization: {\n    minimizer: [\n      new TerserPlugin({\n        terserOptions: {\n          keep_classnames: true,\n        },\n      }),\n    ],\n  },\n  output: {\n    ...options.output,\n    libraryTarget: 'commonjs2',\n  },\n  // ... the rest of the configuration\n};\n```\n\n#### Using standalone application feature\n\nAlternatively, if you want to keep your function very lightweight and you don't need any HTTP-related features (routing, but also guards, interceptors, pipes, etc.),\nyou can just use `NestFactory.createApplicationContext` (as mentioned earlier) instead of running the entire HTTP server (and `express` under the hood), as follows:\n\n```typescript\n@@filename(main)\nimport { HttpStatus } from '@nestjs/common';\nimport { NestFactory } from '@nestjs/core';\nimport { Callback, Context, Handler } from 'aws-lambda';\nimport { AppModule } from './app.module';\nimport { AppService } from './app.service';\n\nexport const handler: Handler = async (\n  event: any,\n  context: Context,\n  callback: Callback,\n) => {\n  const appContext = await NestFactory.createApplicationContext(AppModule);\n  const appService = appContext.get(AppService);\n\n  return {\n    body: appService.getHello(),\n    statusCode: HttpStatus.OK,\n  };\n};\n```\n\n> info **Hint** Be aware that `NestFactory.createApplicationContext` does not wrap controller methods with enhancers (guard, interceptors, etc.). For this, you must use the `NestFactory.create` method.\n\nYou could also pass the `event` object down to, let's say, `EventsService` provider that could process it and return a corresponding value (depending on the input value and your business logic).\n\n```typescript\nexport const handler: Handler = async (\n  event: any,\n  context: Context,\n  callback: Callback,\n) => {\n  const appContext = await NestFactory.createApplicationContext(AppModule);\n  const eventsService = appContext.get(EventsService);\n  return eventsService.process(event);\n};\n```\n"
  },
  {
    "path": "content/first-steps.md",
    "content": "### 시작하기\n\n이 문서에서는 Nest의 **핵심 원리** 에 대해 알아봅니다. Nest 애플리케이션의 필수 구성 요소를 숙지하려면,\n기초적인 수준에서 많은 분야를 다루며 기본적인 CRUD 애플리케이션을 구축해 봐야 합니다.\n\n#### 언어\n\n우리는 [TypeScript](https://www.typescriptlang.org/)와 사랑에 빠졌지만, 무엇보다도 [Node.js](https://nodejs.org/en/)를 사랑합니다. 이것이 Nest가 TypeScript, **pure JavaScript** 모두와 호환되는 이유입니다. Nest는 최신 언어 기능을 활용하기 때문에 바닐라 자바스크립트와 함께 사용하려면 [Babel](https://babeljs.io/) 컴파일러가 필요합니다.\n\n우리가 제공하는 예제 에서는 대부분 타입스크립트를 사용하겠지만, 언제든 바닐라 자바스크립트로 **코드 스니펫을 전환** 할 수 있습니다 (각 스니펫의 오른쪽 상단 모서리에 있는 언어 버튼을 클릭하여 전환).\n\n#### 전제조건\n\n운영 체제에 [Node.js](https://nodejs.org/)(>= 10.13.0, v13 제외)가 설치되어 있는지 확인하세요.\n\n#### 설정하기\n\n[Nest CLI](/cli/overview) 로 새 프로젝트를 설정하는 것은 매우 간단합니다. [npm](https://www.npmjs.com/)이 설치되어 있다면, OS 터미널에서 다음 명령을 사용해 새 Nest 프로젝트를 생성할 수 있습니다.\n\n```bash\n$ npm i -g @nestjs/cli\n$ nest new project-name\n```\n\n`project-name` 디렉토리가 생성되고, node modules 와 몇가지 boilerplate 파일들이 생성되며, `src/` 디렉토리와 함께 여러개의 코어 파일들로 채워집니다.\n\n<div class=\"file-tree\">\n  <div class=\"item\">src</div>\n  <div class=\"children\">\n    <div class=\"item\">app.controller.spec.ts</div>\n    <div class=\"item\">app.controller.ts</div>\n    <div class=\"item\">app.module.ts</div>\n    <div class=\"item\">app.service.ts</div>\n    <div class=\"item\">main.ts</div>\n  </div>\n</div>\n\n다음은 코어 파일들의 간략한 설명 입니다.\n\n|                          |                                                                                                                     |\n| ------------------------ | ------------------------------------------------------------------------------------------------------------------- |\n| `app.controller.ts`      | A basic controller with a single route.                                                                             |\n| `app.controller.spec.ts` | The unit tests for the controller.                                                                                  |\n| `app.module.ts`          | The root module of the application.                                                                                 |\n| `app.service.ts`         | A basic service with a single method.                                                                               |\n| `main.ts`                | The entry file of the application which uses the core function `NestFactory` to create a Nest application instance. |\n\n`main.ts`는 우리의 어플리케이션의 **시작점**이 되는 비동기 함수를 포함하고 있습니다.\n\n```typescript\n@@filename(main)\n\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n@@switch\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nNest 애플리케이션 인스턴스를 생성하기 위해 우리는 `NestFactory` 클래스를 사용합니다. `NestFactory` 는 애플리케이션 인스턴스를 만들 수 있는 몇가지 정적 메소드를 제공합니다. `create()` 메소드는 `INestApplication` 인터페이스를 따르는 애플리케이션 객체를 반환합니다. 이 객체는 다음 장에서 설명하는 메소드 집합을 제공합니다. 우리는 위의 `main.ts` 예제에서 HTTP 요청을 받을 수 있도록 HTTP 리스너를 실행 했습니다.\n\nNest CLI로 생성된 프로젝트는 개발자가 각 모듈을 독립된 디렉토리에 작성하는 관례를 따르도록 권장하기 위해 초기 프로젝트 구조를 생성합니다.\n\n<app-banner-courses></app-banner-courses>\n\n#### 플랫폼\n\nNest는 플랫폼에 구애받지 않는 프레임워크가 되는 것을 목표로 합니다. 플랫폼 독립성을 통해 개발자가 여러 유형의 애플리케이션에 걸쳐 활용할 수 있는 재사용 가능한 논리적 모듈을 만들 수 있습니다. 기술적으로 Nest는 어댑터가 만들어지면 어떤 Node HTTP 프레임워크에서도 동작 합니다. 기본적으로 지원되는 HTTP 플랫폼은 [express](https://expressjs.com/)와 [fastify](https://www.fastify.io) 두 가지가 있습니다. 요구사항에 맞는 적합한 프레임워크를 선택하여 사용하면 됩니다.\n\n|                    |                                                                                                                                                                                                                                                                                                                                    |\n| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `platform-express` | [Express](https://expressjs.com/) is a well-known minimalist web framework for node. It's a battle tested, production-ready library with lots of resources implemented by the community. The `@nestjs/platform-express` package is used by default. Many users are well served with Express, and need take no action to enable it. |\n| `platform-fastify` | [Fastify](https://www.fastify.io/) is a high performance and low overhead framework highly focused on providing maximum efficiency and speed. Read how to use it [here](/techniques/performance).                                                                                                                                  |\n\n어떤 플랫폼을 사용하더라도 자체적인 애플리케이션 인터페이스를 제공합니다. 각각 `NestExpressApplication` 과 `NestFastifyApplication` 입니다.\n\n아래 예제와 같이 타입을 `NestFactory.create()` 메소드에 전달하면 `app` 객체는 해당 특정 플랫폼에서만 사용할 수있는 메소드를 갖게 됩니다. 하지만 참고로, 실제로 기본 플랫폼 API에 액세스하려는 경우가 **아니라면** 타입을 지정할 **필요**가 없습니다.\n\n```typescript\nconst app = await NestFactory.create<NestExpressApplication>(AppModule);\n```\n\n#### 애플리케이션 실행\n\n설치가 끝났다면 OS 명령 프롬프트에서 다음 명령을 실행하여 HTTP 요청을 기다리는 애플리케이션을 시작할 수 있습니다.\n\n```bash\n$ npm run start\n```\n\n이 명령은 `src/main.ts` 파일에 정의된 포트에서 HTTP 서버 앱을 시작합니다. 애플리케이션이 실행되면 브라우저를 열고 `http://localhost:3000/`로 이동하세요. `Hello World!` 라는 메시지를 볼 수 있습니다.\n"
  },
  {
    "path": "content/fundamentals/async-components.md",
    "content": "### Asynchronous providers\n\nAt times, the application start should be delayed until one or more **asynchronous tasks** are completed. For example, you may not want to start accepting requests until the connection with the database has been established. You can achieve this using asynchronous providers.\n\nThe syntax for this is to use `async/await` with the `useFactory` syntax. The factory returns a `Promise`, and the factory function can `await` asynchronous tasks. Nest will await resolution of the promise before instantiating any class that depends on (injects) such a provider.\n\n```typescript\n{\n  provide: 'ASYNC_CONNECTION',\n  useFactory: async () => {\n    const connection = await createConnection(options);\n    return connection;\n  },\n}\n```\n\n> info **Hint** Learn more about custom provider syntax [here](/fundamentals/custom-providers).\n\n#### Injection\n\nAsynchronous providers are injected to other components by their tokens, like any other provider. In the example above, you would use the construct `@Inject('ASYNC_CONNECTION')`.\n\n#### Example\n\n[The TypeORM recipe](/recipes/sql-typeorm) has a more substantial example of an asynchronous provider.\n"
  },
  {
    "path": "content/fundamentals/circular-dependency.md",
    "content": "### Circular dependency\n\nA circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers.\n\nWhile circular dependencies should be avoided where possible, you can't always do so. In such cases, Nest enables resolving circular dependencies between providers in two ways. In this chapter, we describe using **forward referencing** as one technique, and using the **ModuleRef** class to retrieve a provider instance from the DI container as another.\n\nWe also describe resolving circular dependencies between modules.\n\n> warning **Warning** A circular dependency might also be caused when using \"barrel files\"/index.ts files to group imports. Barrel files should be omitted when it comes to module/provider classes. For example, barrel files should not be used when importing files within the same directory as the barrel file, i.e. `cats/cats.controller` should not import `cats` to import the `cats/cats.service` file. For more details please also see [this github issue](https://github.com/nestjs/nest/issues/1181#issuecomment-430197191). \n\n#### Forward reference\n\nA **forward reference** allows Nest to reference classes which aren't yet defined using the `forwardRef()` utility function. For example, if `CatsService` and `CommonService` depend on each other, both sides of the relationship can use `@Inject()` and the `forwardRef()` utility to resolve the circular dependency. Otherwise Nest won't instantiate them because all of the essential metadata won't be available. Here's an example:\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService {\n  constructor(\n    @Inject(forwardRef(() => CommonService))\n    private commonService: CommonService,\n  ) {}\n}\n@@switch\n@Injectable()\n@Dependencies(forwardRef(() => CommonService))\nexport class CatsService {\n  constructor(commonService) {\n    this.commonService = commonService;\n  }\n}\n```\n\n> info **Hint** The `forwardRef()` function is imported from the `@nestjs/common` package.\n\nThat covers one side of the relationship. Now let's do the same with `CommonService`:\n\n```typescript\n@@filename(common.service)\n@Injectable()\nexport class CommonService {\n  constructor(\n    @Inject(forwardRef(() => CatsService))\n    private catsService: CatsService,\n  ) {}\n}\n@@switch\n@Injectable()\n@Dependencies(forwardRef(() => CatsService))\nexport class CommonService {\n  constructor(catsService) {\n    this.catsService = catsService;\n  }\n}\n```\n\n> warning **Warning** The order of instantiation is indeterminate. Make sure your code does not depend on which constructor is called first.\n\n#### ModuleRef class alternative\n\nAn alternative to using `forwardRef()` is to refactor your code and use the `ModuleRef` class to retrieve a provider on one side of the (otherwise) circular relationship. Learn more about the `ModuleRef` utility class [here](/fundamentals/module-ref).\n\n#### Module forward reference\n\nIn order to resolve circular dependencies between modules, use the same `forwardRef()` utility function on both sides of the modules association. For example:\n\n```typescript\n@@filename(common.module)\n@Module({\n  imports: [forwardRef(() => CatsModule)],\n})\nexport class CommonModule {}\n```\n"
  },
  {
    "path": "content/fundamentals/dependency-injection.md",
    "content": "### Custom providers\n\nIn earlier chapters, we touched on various aspects of **Dependency Injection (DI)** and how it is used in Nest. One example of this is the [constructor based](https://docs.nestjs.com/providers#dependency-injection) dependency injection used to inject instances (often service providers) into classes. You won't be surprised to learn that Dependency Injection is built into the Nest core in a fundamental way. So far, we've only explored one main pattern. As your application grows more complex, you may need to take advantage of the full features of the DI system, so let's explore them in more detail.\n\n#### DI fundamentals\n\nDependency injection is an [inversion of control (IoC)](https://en.wikipedia.org/wiki/Inversion_of_control) technique wherein you delegate instantiation of dependencies to the IoC container (in our case, the NestJS runtime system), instead of doing it in your own code imperatively. Let's examine what's happening in this example from the [Providers chapter](https://docs.nestjs.com/providers).\n\nFirst, we define a provider. The `@Injectable()` decorator marks the `CatsService` class as a provider.\n\n```typescript\n@@filename(cats.service)\nimport { Injectable } from '@nestjs/common';\nimport { Cat } from './interfaces/cat.interface';\n\n@Injectable()\nexport class CatsService {\n  private readonly cats: Cat[] = [];\n\n  findAll(): Cat[] {\n    return this.cats;\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class CatsService {\n  constructor() {\n    this.cats = [];\n  }\n\n  findAll() {\n    return this.cats;\n  }\n}\n```\n\nThen we request that Nest inject the provider into our controller class:\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get } from '@nestjs/common';\nimport { CatsService } from './cats.service';\nimport { Cat } from './interfaces/cat.interface';\n\n@Controller('cats')\nexport class CatsController {\n  constructor(private catsService: CatsService) {}\n\n  @Get()\n  async findAll(): Promise<Cat[]> {\n    return this.catsService.findAll();\n  }\n}\n@@switch\nimport { Controller, Get, Bind, Dependencies } from '@nestjs/common';\nimport { CatsService } from './cats.service';\n\n@Controller('cats')\n@Dependencies(CatsService)\nexport class CatsController {\n  constructor(catsService) {\n    this.catsService = catsService;\n  }\n\n  @Get()\n  async findAll() {\n    return this.catsService.findAll();\n  }\n}\n```\n\nFinally, we register the provider with the Nest IoC container:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats/cats.controller';\nimport { CatsService } from './cats/cats.service';\n\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n})\nexport class AppModule {}\n```\n\nWhat exactly is happening under the covers to make this work? There are three key steps in the process:\n\n1. In `cats.service.ts`, the `@Injectable()` decorator declares the `CatsService` class as a class that can be managed by the Nest IoC container.\n2. In `cats.controller.ts`, `CatsController` declares a dependency on the `CatsService` token with constructor injection:\n\n```typescript\n  constructor(private catsService: CatsService)\n```\n\n3. In `app.module.ts`, we associate the token `CatsService` with the class `CatsService` from the `cats.service.ts` file. We'll <a href=\"/fundamentals/custom-providers#standard-providers\">see below</a> exactly how this association (also called _registration_) occurs.\n\nWhen the Nest IoC container instantiates a `CatsController`, it first looks for any dependencies\\*. When it finds the `CatsService` dependency, it performs a lookup on the `CatsService` token, which returns the `CatsService` class, per the registration step (#3 above). Assuming `SINGLETON` scope (the default behavior), Nest will then either create an instance of `CatsService`, cache it, and return it, or if one is already cached, return the existing instance.\n\n\\*This explanation is a bit simplified to illustrate the point. One important area we glossed over is that the process of analyzing the code for dependencies is very sophisticated, and happens during application bootstrapping. One key feature is that dependency analysis (or \"creating the dependency graph\"), is **transitive**. In the above example, if the `CatsService` itself had dependencies, those too would be resolved. The dependency graph ensures that dependencies are resolved in the correct order - essentially \"bottom up\". This mechanism relieves the developer from having to manage such complex dependency graphs.\n\n<app-banner-courses></app-banner-courses>\n\n#### Standard providers\n\nLet's take a closer look at the `@Module()` decorator. In `app.module`, we declare:\n\n```typescript\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n})\n```\n\nThe `providers` property takes an array of `providers`. So far, we've supplied those providers via a list of class names. In fact, the syntax `providers: [CatsService]` is short-hand for the more complete syntax:\n\n```typescript\nproviders: [\n  {\n    provide: CatsService,\n    useClass: CatsService,\n  },\n];\n```\n\nNow that we see this explicit construction, we can understand the registration process. Here, we are clearly associating the token `CatsService` with the class `CatsService`. The short-hand notation is merely a convenience to simplify the most common use-case, where the token is used to request an instance of a class by the same name.\n\n#### Custom providers\n\nWhat happens when your requirements go beyond those offered by _Standard providers_? Here are a few examples:\n\n- You want to create a custom instance instead of having Nest instantiate (or return a cached instance of) a class\n- You want to re-use an existing class in a second dependency\n- You want to override a class with a mock version for testing\n\nNest allows you to define Custom providers to handle these cases. It provides several ways to define custom providers. Let's walk through them.\n\n> info **Hint** If you are having problems with dependency resolution you can set the `NEST_DEBUG` environment variable and get extra dependency resolution logs during startup.\n\n#### Value providers: `useValue`\n\nThe `useValue` syntax is useful for injecting a constant value, putting an external library into the Nest container, or replacing a real implementation with a mock object. Let's say you'd like to force Nest to use a mock `CatsService` for testing purposes.\n\n```typescript\nimport { CatsService } from './cats.service';\n\nconst mockCatsService = {\n  /* mock implementation\n  ...\n  */\n};\n\n@Module({\n  imports: [CatsModule],\n  providers: [\n    {\n      provide: CatsService,\n      useValue: mockCatsService,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\nIn this example, the `CatsService` token will resolve to the `mockCatsService` mock object. `useValue` requires a value - in this case a literal object that has the same interface as the `CatsService` class it is replacing. Because of TypeScript's [structural typing](https://www.typescriptlang.org/docs/handbook/type-compatibility.html), you can use any object that has a compatible interface, including a literal object or a class instance instantiated with `new`.\n\n#### Non-class-based provider tokens\n\nSo far, we've used class names as our provider tokens (the value of the `provide` property in a provider listed in the `providers` array). This is matched by the standard pattern used with [constructor based injection](https://docs.nestjs.com/providers#dependency-injection), where the token is also a class name. (Refer back to <a href=\"/fundamentals/custom-providers#di-fundamentals\">DI Fundamentals</a> for a refresher on tokens if this concept isn't entirely clear). Sometimes, we may want the flexibility to use strings or symbols as the DI token. For example:\n\n```typescript\nimport { connection } from './connection';\n\n@Module({\n  providers: [\n    {\n      provide: 'CONNECTION',\n      useValue: connection,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\nIn this example, we are associating a string-valued token (`'CONNECTION'`) with a pre-existing `connection` object we've imported from an external file.\n\n> warning **Notice** In addition to using strings as token values, you can also use JavaScript [symbols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) or TypeScript [enums](https://www.typescriptlang.org/docs/handbook/enums.html).\n\nWe've previously seen how to inject a provider using the standard [constructor based injection](https://docs.nestjs.com/providers#dependency-injection) pattern. This pattern **requires** that the dependency be declared with a class name. The `'CONNECTION'` custom provider uses a string-valued token. Let's see how to inject such a provider. To do so, we use the `@Inject()` decorator. This decorator takes a single argument - the token.\n\n```typescript\n@@filename()\n@Injectable()\nexport class CatsRepository {\n  constructor(@Inject('CONNECTION') connection: Connection) {}\n}\n@@switch\n@Injectable()\n@Dependencies('CONNECTION')\nexport class CatsRepository {\n  constructor(connection) {}\n}\n```\n\n> info **Hint** The `@Inject()` decorator is imported from `@nestjs/common` package.\n\nWhile we directly use the string `'CONNECTION'` in the above examples for illustration purposes, for clean code organization, it's best practice to define tokens in a separate file, such as `constants.ts`. Treat them much as you would symbols or enums that are defined in their own file and imported where needed.\n\n#### Class providers: `useClass`\n\nThe `useClass` syntax allows you to dynamically determine a class that a token should resolve to. For example, suppose we have an abstract (or default) `ConfigService` class. Depending on the current environment, we want Nest to provide a different implementation of the configuration service. The following code implements such a strategy.\n\n```typescript\nconst configServiceProvider = {\n  provide: ConfigService,\n  useClass:\n    process.env.NODE_ENV === 'development'\n      ? DevelopmentConfigService\n      : ProductionConfigService,\n};\n\n@Module({\n  providers: [configServiceProvider],\n})\nexport class AppModule {}\n```\n\nLet's look at a couple of details in this code sample. You'll notice that we define `configServiceProvider` with a literal object first, then pass it in the module decorator's `providers` property. This is just a bit of code organization, but is functionally equivalent to the examples we've used thus far in this chapter.\n\nAlso, we have used the `ConfigService` class name as our token. For any class that depends on `ConfigService`, Nest will inject an instance of the provided class (`DevelopmentConfigService` or `ProductionConfigService`) overriding any default implementation that may have been declared elsewhere (e.g., a `ConfigService` declared with an `@Injectable()` decorator).\n\n#### Factory providers: `useFactory`\n\nThe `useFactory` syntax allows for creating providers **dynamically**. The actual provider will be supplied by the value returned from a factory function. The factory function can be as simple or complex as needed. A simple factory may not depend on any other providers. A more complex factory can itself inject other providers it needs to compute its result. For the latter case, the factory provider syntax has a pair of related mechanisms:\n\n1. The factory function can accept (optional) arguments.\n2. The (optional) `inject` property accepts an array of providers that Nest will resolve and pass as arguments to the factory function during the instantiation process. The two lists should be correlated: Nest will pass instances from the `inject` list as arguments to the factory function in the same order.\n\nThe example below demonstrates this.\n\n```typescript\n@@filename()\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  useFactory: (optionsProvider: OptionsProvider) => {\n    const options = optionsProvider.get();\n    return new DatabaseConnection(options);\n  },\n  inject: [OptionsProvider],\n};\n\n@Module({\n  providers: [connectionFactory],\n})\nexport class AppModule {}\n@@switch\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  useFactory: (optionsProvider) => {\n    const options = optionsProvider.get();\n    return new DatabaseConnection(options);\n  },\n  inject: [OptionsProvider],\n};\n\n@Module({\n  providers: [connectionFactory],\n})\nexport class AppModule {}\n```\n\n#### Alias providers: `useExisting`\n\nThe `useExisting` syntax allows you to create aliases for existing providers. This creates two ways to access the same provider. In the example below, the (string-based) token `'AliasedLoggerService'` is an alias for the (class-based) token `LoggerService`. Assume we have two different dependencies, one for `'AliasedLoggerService'` and one for `LoggerService`. If both dependencies are specified with `SINGLETON` scope, they'll both resolve to the same instance.\n\n```typescript\n@Injectable()\nclass LoggerService {\n  /* implementation details */\n}\n\nconst loggerAliasProvider = {\n  provide: 'AliasedLoggerService',\n  useExisting: LoggerService,\n};\n\n@Module({\n  providers: [LoggerService, loggerAliasProvider],\n})\nexport class AppModule {}\n```\n\n#### Non-service based providers\n\nWhile providers often supply services, they are not limited to that usage. A provider can supply **any** value. For example, a provider may supply an array of configuration objects based on the current environment, as shown below:\n\n```typescript\nconst configFactory = {\n  provide: 'CONFIG',\n  useFactory: () => {\n    return process.env.NODE_ENV === 'development' ? devConfig : prodConfig;\n  },\n};\n\n@Module({\n  providers: [configFactory],\n})\nexport class AppModule {}\n```\n\n#### Export custom provider\n\nLike any provider, a custom provider is scoped to its declaring module. To make it visible to other modules, it must be exported. To export a custom provider, we can either use its token or the full provider object.\n\nThe following example shows exporting using the token:\n\n```typescript\n@@filename()\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  useFactory: (optionsProvider: OptionsProvider) => {\n    const options = optionsProvider.get();\n    return new DatabaseConnection(options);\n  },\n  inject: [OptionsProvider],\n};\n\n@Module({\n  providers: [connectionFactory],\n  exports: ['CONNECTION'],\n})\nexport class AppModule {}\n@@switch\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  useFactory: (optionsProvider) => {\n    const options = optionsProvider.get();\n    return new DatabaseConnection(options);\n  },\n  inject: [OptionsProvider],\n};\n\n@Module({\n  providers: [connectionFactory],\n  exports: ['CONNECTION'],\n})\nexport class AppModule {}\n```\n\nAlternatively, export with the full provider object:\n\n```typescript\n@@filename()\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  useFactory: (optionsProvider: OptionsProvider) => {\n    const options = optionsProvider.get();\n    return new DatabaseConnection(options);\n  },\n  inject: [OptionsProvider],\n};\n\n@Module({\n  providers: [connectionFactory],\n  exports: [connectionFactory],\n})\nexport class AppModule {}\n@@switch\nconst connectionFactory = {\n  provide: 'CONNECTION',\n  useFactory: (optionsProvider) => {\n    const options = optionsProvider.get();\n    return new DatabaseConnection(options);\n  },\n  inject: [OptionsProvider],\n};\n\n@Module({\n  providers: [connectionFactory],\n  exports: [connectionFactory],\n})\nexport class AppModule {}\n```\n"
  },
  {
    "path": "content/fundamentals/dynamic-modules.md",
    "content": "### 동적 모듈\n\n[모듈 챕터](/modules)에서 모듈에 대한 기본적인 내용을 다루면서 [동적 모듈](https://docs.nestjs.com/modules#dynamic-modules)에 대해 간단히 소개하기도 했습니다. 이번 챕터에서는 동적 모듈에 대해 더 자세히 다룹니다. 이번 챕터를 마치고 나면 그것들이 무엇이며 언제 어떻게 사용하는지 제대로 파악할 수 있을 것입니다.\n\n#### 소개\n\n본 문서의 **개요** 섹션에 있는 대부분의 예제 코드에서는 일반 모듈이나 정적 모듈을 사용합니다. 모듈은 [프로바이더](/providers)와 [컨트롤러](/controllers)같이 전체 어플리케이션의 모듈적인 부분이 되어 함께 어울리는 컴포넌트들의 그룹을 나타냅니다. 모듈은 이러한 컴포넌트들에게 실행 컨텍스트나 스코프 등을 주입해 줍니다. 예를 들어, 어떤 모듈 안에 정의된 프로바이더를 따로 내보내지 않아도 해당 모듈의 다른 다른 멤버들이 그 프로바이더를 찾을 수 있습니다. 프로바이더가 모듈 바깥에 노출될 필요가 있다면, 우선 해당 프로바이더의 호스트 모듈로부터 내보낸 다음, 사용하고자 하는 모듈에 import 되어야 합니다.\n\n익숙한 예시를 통해 다시 들여다 봅시다.\n\n우선, `UsersModule`에서 `UsersService`를 공급받고 내보냅니다. `UsersModule`은 `UsersService`의 **호스트** 모듈입니다.\n\n```typescript\nimport { Module } from \"@nestjs/common\";\nimport { UsersService } from \"./users.service\";\n\n@Module({\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\n그 다음, `UsersModule`을 import하는 `AuthModule`을 정의하고, `UsersModule`에서 내보낸 프로바이더를 `AuthModule` 내부에서 사용할 수 있게 만듭니다:\n\n```typescript\nimport { Module } from \"@nestjs/common\";\nimport { AuthService } from \"./auth.service\";\nimport { UsersModule } from \"../users/users.module\";\n\n@Module({\n  imports: [UsersModule],\n  providers: [AuthService],\n  exports: [AuthService],\n})\nexport class AuthModule {}\n```\n\n이렇게 작성하면 `AuthModule`을 호스트로 두는 가령 `AuthService`같은 곳에 `UsersService`를 주입할 수 있게 됩니다:\n\n```typescript\nimport { Injectable } from \"@nestjs/common\";\nimport { UsersService } from \"../users/users.service\";\n\n@Injectable()\nexport class AuthService {\n  constructor(private usersService: UsersService) {}\n  /*\n    Implementation that makes use of this.usersService\n  */\n}\n```\n\n이와 같은 일을 **정적** 모듈 바인딩이라고 합니다. Nest가 엮어야 할 모듈에 대한 정보는 호스트 모듈과 그 모듈을 사용하는 모듈에 이미 정의되어 있습니다. 이러한 작업이 내부적으로 어떻게 이루어지는지 살펴봅시다. Nest는 아래의 과정들을 통해 `AuthModule` 내부에서 `UsersService`를 사용할 수 있게 만듭니다:\n\n1. `UsersModule`을 인스턴스화 하는데, 이 때 이 모듈이 사용하는 다른 모듈들을 가져오면서 의존성을 해소합니다. ([사용자 정의 프로바이더](/fundamentals/custom-providers)를 참조해 주세요)\n2. `AuthModule`을 인스턴스화 하면서, `UsersModule`에서 내보낸 프로바이더들을 `AuthModule` 속 컴포넌트들이 사용할 수 있게 만듭니다. (마치 그 프로바이더들이 `AuthModule` 안에 선언되듯이)\n3. `AuthService`에 `UsersService` 인스턴스를 주입합니다.\n\n#### 동적 모듈 사용 사례\n\n정적 모듈 바인딩을 할 때, 사용하는 모듈 쪽에서는 호스트 모듈에서 제공하는 프로바이더를 설정할 수 있도록 영향을 미칠 기회가 없습니다. 그게 왜 문제가 될까요? 다양한 유스케이스에서 다르게 동작할 필요가 있도록 범용적으로 사용하는 모듈이 있다고 가정해 봅시다. 이것은 많은 시스템에서 \"플러그인\" 이라 칭하는 컨셉과 유사할 테고, 사용자가 이를 사용하기 전에 몇가지 설정을 해야 합니다.\n\nNest에서 이와 관련한 좋은 예시가 바로 **환경설정 모듈**입니다. 많은 애플리케이션들이 세부설정을 외부로 빼기 위해 환경설정 모듈을 유용하게 사용합니다. 이것은 다양한 배포환경에서 동적으로 애플리케이션 설정을 쉽게 바꿀 수 있게 해줍니다: 예를 들면, 개발자가 사용하는 개발용 데이터베이스, 스테이징과 테스팅 환경에서 쓰이는 스테이징 데이터베이스 등이 있습니다. 설정값들의 관리를 환경설정 모듈에게 위임함으로써, 애플리케이션의 소스코드를 설정값으로부터 독립적으로 유지할 수 있습니다.\n\n해야 할 일은, 환경설정 모듈 자체는 \"플러그인과\"처럼 범용적이기 때문에 이를 사용하는 모듈에서 커스터마이징 하는 것입니다. 이곳이 바로 *동적 모듈*이 동작하는 곳입니다. 동적 모듈의 기능으로 환경설정 모듈을 **동적**으로 만들었기 때문에 사용하는 모듈에서는 환경설정 모듈을 import할 때 API를 호출할 수 있게 되며, 해당 API를 통해 환경설정 모듈이 어떻게 커스터마이징될지를 제어합니다.\n\n달리 말하면, 동적 모듈은 어떤 모듈을 다른 여러 모듈에서 import한다거나 해당 모듈을 import할 때 그 모듈의 프로퍼티와 동작을 커스터마이징할 수 있도록 API를 제공합니다. 이는 이제껏 보았던 정적 바인딩과 아주 대조적입니다.\n\n<app-banner-shop></app-banner-shop>\n\n#### 설정 모듈 예제\n\n이번 섹션에서는 [환경설정 챕터](https://docs.nestjs.com/techniques/configuration#service)의 예제 코드를 기반으로 설명하겠습니다. 이번 챕터를 통해 완성된 코드는 [이 예제](https://github.com/nestjs/nest/tree/master/sample/25-dynamic-modules)에서 동작을 확인할 수 있습니다.\n\n우리의 요구사항은 `ConfigModule`을 만들고 이를 커스터마이징 하기 위해 `options` 객체를 사용하는 것입니다. 제공하려는 기능에 대해 말씀 드리겠습니다. 기본 예제에서는 `.env`파일의 위치가 프로젝트 폴더 최상단으로 하드코딩 되어 있습니다. 이것을 `.env` 파일들이 어느 폴더에 있든 관리할 수 있게끔 설정 가능하게 만든다고 가정해 봅시다. 예를 들어, 프로젝트 최상단의 `config`폴더(`src`폴더의 형제 위치) 안에 다양한 `.env` 파일들을 저장해 두었다고 한다면, 다른 프로젝트들에서는 `ConfigModule`을 사용할 때 다른 폴더를 지정하고 싶어집니다.\n\n동적 모듈은 해당 모듈을 import할 때 인자를 전달할 수 있게 해주어 우리가 그 동작을 변경할 수 있게 됩니다. 이것이 어떻게 동작하는지 살펴봅시다. 사용하는 모듈의 관점에서 어떻게 보이는지부터 시작해서 거꾸로 파악해 나가면 더 이해하기 쉽습니다. 우선, `ConfigModule`을 _정적으로_ import하던 예제(모듈을 import할 때 그 모듈의 동작에 영향을 줄 수 없던 접근방식이었습니다)를 다시금 빠르게 살펴보고 지나갑시다. `@Module()` 데코레이터의 `imports` 배열을 집중적으로 봐주세요:\n\n```typescript\nimport { Module } from \"@nestjs/common\";\nimport { AppController } from \"./app.controller\";\nimport { AppService } from \"./app.service\";\nimport { ConfigModule } from \"./config/config.module\";\n\n@Module({\n  imports: [ConfigModule],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n우리가 설정 객체를 전달할 *동적 모듈*을 import하는 모습은 어떨지 생각해 봅시다. 위와 아래 두 예제의 `import` 배열에 어떤 차이가 있는지 비교해 보세요:\n\n```typescript\nimport { Module } from \"@nestjs/common\";\nimport { AppController } from \"./app.controller\";\nimport { AppService } from \"./app.service\";\nimport { ConfigModule } from \"./config/config.module\";\n\n@Module({\n  imports: [ConfigModule.register({ folder: \"./config\" })],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n위의 동적 모듈 예제에 무슨 일이 일어나는지 봅시다. 어떤 부분이 달라졌나요?\n\n1. `ConfigModule`은 평범한 클래스이므로, `register()`이라는 **정적 메서드**를 가진다고 짐작할 수 있습니다. 이 메서드는 클래스의 **인스턴스**가 아니라 `ConfigModule` 클래스 자체에서 불러오기 때문에 정적입니다. 곧 구현할 이 메서드는 임의의 이름을 가질 수 있지만, 관례적으로 `forRoot()`나 `register()`라고 부릅니다.\n2. `register()` 메서드는 우리가 만들 것이기 때문에 원하는 인자를 넣을 수 있습니다. 이번에는, 일반적인 경우에 적합한 프로퍼티들을 가지는 `options` 객체를 받도록 하겠습니다.\n3. `register()` 메서드는 `module`같은 무언가를 반환해야 한다고 짐작할 수 있습니다. 왜냐면 그 반환 값이 `imports` 리스트에 들어가고 있고, 지금까지 이 리스트에 모듈들이 들어가는 것을 보았기 때문입니다.\n\n사실, `register()`메서드는 `DynamicModule`을 반환합니다. 동적 모듈은 런타임에서 만들어진다는 것 말고는 아무것도 없습니다. 정적 모듈이 가지는 모든 프로퍼티를 동일하게 가지고, 거기에 `module`이라는 프로퍼티만 추가로 가집니다. 정적 모듈을 선언할 때 데코레이터에 전달되는 모듈 옵션을 다시금 빠르게 살펴봅시다:\n\n```typescript\n@Module({\n  imports: [DogsModule],\n  controllers: [CatsController],\n  providers: [CatsService],\n  exports: [CatsService]\n})\n```\n\n동적 모듈은 인터페이스와 동일한 객체에 `module`이라는 프로퍼티를 추가하여 반환해야 합니다. `module` 프로퍼티는 모듈의 이름을 제공하며 아래 예시에서 볼 수 있듯 모듈의 클래스 이름과 같아야 합니다.\n\n> info **힌트** 동적 모듈에서는 `module`프로퍼티를 **제외**하고 모듈 옵션 객체의 모든 프로퍼티를 선택적으로 가집니다.\n\n`register()`라는 정적 메서드는 무엇일까요? 우리는 이제 이 메서드가 하는 일이 `DynamicModule` 인터페이스를 가지는 객체를 반환하는 것이라는 걸 압니다. 이 메서드를 호출함으로써, `imports` 리스트에 정적으로 모듈 클래스 이름을 적어주었던 것과 유사한 방법으로 모듈을 효과적으로 제공합니다. 달리 말하면, 동적 모듈의 API는 단순하게 어떤 모듈을 반환하되, `@Module` 데코레이터의 프로퍼티들을 고정시키지 않고 프로그래밍적으로 명시합니다.\n\n그림을 완성하려면 몇 가지 세부사항들이 더 필요합니다:\n\n1. 이제는 `@Module()` 데코레이터의 `imports` 프로퍼티에는 모듈 클래스 이름(예: `imports: [UsersModule]`)뿐만 아니라 동적 모듈을 반환하는 함수(예: `imports: [ConfigModule.register(...)]`)도 사용할 수 있다고 말할 수 있습니다.\n2. 동적 모듈은 스스로 다른 모듈들을 import할 수 있습니다. 이번 예제에서는 그러지 않았지만 만약 동적 모듈이 다른 모듈의 프로바이더에 의존한다면, `imports` 프로퍼티를 사용하여 그 모듈들을 import하면 됩니다. 다시 말씀 드리지만, 정적 모듈에서 `@Module()` 데코레이터를 사용하여 메타데이터를 선언하던 방식과 완전히 동일합니다.\n\n이러한 이해를 바탕으로, 이제 우리의 동적 모듈인 `ConfigModule`의 선언이 어떻게 생겼는지 확인할 수 있습니다. 다음과 같이 시도해 봅시다.\n\n```typescript\nimport { DynamicModule, Module } from \"@nestjs/common\";\nimport { ConfigService } from \"./config.service\";\n\n@Module({})\nexport class ConfigModule {\n  static register(): DynamicModule {\n    return {\n      module: ConfigModule,\n      providers: [ConfigService],\n      exports: [ConfigService],\n    };\n  }\n}\n```\n\n이제는 지금까지 다룬 조각들이 서로 어떻게 연결되는지 명확히 이해할 차례입니다. `ConfigModule.register(...)`을 호출하면, 지금까지 `@Module()` 데코레이터를 통해 메타데이터를 제공했던 것과 본질적으로 동일한 프로퍼티를 가지는 `DynamicModule` 객체를 반환합니다.\n\n> info **힌트** `DynamicModule`는 `@nestjs/common`에서 import합니다.\n\n우리의 동적 모듈은 아직까지는 그다지 흥미롭지 않은데, 이는 우리가 하고 싶다고 말했던 그 **설정** 기능을 아직 다루지 않았기 때문입니다. 이는 다음 섹션에서 다루도록 하겠습니다.\n\n#### 모듈 설정\n\n위에서 추측한 대로, `ConfigModule`의 동작을 커스터마이징하는 분명한 방법은 정적 메서드인 `register()`에 `options` 객체를 넘기는 것입니다. 사용하는 모듈의 `imports` 프로퍼티를 다시 한 번 봅시다:\n\n```typescript\nimport { Module } from \"@nestjs/common\";\nimport { AppController } from \"./app.controller\";\nimport { AppService } from \"./app.service\";\nimport { ConfigModule } from \"./config/config.module\";\n\n@Module({\n  imports: [ConfigModule.register({ folder: \"./config\" })],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\n동적 모듈에 `options` 객체를 넘기는 것이 좋은 조작입니다. 이후에 그 `options` 객체를 `ConfigModule`에서 어떻게 사용할 수 있을까요? 잠시 스스로 생각해 봅시다. `ConfigModule`은 기본적으로 다른 프로바이더에 주입할 수 있는 서비스(`ConfigService`)를 포함하고 내보내는 호스트 모듈입니다. 실제로 `options` 객체를 읽어서 동작을 커스터마이징 해야 하는 건 `ConfigService`입니다. 이러한 가정을 바탕으로, `options` 객체의 프로퍼티들을 기반으로 서비스의 동작을 커스터마이징 하기 위해 서비스를 약간 수정할 수 있습니다. (**참고**: 실제로 어떻게 전달하는지는 아직 다루지 않았기 때문에, 당분간은 `options`를 하드코딩하겠습니다. 이는 잠시 후에 해결하겠습니다.)\n\n```typescript\nimport { Injectable } from \"@nestjs/common\";\nimport * as dotenv from \"dotenv\";\nimport * as fs from \"fs\";\nimport { EnvConfig } from \"./interfaces\";\n\n@Injectable()\nexport class ConfigService {\n  private readonly envConfig: EnvConfig;\n\n  constructor() {\n    const options = { folder: \"./config\" };\n\n    const filePath = `${process.env.NODE_ENV || \"development\"}.env`;\n    const envFile = path.resolve(__dirname, \"../../\", options.folder, filePath);\n    this.envConfig = dotenv.parse(fs.readFileSync(envFile));\n  }\n\n  get(key: string): string {\n    return this.envConfig[key];\n  }\n}\n```\n\n이제 `ConfigService`는 `options`에 명시한 폴더에서 `.env`파일을 찾습니다.\n\n이제 남은 작업은 어떻게든 `options` 객체를 `register()`를 통해 `ConfigService`에 주입하는 것입니다. 이번에도 당연히 *의존성 주입*을 사용합니다. 이것이 중요한 포인트이니 꼭 숙지하시길 바랍니다. `ConfigModule`은 `ConfigService`를 제공합니다. `ConfigService`는 `options` 객체에 의존하며 이는 오직 런타임 환경에서만 제공됩니다. 따라서 런타임에서는, 우선 `options` 객체를 Nest의 IoC 컨테이너에 바인딩하고, Nest가 이를 `ConfigService`에 주입해야 합니다. **사용자 정의 프로바이더** 챕터에서 말씀 드렸듯 프로바이더는 [어떤 값이든 포함할 수 있다](https://docs.nestjs.com/fundamentals/custom-providers#non-service-based-providers)는 점을 기억하시길 바라며, 이는 단순히 서비스만 해당되는 내용이 아닙니다. 따라서 우리는 `options` 객체를 쉽게 다루기 위해 의존성 주입을 사용하기만 하면 됩니다.\n\noptions 객체를 IoC 컨테이너에 바인딩하는 문제부터 해결해 봅시다. 이 작업은 우리의 정적 메서드인 `register()`에서 이루어집니다. 우리는 지금 모듈을 동적으로 구성하고 있고, 모듈의 프로퍼티 중 하나는 프로바이더 리스트라는 점을 기억해 보세요. 그렇다면 우리가 해야 할 일은 우리의 options 객체를 프로바이더라고 정의하는 것입니다. 이렇게 하면 다음 단계에서 활용할 `ConfigModule`에 options 객체를 주입할 수 있게 됩니다. 아래 코드에서 `providers` 배열을 집중적으로 살펴보세요:\n\n```typescript\nimport { DynamicModule, Module } from \"@nestjs/common\";\nimport { ConfigService } from \"./config.service\";\n\n@Module({})\nexport class ConfigModule {\n  static register(options): DynamicModule {\n    return {\n      module: ConfigModule,\n      providers: [\n        {\n          provide: \"CONFIG_OPTIONS\",\n          useValue: options,\n        },\n        ConfigService,\n      ],\n      exports: [ConfigService],\n    };\n  }\n}\n```\n\n이제 `ConfigService`에 `'CONFIG_OPIONS'` 프로바이더를 주입하면 완성입니다. 클래스가 아닌 토큰을 사용하는 프로바이더를 정의하려면 `@Inject()` 데코레이터를 사용해야 하며, 이에 대한 내용은 [여기에서 설명하고 있습니다](https://docs.nestjs.com/fundamentals/custom-providers#non-class-based-provider-tokens).\n\n```typescript\nimport * as dotenv from \"dotenv\";\nimport * as fs from \"fs\";\nimport { Injectable, Inject } from \"@nestjs/common\";\nimport { EnvConfig } from \"./interfaces\";\n\n@Injectable()\nexport class ConfigService {\n  private readonly envConfig: EnvConfig;\n\n  constructor(@Inject(\"CONFIG_OPTIONS\") private options) {\n    const filePath = `${process.env.NODE_ENV || \"development\"}.env`;\n    const envFile = path.resolve(__dirname, \"../../\", options.folder, filePath);\n    this.envConfig = dotenv.parse(fs.readFileSync(envFile));\n  }\n\n  get(key: string): string {\n    return this.envConfig[key];\n  }\n}\n```\n\n마지막으로 기억해야 할 것이 있습니다. 위에서는 단순하게 문자열 기반의 주입 토큰(`'CONFIG_OPTIONS'`)을 사용했지만, 이러한 토큰을 정의하는 가장 좋은 방법은 별도의 파일에 상수(또는 `Symbol`)로 정의해 두고 다른 파일에서 가져다 사용하는 것입니다. 아래는 그 예시입니다:\n\n```typescript\nexport const CONFIG_OPTIONS = \"CONFIG_OPTIONS\";\n```\n\n### 예제\n\n이번 챕터의 예제 코드 최종본은 [여기](https://github.com/nestjs/nest/tree/master/sample/25-dynamic-modules)에 있습니다.\n"
  },
  {
    "path": "content/fundamentals/execution-context.md",
    "content": "### 실행 컨텍스트\n\nNest는 여러 애플리케이션 컨텍스트들(예를 들면 Nest HTTP 서버 기반과 마이크로서비스, 웹소켓 컨텍스트)을 아울러서 작동하는 애플리케이션을 쉽게 작성할 수 있도록 몇 가지 유틸리티 클래스들을 제공합니다. 이 유틸리티들은 전반적인 컨트롤러, 메서드, 실행 컨텍스트를 아울러 동작하는 범용적인 [가드](/guards), [필터](/exception-filters), [인터셉터](/interceptors)를 만들 수 있도록 현재 실행 컨텍스트에 대한 정보를 제공합니다.\n\n이 챕터에서는 `ArgumentsHost`, `ExecutionContext` 두 클래스를 다룹니다.\n\n#### ArgumentsHost 클래스\n\n`ArgumentsHost` 클래스는 핸들러에 전달 된 인자들을 찾을 수 있는 메서드들을 제공하며, 인자들을 찾을 수 있는 적절한 컨텍스트(예를 들면 HTTP, RPC(마이크로서비스), 웹소켓)를 선택할 수 있게 해줍니다. 프레임워크는 `ArgumentsHost`의 인스턴스를 제공하며, 접근하려는 곳에서는 일반적으로 `host`라는 이름의 매개변수로 참조됩니다. 예를 들어, [예외 필터](https://docs.nestjs.com/exception-filters#arguments-host)의 `catch()`메서드는 `ArgumentsHost` 인스턴스와 함께 호출됩니다.\n\n`ArgumentsHost`는 단순하게 핸들러의 전체적인 인자에 대한 추상화 역할을 수행합니다. HTTP 서버 애플리케이션(`@nestjs/platform-express`를 사용할 때)을 예를 들면 `host`객체가 Express의 `[request, response, next]`배열을 캡슐화 합니다. 여기서 `request`는 요청 객체를, `response`는 응답 객체를, `next`는 애플리케이션의 요청-응답 사이클을 제어하는 함수입니다. 반면에 [GraphQL](/graphql/quick-start) 애플리케이션에서의 `host`객체는 `[root, args, context, info]` 배열을 포함합니다.\n\n#### 현재 애플리케이션 컨텍스트\n\n여러 애플리케이션 컨텍스트를 아울러 동작하는 일반적인 [가드](/guards), [필터](/exception-filters), [인터셉터](/interceptors)를 만들기 위해서는 현재 메서드가 동작하고 있는 애플리케이션 타입을 결정지어야 하며, 이는 `ArgumentsHost`의 `getType()`메서드를 통해 가능합니다:\n\n```typescript\nif (host.getType() === \"http\") {\n  // do something that is only important in the context of regular HTTP requests (REST)\n} else if (host.getType() === \"rpc\") {\n  // do something that is only important in the context of Microservice requests\n} else if (host.getType<GqlContextType>() === \"graphql\") {\n  // do something that is only important in the context of GraphQL requests\n}\n```\n\n> info **힌트** `GqlContextType`은 `@nestjs/graphql`패키지에서 import합니다.\n\n이처럼, 사용 가능한 애플리케이션 타입을 활용하여 보다 범용적인 컴포넌트를 작성할 수 있습니다.\n\n#### 호스트 핸들러 매개변수\n\n핸들러에 전달 된 인자를 찾기 위해 host 객체의 `getArgs()`메서드를 사용할 수 있습니다.\n\n```typescript\nconst [req, res, next] = host.getArgs();\n```\n\n`getArgByIndex()`메서드를 사용하여 특정 인자만 찾을 수 있습니다:\n\n```typescript\nconst request = host.getArgByIndex(0);\nconst response = host.getArgByIndex(1);\n```\n\n이 예제들에서 요청 객체 및 응답 객체를 인덱스를 통해 찾았는데, 일반적으로 이는 어플리케이션을 특정한 하나의 실행 컨텍스트에 국한시키는 것이므로 권장되지 않습니다. 대신에, `host`객체에는 적절한 어플리케이션 컨텍스트로 전환할 수 있는 유틸리티 메서드가 있으므로 이를 사용하여 더욱 안정되고 재사용가능한 코드를 작성할 수 있습니다. 아래는 컨텍스트를 전환하는 유틸리티 메서드들입니다.\n\n```typescript\n/**\n * Switch context to RPC.\n */\nswitchToRpc(): RpcArgumentsHost;\n/**\n * Switch context to HTTP.\n */\nswitchToHttp(): HttpArgumentsHost;\n/**\n * Switch context to WebSockets.\n */\nswitchToWs(): WsArgumentsHost;\n```\n\n직전의 예제를 `switchToHttp()`메서드를 사용하여 다시 작성해 봅시다. `host.switchToHttp()`는 HTTP 애플리케이션 컨텍스트에 걸맞는 `HttpArgugentsHost`객체를 반환합니다. `HttpArgugentsHost`객체는 우리가 원하는 객체를 받아올 수 있도록 두 가지 유용한 메서드를 제공합니다. 이 경우에는 Express 본연의 타입을 가진 객체를 반환받을 수 있도록 Express의 타입을 type assertion 해줍니다:\n\n```typescript\nconst ctx = host.switchToHttp();\nconst request = ctx.getRequest<Request>();\nconst response = ctx.getResponse<Response>();\n```\n\n`WsArgumentsHost`와 `RpcArgumentsHost`에도 각각 웹소켓 컨텍스트와 마이크로서비스 컨텍스트에서 적당한 객체를 반환하는 메서드들이 있습니다. 아래는 `WsArgMentsHost`의 메서드들입니다.\n\n```typescript\nexport interface WsArgumentsHost {\n  /**\n   * Returns the data object.\n   */\n  getData<T>(): T;\n  /**\n   * Returns the client object.\n   */\n  getClient<T>(): T;\n}\n```\n\n이어서 `RpcArgumentsHost`의 메서드들입니다:\n\n```typescript\nexport interface RpcArgumentsHost {\n  /**\n   * Returns the data object.\n   */\n  getData<T>(): T;\n\n  /**\n   * Returns the context object.\n   */\n  getContext<T>(): T;\n}\n```\n\n#### ExecutionContext 클래스\n\n`ExecutionContext`는 `ArgumentsHost`를 상속 받으며, 현재 실행 프로세스에 대한 추가적인 세부사항을 제공합니다. `ArgumentsHost`와 같이, Nest는 우리가 원하는 곳에 `ExecutionContext` 인스턴스를 제공하며, [가드](https://docs.nestjs.com/guards#execution-context)의 `canActive()`메서드나 [인터셉터](https://docs.nestjs.com/interceptors#execution-context)의 `intercept()`메서드가 그 예시입니다. 인스턴스는 아래 메서드들을 제공합니다:\n\n```typescript\nexport interface ExecutionContext extends ArgumentsHost {\n  /**\n   * Returns the type of the controller class which the current handler belongs to.\n   */\n  getClass<T>(): Type<T>;\n  /**\n   * Returns a reference to the handler (method) that will be invoked next in the\n   * request pipeline.\n   */\n  getHandler(): Function;\n}\n```\n\n`getHandler()`메서드는 실행 될 핸들러의 참조를 반환합니다. `getClass()`메서드는 그 핸들러가 속한 `Controller`클래스의 타입을 반환합니다. HTTP 컨텍스트에서의 예시로, 현재 처리되는 요청이 `POST`요청이고 `CatsController`의 `create()`메서드가 실행된다면 `getHandler()`는 `create()`메서드의 참조를 반환하고 `getClass()`는 `CatsController`의 인스턴스가 아닌 **타입**을 반환합니다.\n\n```typescript\nconst methodKey = ctx.getHandler().name; // \"create\"\nconst className = ctx.getClass().name; // \"CatsController\"\n```\n\n현재 클래스와 핸들러 메서드 둘의 참조 모두에 접근하는 기능은 굉장한 유연성을 제공합니다. 가장 중요한 건, 연관된 가드나 인터셉터에서 `@SetMetadata()`데코레이터를 통해 지정한 메타데이터에 접근할 수 있는 기회가 된다는 점입니다. 이 사례에 대해서는 아래에서 다루어 보겠습니다.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Reflection과 메타데이터\n\nNest는 **사용자 정의 메타데이터** 붙일 수 있는 기능을 제공하며 이는 라우트 핸들러에서 `@SetMetadata()`데코레이터를 통해 가능합니다. 이후 클래스 내에서 이 메타데이터에 접근하여 특정 결정을 내릴 수 있습니다.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@SetMetadata('roles', ['admin'])\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@SetMetadata('roles', ['admin'])\n@Bind(Body())\nasync create(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n> info **힌트** `@SetMetadata()` 데코레이터는 `@nestjs/common` 패키지에서 import합니다.\n\n위의 예제에서는 `roles`라는 메타데이터를 `create()`메서드에 붙였습니다(`roles`는 메타데이터 키이며 `['admin']`은 그 값입니다). 라우트에서 `@SetMetadata()`데코레이터를 직접 쓰는 것은 그다지 좋은 방법은 아닙니다. 대신에 아래와 같이 사용자 정의 데코레이터를 작성합니다:\n\n```typescript\n@@filename(roles.decorator)\nimport { SetMetadata } from '@nestjs/common';\n\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n@@switch\nimport { SetMetadata } from '@nestjs/common';\n\nexport const Roles = (...roles) => SetMetadata('roles', roles);\n```\n\n이러한 접근 방식이 훨씬 깔끔하고 가독성 있으며, 타입을 더욱 엄격하게 관리할 수 있습니다. 이제 `@Roles()`데코레이터를 `create()`메서드에 사용합니다.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@Roles('admin')\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@Roles('admin')\n@Bind(Body())\nasync create(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n라우트에서 role이라는 사용자 정의 메타데이터에 접근하기 위해서는 `Reflector` 헬퍼 클래스를 사용하면 됩니다. 이 클래스는 별도의 작업 없이 그저 `@nestjs/core`에서 가져다 사용하기만 하면 됩니다. `Reflector` 일반적인 방법으로 클래스에 주입시킬 수 있습니다:\n\n```typescript\n@@filename(roles.guard)\n@Injectable()\nexport class RolesGuard {\n  constructor(private reflector: Reflector) {}\n}\n@@switch\n@Injectable()\n@Dependencies(Reflector)\nexport class CatsService {\n  constructor(reflector) {\n    this.reflector = reflector;\n  }\n}\n```\n\n> info **힌트** `Reflector` 클래스는 `@nestjs/core` 패키지에서 import합니다.\n> Now, to read the handler metadata, use the `get()` method.\n\n```typescript\nconst roles = this.reflector.get<string[]>(\"roles\", context.getHandler());\n```\n\n메타데이터의 **키**와 메타데이터를 찾을 **컨텍스트** (데코레이터가 붙는 대상) 두 가지를 `Reflector#get` 메서드에 인자로 넘김으로써 쉽게 메타데이터에 접근할 수 있습니다. 이 예제에서는 위에서 작성한 `roles.decorator.ts`파일에서 `SetMetadata()`를 통해 만들었던 `'roles'`라는 **키**가 있습니다. 컨텍스트는 `context.getHandler()`를 호출하면 얻을 수 있고, 이 둘을 넘긴 결과로 현재 처리되는 라우트 핸들러의 메타데이터를 추출할 수 있습니다. `getHandler()`는 라우트 핸들러 함수의 **참조**를 반환한다는 점을 기억해야 합니다.\n\n또한, 컨트롤러 레벨에 메타데이터를 적용하여 해당 컨트롤러의 모든 라우트들에 메타데이터를 적용시킬 수 있습니다.\n\n```typescript\n@@filename(cats.controller)\n@Roles('admin')\n@Controller('cats')\nexport class CatsController {}\n@@switch\n@Roles('admin')\n@Controller('cats')\nexport class CatsController {}\n```\n\n이 경우에는, `context.getHandler()` 대신에 `context.getClass()`를 두 번째 인자로 넣어야 하며, 이는 메타데이터를 추출하기 위한 컨텍스트로 해당 컨트롤러 클래스를 제공하기 위함입니다.\n\n```typescript\n@@filename(roles.guard)\nconst roles = this.reflector.get<string[]>('roles', context.getClass());\n@@switch\nconst roles = this.reflector.get('roles', context.getClass());\n```\n\n하나의 메타데이터를 다양한 레벨에서 동시에 지정한다면, 다수의 컨텍스트로부터 메타데이터를 추출하고 합쳐야 할 것입니다. `Reflector` 클래스는 이를 위해 두 가지의 유틸리티 메서드를 제공합니다. 이 메서드들은 컨트롤러와 메서드 **두 곳 모두**에서 메타데이터를 추출하고, 각기 다른 방법으로 조합합니다.\n\n`'roles'`메타데이터를 두 가지 레벨에서 동시에 공급한다고 가정해 봅시다.\n\n```typescript\n@@filename(cats.controller)\n@Roles('user')\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  @Roles('admin')\n  async create(@Body() createCatDto: CreateCatDto) {\n    this.catsService.create(createCatDto);\n  }\n}\n@@switch\n@Roles('user')\n@Controller('cats')\nexport class CatsController {}\n  @Post()\n  @Roles('admin')\n  @Bind(Body())\n  async create(createCatDto) {\n    this.catsService.create(createCatDto);\n  }\n}\n```\n\n위 코드의 의도가 `'user'` role을 기본으로 취급하되 몇몇 메서드에서만 role을 덮어씌우고자 하는 것이라면, `getAllAndOverride()` 메서드를 사용하면 됩니다.\n\n```typescript\nconst roles = this.reflector.getAllAndOverride<string[]>(\"roles\", [\n  context.getHandler(),\n  context.getClass(),\n]);\n```\n\n`created()` 메서드의 컨텍스트 속에서 동작하는 가드에서 위와 같이 코드를 작성하면 `roles`의 값은 `['admin']`가 됩니다.\n\n두 메타데이터를 병합하려면 `getAllAndMerge()` 메서드를 사용합니다. 이 메서드는 두 배열을 하나로 병합합니다.\n\n```typescript\nconst roles = this.reflector.getAllAndMerge<string[]>(\"roles\", [\n  context.getHandler(),\n  context.getClass(),\n]);\n```\n\n위와 같이 작성하면 `roles`의 값은 `['user', 'admin']`가 됩니다.\n\n이 두 가지 메서드를 사용할 때에는 첫 번째 인자로 메타데이터 키를, 두 번재 인자로는 메타데이터 대상 컨텍스트(`getHandler()`나 `getClass()` 메서드를 호출한 결과)가 담긴 배열을 건네야 합니다.\n"
  },
  {
    "path": "content/fundamentals/lazy-loading-modules.md",
    "content": "### Lazy-loading modules\n\nBy default, modules are eagerly loaded, which means that as soon as the application loads, so do all the modules, whether or not they are immediately necessary. While this is fine for most applications, it may become a bottleneck for apps/workers running in the **serverless environment**, where the startup latency (\"cold start\") is crucial.\n\nLazy loading can help decrease bootstrap time by loading only modules required by the specific serverless function invocation. In addition, you could also load other modules asynchronously once the serverless function is \"warm\" to speed-up the bootstrap time for subsequent calls even further (deferred modules registration).\n\n> info **Hint** If you're familiar with the **Angular** framework, you might have seen the \"lazy-loading modules\" term before. Be aware that this technique is **functionally different** in Nest and so think about this as an entirely different feature that shares similar naming conventions.\n\n#### Getting started\n\nTo load modules on-demand, Nest provides the `LazyModuleLoader` class that can be injected into a class in the normal way:\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService {\n  constructor(private lazyModuleLoader: LazyModuleLoader) {}\n}\n@@switch\n@Injectable()\n@Dependencies(LazyModuleLoader)\nexport class CatsService {\n  constructor(lazyModuleLoader) {\n    this.lazyModuleLoader = lazyModuleLoader;\n  }\n}\n```\n\n> info **Hint** The `LazyModuleLoader` class is imported from the `@nestjs/core` package.\n\nAlternatively, you can obtain a reference to the `LazyModuleLoader` provider from within your application bootstrap file (`main.ts`), as follows:\n\n```typescript\n// \"app\" represents a Nest application instance\nconst lazyModuleLoader = app.get(LazyModuleLoader);\n```\n\nWith this in place, you can now load any module using the following construction:\n\n```typescript\nconst { LazyModule } = await import('./lazy.module');\nconst moduleRef = await this.lazyModuleLoader.load(() => LazyModule);\n```\n\n> info **Hint** \"Lazy-loaded\" modules are **cached** upon the first `LazyModuleLoader#load` method invocation. That means, each consecutive attempt to load `LazyModule` will be **very fast** and will return a cached instance, instead of loading the module again.\n>\n> ```bash\n> Load \"LazyModule\" attempt: 1\n> time: 2.379ms\n> Load \"LazyModule\" attempt: 2\n> time: 0.294ms\n> Load \"LazyModule\" attempt: 3\n> time: 0.303ms\n> ```\n>\n> Also, \"lazy-loaded\" modules share the same modules graph as those eagerly loaded on the application bootstrap as well as any other lazy modules registered later in your app.\n\nWhere `lazy.module.ts` is a TypeScript file that exports a **regular Nest module** (no extra changes are required).\n\nThe `LazyModuleLoader#load` method returns the [module reference](/fundamentals/module-ref) (of `LazyModule`) that lets you navigate the internal list of providers and obtain a reference to any provider using its injection token as a lookup key.\n\nFor example, let's say we have a `LazyModule` with the following definition:\n\n```typescript\n@Module({\n  providers: [LazyService],\n  exports: [LazyService],\n})\nexport class LazyModule {}\n```\n\n> info **Hint** Lazy-loaded modules cannot be registered as **global modules** as it simply makes no sense (since they are registered lazily, on-demand when all the statically registered modules have been already instantiated). Likewise, registered **global enhancers** (guards/interceptors/etc.) **will not work** properly either.\n\nWith this, we could obtain a reference to the `LazyService` provider, as follows:\n\n```typescript\nconst { LazyModule } = await import('./lazy.module');\nconst moduleRef = await this.lazyModuleLoader.load(() => LazyModule);\n\nconst { LazyService } = await import('./lazy.service');\nconst lazyService = moduleRef.get(LazyService);\n```\n\n> warning **Warning** If you use **Webpack**, make sure to update your `tsconfig.json` file - setting `compilerOptions.module` to `\"esnext\"` and adding `compilerOptions.moduleResolution` property with `\"node\"` as a value:\n>\n> ```json\n> {\n>   \"compilerOptions\": {\n>     \"module\": \"esnext\",\n>     \"moduleResolution\": \"node\",\n>     ...\n>   }\n> }\n> ```\n>\n> With these options set up, you'll be able to leverage the [code splitting](https://webpack.js.org/guides/code-splitting/) feature.\n\n#### Lazy-loading controllers, gateways, and resolvers\n\nSince controllers (or resolvers in GraphQL applications) in Nest represent sets of routes/paths/topics (or queries/mutations), you **cannot lazy load them** using the `LazyModuleLoader` class.\n\n> error **Warning** Controllers, [resolvers](/graphql/resolvers), and [gateways](/websockets/gateways) registered inside lazy-loaded modules will not behave as expected. Similarly, you cannot register middleware functions (by implementing the `MiddlewareConsumer` interface) on-demand.\n\nFor example, let's say you're building a REST API (HTTP application) with a Fastify driver under the hood (using the `@nestjs/platform-fastify` package). Fastify does not let you register routes after the application is ready/successfully listening to messages. That means even if we analyzed route mappings registered in the module's controllers, all lazy-loaded routes wouldn't be accessible since there is no way to register them at runtime.\n\nLikewise, some transport strategies we provide as part of the `@nestjs/microservices` package (including Kafka, gRPC, or RabbitMQ) require to subscribe/listen to specific topics/channels before the connection is established. Once your application starts listening to messages, the framework would not be able to subscribe/listen to new topics.\n\nLastly, the `@nestjs/graphql` package with the code first approach enabled automatically generates the GraphQL schema on-the-fly based on the metadata. That means, it requires all classes to be loaded beforehand. Otherwise, it would not be doable to create the appropriate, valid schema.\n\n#### Common use-cases\n\nMost commonly, you will see lazy loaded modules in situations when your worker/cron job/lambda & serverless function/webhook must trigger different services (different logic) based on the input arguments (route path/date/query parameters, etc.). On the other hand, lazy-loading modules may not make too much sense for monolithic applications, where the startup time is rather irrelevant.\n"
  },
  {
    "path": "content/fundamentals/lifecycle-events.md",
    "content": "### Lifecycle Events\n\nA Nest application, as well as every application element, has a lifecycle managed by Nest. Nest provides **lifecycle hooks** that give visibility into key lifecycle events, and the ability to act (run registered code on your `module`, `injectable` or `controller`) when they occur.\n\n#### Lifecycle sequence\n\nThe following diagram depicts the sequence of key application lifecycle events, from the time the application is bootstrapped until the node process exits. We can divide the overall lifecycle into three phases: **initializing**, **running** and **terminating**. Using this lifecycle, you can plan for appropriate initialization of modules and services, manage active connections, and gracefully shutdown your application when it receives a termination signal.\n\n<figure><img src=\"/assets/lifecycle-events.png\" /></figure>\n\n#### Lifecycle events\n\nLifecycle events happen during application bootstrapping and shutdown. Nest calls registered lifecycle hook methods on `modules`, `injectables` and `controllers` at each of the following lifecycle events (**shutdown hooks** need to be enabled first, as described [below](https://docs.nestjs.com/fundamentals/lifecycle-events#application-shutdown)). As shown in the diagram above, Nest also calls the appropriate underlying methods to begin listening for connections, and to stop listening for connections.\n\nIn the following table, `onModuleDestroy`, `beforeApplicationShutdown` and `onApplicationShutdown` are only triggered if you explicitly call `app.close()` or if the process receives a special system signal (such as SIGTERM) and you have correctly called `enableShutdownHooks` at application bootstrap (see below **Application shutdown** part).\n\n| Lifecycle hook method           | Lifecycle event triggering the hook method call                                                                                                                                                                   |\n| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `onModuleInit()`                | Called once the host module's dependencies have been resolved.                                                                                                                                                    |\n| `onApplicationBootstrap()`      | Called once all modules have been initialized, but before listening for connections.                                                                                                                              |\n| `onModuleDestroy()`\\*           | Called after a termination signal (e.g., `SIGTERM`) has been received.                                                                                                                                            |\n| `beforeApplicationShutdown()`\\* | Called after all `onModuleDestroy()` handlers have completed (Promises resolved or rejected);<br />once complete (Promises resolved or rejected), all existing connections will be closed (`app.close()` called). |\n| `onApplicationShutdown()`\\*     | Called after connections close (`app.close()` resolves).                                                                                                                                                           |\n\n\\* For these events, if you're not calling `app.close()` explicitly, you must opt-in to make them work with system signals such as `SIGTERM`. See [Application shutdown](fundamentals/lifecycle-events#application-shutdown) below.\n\n> warning **Warning** The lifecycle hooks listed above are not triggered for **request-scoped** classes. Request-scoped classes are not tied to the application lifecycle and their lifespan is unpredictable. They are exclusively created for each request and automatically garbage-collected after the response is sent.\n\n#### Usage\n\nEach lifecycle hook is represented by an interface. Interfaces are technically optional because they do not exist after TypeScript compilation. Nonetheless, it's good practice to use them in order to benefit from strong typing and editor tooling. To register a lifecycle hook, implement the appropriate interface. For example, to register a method to be called during module initialization on a particular class (e.g., Controller, Provider or Module), implement the `OnModuleInit` interface by supplying an `onModuleInit()` method, as shown below:\n\n```typescript\n@@filename()\nimport { Injectable, OnModuleInit } from '@nestjs/common';\n\n@Injectable()\nexport class UsersService implements OnModuleInit {\n  onModuleInit() {\n    console.log(`The module has been initialized.`);\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class UsersService {\n  onModuleInit() {\n    console.log(`The module has been initialized.`);\n  }\n}\n```\n\n#### Asynchronous initialization\n\nBoth the `OnModuleInit` and `OnApplicationBootstrap` hooks allow you to defer the application initialization process (return a `Promise` or mark the method as `async` and `await` an asynchronous method completion in the method body).\n\n```typescript\n@@filename()\nasync onModuleInit(): Promise<void> {\n  await this.fetch();\n}\n@@switch\nasync onModuleInit() {\n  await this.fetch();\n}\n```\n\n#### Application shutdown\n\nThe `onModuleDestroy()`, `beforeApplicationShutdown()` and `onApplicationShutdown()` hooks are called in the terminating phase (in response to an explicit call to `app.close()` or upon receipt of system signals such as SIGTERM if opted-in). This feature is often used with [Kubernetes](https://kubernetes.io/) to manage containers' lifecycles, by [Heroku](https://www.heroku.com/) for dynos or similar services.\n\nShutdown hook listeners consume system resources, so they are disabled by default. To use shutdown hooks, you **must enable listeners** by calling `enableShutdownHooks()`:\n\n```typescript\nimport { NestFactory } from '@nestjs/core';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  // Starts listening for shutdown hooks\n  app.enableShutdownHooks();\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n> warning **warning** Due to inherent platform limitations, NestJS has limited support for application shutdown hooks on Windows. You can expect `SIGINT` to work, as well as `SIGBREAK` and to some extent `SIGHUP` - [read more](https://nodejs.org/api/process.html#process_signal_events). However `SIGTERM` will never work on Windows because killing a process in the task manager is unconditional, \"i.e., there's no way for an application to detect or prevent it\". Here's some [relevant documentation](https://docs.libuv.org/en/v1.x/signal.html) from libuv to learn more about how `SIGINT`, `SIGBREAK` and others are handled on Windows. Also, see Node.js documentation of [Process Signal Events](https://nodejs.org/api/process.html#process_signal_events)\n\n> info **Info** `enableShutdownHooks` consumes memory by starting listeners. In cases where you are running multiple Nest apps in a single Node process (e.g., when running parallel tests with Jest), Node may complain about excessive listener processes. For this reason, `enableShutdownHooks` is not enabled by default. Be aware of this condition when you are running multiple instances in a single Node process.\n\nWhen the application receives a termination signal it will call any registered `onModuleDestroy()`, `beforeApplicationShutdown()`, then `onApplicationShutdown()` methods (in the sequence described above) with the corresponding signal as the first parameter. If a registered function awaits an asynchronous call (returns a promise), Nest will not continue in the sequence until the promise is resolved or rejected.\n\n```typescript\n@@filename()\n@Injectable()\nclass UsersService implements OnApplicationShutdown {\n  onApplicationShutdown(signal: string) {\n    console.log(signal); // e.g. \"SIGINT\"\n  }\n}\n@@switch\n@Injectable()\nclass UsersService implements OnApplicationShutdown {\n  onApplicationShutdown(signal) {\n    console.log(signal); // e.g. \"SIGINT\"\n  }\n}\n```\n\n> info **Info** Calling `app.close()` doesn't terminate the Node process but only triggers the `onModuleDestroy()` and `onApplicationShutdown()` hooks, so if there are some intervals, long-running background tasks, etc. the process won't be automatically terminated.\n"
  },
  {
    "path": "content/fundamentals/module-reference.md",
    "content": "### Module reference\n\nNest는 `ModuleRef` 클래스를 제공하여 프로파이더의 내부 목록을 탐색하고 인젝션 토큰을 조회 키로 사용하는 모든 프로파이더에 대한 참조를 가져옵니다. `ModuleRef` 클래스는 정적 및 범위 프로파이더를 모두 동적으로 인스턴스화하는 방법도 제공합니다. `ModuleRef`는 일반적인 방법으로 클래스에 인젝션될 수 있습니다:\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService {\n  constructor(private moduleRef: ModuleRef) {}\n}\n@@switch\n@Injectable()\n@Dependencies(ModuleRef)\nexport class CatsService {\n  constructor(moduleRef) {\n    this.moduleRef = moduleRef;\n  }\n}\n```\n\n> info **Hint** `ModuleRef` 클래스는 `@nestjs/core` 패키지에서 import됩니다.\n\n#### Retrieving instances\n\n`ModuleRef` 인스턴스 (이후 **모듈 참조**라고 함.)는 `get()` 메서드를 가집니다. 이 메서드는 인젝션 토큰/클래스 이름을 사용하여 **현재** 모듈에 존재하는 (인스턴스화된)프로바이더, 컨트롤러 또는 인젝터블(e.g., guard, interceptor, etc.)을 조회합니다.\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService implements OnModuleInit {\n  private service: Service;\n  constructor(private moduleRef: ModuleRef) {}\n\n  onModuleInit() {\n    this.service = this.moduleRef.get(Service);\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(ModuleRef)\nexport class CatsService {\n  constructor(moduleRef) {\n    this.moduleRef = moduleRef;\n  }\n\n  onModuleInit() {\n    this.service = this.moduleRef.get(Service);\n  }\n}\n```\n\n> warn **경고** `get()` 메서드로 스코프 프로바이더(transient or request-scoped)를 조회하면 안 됩니다. 대신에 <a href=\"https://docs.nestjs.kr/fundamentals/module-ref#resolving-scoped-providers\">밑에</a> 서술된 기법을 사용하십시오. 스코프를 컨트롤 하는 방법 배우기 [here](/fundamentals/injection-scopes).\n\n전역 컨텍스트에서(예를 들어, 프로바이더가 다른 모듈에서 인젝션되었다면) 프로바이더를 조회하기 위해서는 `{ strict: false }` 옵션을 `get()`에 두 번째 인자로 넘겨주십시오.\n\n```typescript\nthis.moduleRef.get(Service, { strict: false });\n```\n\n#### Resolving scoped providers\n\n스코프 프로바이더 (transient 또는 request-scoped)를 동적으로 리졸브하기 위해서는 인젝션 토큰을 인자로 넘겨주는`resolve()` 메서드를 사용하십시오.,\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService implements OnModuleInit {\n  private transientService: TransientService;\n  constructor(private moduleRef: ModuleRef) {}\n\n  async onModuleInit() {\n    this.transientService = await this.moduleRef.resolve(TransientService);\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(ModuleRef)\nexport class CatsService {\n  constructor(moduleRef) {\n    this.moduleRef = moduleRef;\n  }\n\n  async onModuleInit() {\n    this.transientService = await this.moduleRef.resolve(TransientService);\n  }\n}\n```\n\n`resolve()` 메서드는 프로바이더의 **DI container sub-tree**로부터 고유한 프로바이더 인스턴스를 반환합니다. 각각의 서브트리는 유니크한 **컨텍스트 식별자**를 가집니다. 그래서 만약 이 메서드를 한 번 이상 호출하고 인스턴스 참조를 비교한다면 이 둘이 같지 않음을 확인할 것입니다.\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService implements OnModuleInit {\n  constructor(private moduleRef: ModuleRef) {}\n\n  async onModuleInit() {\n    const transientServices = await Promise.all([\n      this.moduleRef.resolve(TransientService),\n      this.moduleRef.resolve(TransientService),\n    ]);\n    console.log(transientServices[0] === transientServices[1]); // false\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(ModuleRef)\nexport class CatsService {\n  constructor(moduleRef) {\n    this.moduleRef = moduleRef;\n  }\n\n  async onModuleInit() {\n    const transientServices = await Promise.all([\n      this.moduleRef.resolve(TransientService),\n      this.moduleRef.resolve(TransientService),\n    ]);\n    console.log(transientServices[0] === transientServices[1]); // false\n  }\n}\n```\n\n여러 `resolve()`호출을 걸쳐 단일 인스턴스를 생성하고, 이들이 동일한 생성된 DI container sub-tree를 공유하도록 보장하려면 컨텍스트 식별자를 `resolve()` 메서드에 전달하면 됩니다. 컨텍스트 식별자를 생성하기 위해서 `ContextIdFactory` 클래스를 사용하십시오. 이 클래스는 적절한 고유 식별자를 반환하는 `create()` 메서드를 제공합니다.\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService implements OnModuleInit {\n  constructor(private moduleRef: ModuleRef) {}\n\n  async onModuleInit() {\n    const contextId = ContextIdFactory.create();\n    const transientServices = await Promise.all([\n      this.moduleRef.resolve(TransientService, contextId),\n      this.moduleRef.resolve(TransientService, contextId),\n    ]);\n    console.log(transientServices[0] === transientServices[1]); // true\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(ModuleRef)\nexport class CatsService {\n  constructor(moduleRef) {\n    this.moduleRef = moduleRef;\n  }\n\n  async onModuleInit() {\n    const contextId = ContextIdFactory.create();\n    const transientServices = await Promise.all([\n      this.moduleRef.resolve(TransientService, contextId),\n      this.moduleRef.resolve(TransientService, contextId),\n    ]);\n    console.log(transientServices[0] === transientServices[1]); // true\n  }\n}\n```\n\n> info **힌트** `ContextIdFactory` 클래스는 `@nestjs/core` 패키지에서 import 됩니다.\n\n#### Registering `REQUEST` provider\n\n(`ContextIdFactory.create()`로) 수동으로 생성된 컨텍스트 식별자는 Nest 의존성 주입 시스템에 의해 인스턴스화 되고 관리되지 않으므로 `REQUEST` 프로바이더가 `undefined` DI sub-trees를 나타낸다.\n\n수동으로 생성된 DI sub-tree를 위해 커스텀 `REQUEST` 오브젝트를 등록하기 위해서, `ModuleRef#registerRequestByContextId()` 메서드를 다음과 같이 사용하십시오:\n\n```typescript\nconst contextId = ContextIdFactory.create();\nthis.moduleRef.registerRequestByContextId(/* YOUR_REQUEST_OBJECT */, contextId);\n```\n\n#### Getting current sub-tree\n\n경우에 따라 **request context** 안에 있는 request-scoped 프로바이더 인스턴스를 리졸브하고 싶을 수도 있습니다. `CatsService`가 request-scoped 이고 당신이 request-scoped 프로바이더로 표시된`CatsRepository` 인스턴스를 리졸브 하고 싶다고 해봅시다. In order to share the 같은 DI container sub-tree를 공유하기 위해서, (e.g., 위에서 보여준 것과 같이`ContextIdFactory.create()` 함수로 생성했던) 새로운 컨텍스트 식별자를 생성하는 대신 현재 컨텍스트 식별자를 얻어야만 합니다. 현재 컨텍스트 식별자를 얻기 위해서, `@Inject()` 데코레이더를 사용해서 요청 객체를 주입하는 것으로 시작하십시오.\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService {\n  constructor(\n    @Inject(REQUEST) private request: Record<string, unknown>,\n  ) {}\n}\n@@switch\n@Injectable()\n@Dependencies(REQUEST)\nexport class CatsService {\n  constructor(request) {\n    this.request = request;\n  }\n}\n```\n\n> info **힌트** 요청 프로바이더에 더 배우고 싶다면 [here](https://docs.nestjs.kr/fundamentals/injection-scopes#request-provider).\n\n이제, 요청 객체에 기반을 둔 컨텍스트 id를 생성하기 위해 `ContextIdFactory` 클래스의 `getByRequest()` 메서드를 사용하고 컨텍스트 id를 `resolve()` 호출에 전달하십시오:\n\n```typescript\nconst contextId = ContextIdFactory.getByRequest(this.request);\nconst catsRepository = await this.moduleRef.resolve(CatsRepository, contextId);\n```\n\n#### Instantiating custom classes dynamically\n\n동적으로 **이전에 프로바이더로 등록되지 않은** 클래스를 인스턴스화 시키기 위해서, 모듈 참조의 `create()` 메서드를 사용하십시오.\n\n```typescript\n@@filename(cats.service)\n@Injectable()\nexport class CatsService implements OnModuleInit {\n  private catsFactory: CatsFactory;\n  constructor(private moduleRef: ModuleRef) {}\n\n  async onModuleInit() {\n    this.catsFactory = await this.moduleRef.create(CatsFactory);\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(ModuleRef)\nexport class CatsService {\n  constructor(moduleRef) {\n    this.moduleRef = moduleRef;\n  }\n\n  async onModuleInit() {\n    this.catsFactory = await this.moduleRef.create(CatsFactory);\n  }\n}\n```\n\n이 기법은 조건적으로 프레임워크 컨테이너 바깥의 다른 클래스를 인스턴스화 할 수 있게 해줍니다.\n\n<app-banner-shop></app-banner-shop>\n"
  },
  {
    "path": "content/fundamentals/platform-agnosticism.md",
    "content": "### Platform agnosticism\n\nNest is a platform-agnostic framework. This means you can develop **reusable logical parts** that can be used across different types of applications. For example, most components can be re-used without change across different underlying HTTP server frameworks (e.g., Express and Fastify), and even across different _types_ of applications (e.g., HTTP server frameworks, Microservices with different transport layers, and Web Sockets).\n\n#### Build once, use everywhere\n\nThe **Overview** section of the documentation primarily shows coding techniques using HTTP server frameworks (e.g., apps providing a REST API or providing an MVC-style server-side rendered app). However, all those building blocks can be used on top of different transport layers ([microservices](/microservices/basics) or [websockets](/websockets/gateways)).\n\nFurthermore, Nest comes with a dedicated [GraphQL](/graphql/quick-start) module. You can use GraphQL as your API layer interchangeably with providing a REST API.\n\nIn addition, the [application context](/application-context) feature helps to create any kind of Node.js application - including things like CRON jobs and CLI apps - on top of Nest.\n\nNest aspires to be a full-fledged platform for Node.js apps that brings a higher-level of modularity and reusability to your applications. Build once, use everywhere!\n"
  },
  {
    "path": "content/fundamentals/provider-scopes.md",
    "content": "### 스코프 주입하기\n\n다른 개발 언어를 경험하고 오는 사람들은, 들어오는 모든 요청 간에 거의 모든 컴포넌트들이 공유된다는 사실을 예상하지 못할 수 있습니다. 이를테면 데이터베이스와의 연결 풀, 전역 상태를 가지는 싱글톤 서비스 등이 있습니다. Node.js는 모든 요청이 각각 분리된 스레드에서 처리되는 Multi-Threaded Stateless 모델을 따르지 않는다는 것을 기억하고 있어야 합니다. 이 때문에, 싱글톤 인스턴스를 사용하는 것이 우리의 애플리케이션에게 전적으로 **안전**합니다.\n\n하지만 GraphQL 애플리케이션에서의 요청별 캐싱, 요청 트래킹, 멀티테넌시와 같이 인스턴스가 요청에 기반한 수명을 가지길 바라는 경우도 있습니다.\n\n#### 프로바이더의 스코프\n\n프로바이더는 다음 스코프들 중 하나를 가질 수 있습니다:\n\n<table>\n  <tr>\n    <td><code>DEFAULT</code></td>\n    <td>하나의 인스턴스를 가지는 프로바이더로서 전체 애플리케이션 간에 공유됩니다. 인스턴스의 수명은 애플리케이션 생명주기와 직결됩니다. 애플리케이션이 구동되고 나면, 모든 싱글톤 프로바이더들이 인스턴스화 되며 기본적으로 싱글톤 스코프를 가집니다.</td>\n  </tr>\n  <tr>\n    <td><code>REQUEST</code></td>\n    <td>들어오는 각각의 <strong>요청</strong>에 대해 새로운 프로바이더 인스턴스가 생성됩니다. 생성된 인스턴스는 요청이 완전히 처리된 이후에 가비지 콜렉션에 의해 수거됩니다.</td>\n  </tr>\n  <tr>\n    <td><code>TRANSIENT</code></td>\n    <td>Transient 프로바이더는 소비자(프로바이더를 주입받아 사용하는 컴포넌트)들 사이에서 공유되지 않습니다. 하나의 transient 프로바이더를 주입하는 여러 소비자들은 각자 새로운 인스턴스를 할당 받습니다.</td>\n  </tr>\n</table>\n\n> info **힌트** 대부분의 경우에는 싱글톤 스코프를 사용하는 것을 **권장**합니다. 프로바이더를 모든 소비자들과 모든 요청들이 공유한다는 것은 인스턴스의 초기화 작업이 애플리케이션이 구동되는 시점에 딱 한 번 이루어진 후에 그 인스턴스가 캐싱 된다는 것을 뜻합니다.\n\n#### 사용법\n\n주입되는 프로바이더의 스코프를 정하려면 `@Injectable()`데코레이터의 options객체에 `scope`프로퍼티를 넘겨야 합니다:\n\n```typescript\nimport { Injectable, Scope } from \"@nestjs/common\";\n\n@Injectable({ scope: Scope.REQUEST })\nexport class CatsService {}\n```\n\n비슷하게, [custom providers](/fundamentals/custom-providers)에서도 프로바이더를 등록하는 과정에서 `scope`프로퍼티를 지정했습니다.\n\n```typescript\n{\n  provide: 'CACHE_MANAGER',\n  useClass: CacheManager,\n  scope: Scope.TRANSIENT,\n}\n```\n\n> info **힌트** `Scope` enum은 `@nestjs/common`에서 import합니다\n\n> warning **주의** Gateway는 실제 소켓을 캡슐화하기 때문에 여러 번 인스턴스화될 수 없습니다. 즉, Gateway는 무조건 싱글톤으로 동작해야 하기에 요청기반 스코프를 가지는 프로바이더를 사용할 수 없습니다.\n\n싱글톤 스코프는 기본으로 적용되기에 따로 명시할 필요가 없습니다. 만약 프로바이더가 싱글톤 스코프를 가지도록 명시하고 싶다면, `scope`프로퍼티의 값으로 `Scope.DEFAULT`를 넣으면 됩니다.\n\n#### 컨트롤러의 스코프\n\n컨트롤러 또한 스코프를 가질 수 있으며, 해당 컨트롤러에 속한 모든 요청핸들러 메서드들에게 적용됩니다. 프로바이더의 스코프처럼, 컨트롤러의 스코프도 그 수명을 결정합니다. 요청기반 스코프를 가지는 컨트롤러는 들어오는 각 요청에 대해 새로운 인스턴스를 생성하고 요청이 완전히 처리되면 가비지 컬렉션에 의해 수거됩니다.\n\n컨트롤러의 스코프를 정의하려면 `ControllerOptions`객체의 `scope`프로퍼티를 사용합니다:\n\n```typescript\n@Controller({\n  path: \"cats\",\n  scope: Scope.REQUEST,\n})\nexport class CatsController {}\n```\n\n#### 스코프 계층구조\n\n스코프의 주입은 연쇄적으로 버블링 됩니다. 어떤 컨트롤러가 요청기반 스코프의 프로바이더에 의존한다면, 그 컨트롤러도 요청기반 스코프를 가지게 됩니다.\n\n다음과 같은 의존성 구조를 상상해 봅시다: `CatsController <- CatsService <- CatsRepository`. 만약 `CatsService`만 요청기반 스코프를 가지고 나머지는 기본 스코프인 싱글톤 스코프를 가진다면, `CatsController`는 주입받는 서비스에 의존하므로 요청기반 스코프를 가지게 됩니다. `CatsRepository`는 서비스에 의존하지 않으므로 싱글톤 스코프 그대로 남습니다.\n\n<app-banner-courses></app-banner-courses>\n\n#### 요청 프로바이더\n\nHTTP 서버 기반의 애플리케이션(이를테면 `@nestjs/platform-express` 혹은 `@nestjs/platform-fastify`)에서, 요청기반 스코프의 프로바이더를 사용하면서 원래의 요청 객체를 참조하고 싶을 수 있습니다. 이는 `REQUEST`객체를 주입함으로써 가능합니다.\n\n```typescript\nimport { Injectable, Scope, Inject } from \"@nestjs/common\";\nimport { REQUEST } from \"@nestjs/core\";\nimport { Request } from \"express\";\n\n@Injectable({ scope: Scope.REQUEST })\nexport class CatsService {\n  constructor(@Inject(REQUEST) private request: Request) {}\n}\n```\n\n기본적인 플랫폼이나 프로토콜의 차이로 인해, 마이크로서비스나 GraphQL을 사용하는 분들은 들어오는 요청에 접근하는 방법이 아주 살짝 다릅니다. [GraphQL](/graphql/quick-start) 애플리케이션에서는, `REQUEST`대신에 `CONTEXT`를 주입합니다.\n\n```typescript\nimport { Injectable, Scope, Inject } from \"@nestjs/common\";\nimport { CONTEXT } from \"@nestjs/graphql\";\n\n@Injectable({ scope: Scope.REQUEST })\nexport class CatsService {\n  constructor(@Inject(CONTEXT) private context) {}\n}\n```\n\n그 다음, `request`프로퍼티를 포함시키도록 `GraphQLModule`에서 `context`의 값을 구성해야 합니다.\n\n#### 성능\n\n요청기반 스코프의 프로바이더를 사용하는 것은 애플리케이션 성능에 타격을 줄 수 있습니다. Nest는 가능한 많은 메타데이터를 캐싱 하려 하는데, 그 프로바이더의 인스턴스는 요청이 들어올 때마다 계속 생성하므로 평균 응답시간과 전체적인 벤치마킹 결과가 느려질 수밖에 없습니다. 프로바이더가 요청기반 스코프를 무조건 가져야 하는 게 아니라면, 기본값인 싱글톤 스코프를 사용하기를 적극 권장합니다.\n"
  },
  {
    "path": "content/fundamentals/unit-testing.md",
    "content": "### Testing\n\n자동화된 테스트는 진지한 소프트웨어 개발의 필수적인 부분 이라 간주됩니다. 테스트 자동화는 개발하는 도중 각각의 테스트, 혹은 테스트 묶음을 쉽게 혹은 빠르게 반복할 수 있게 해줍니다. 이는 Release가 품질과 성능 목표치를 충족하는지 보장하는데 도움을 줍니다. 테스트 자동화는 보증 범위를 늘려주며, 빠른 테스트 피드백 반복 주기를 개발자에게 제공합니다. 자동화는 개별 개발자의 생산성을 높이며 소스 코드 제어 check-in, 기능 통합 및 버전 릴리즈와 같은 중요한 개발 생명 주기 시점에서 테스트가 실행 될 수 있도록 보장합니다.\n\n이러한 테스트는 종종 단위 다양한 여러 유형으로, 유닛테스트를 포함한, 종단간 테스트, 통합 테스트등 다양한 유형에 걸쳐있습니다. 장점은 의심할 여지가 없습니다, 테스트를 설정하는건 지루할 수 있습니다. NEST는 효과적인 테스트를 포함하여 모범적인 개발사례를 발전시키기 위해 노력하고 있습니다, 그래서 다음과 같이 개발자들과 그 팀들이 자동화된 테스트를 구현하기 위한 기능들을 포함하고 있습니다. NEST :\n\n- automatically scaffolds default unit tests for components and e2e tests for applications\n- provides default tooling (such as a test runner that builds an isolated module/application loader)\n- provides integration with [Jest](https://github.com/facebook/jest) and [Supertest](https://github.com/visionmedia/supertest) out-of-the-box, while remaining agnostic to testing tools\n- makes the Nest dependency injection system available in the testing environment for easily mocking components\n\n언급 했듯, 당신이 사용하고 싶은 어떠한 **테스트 프레임워크**라도 사용할 수 있습니다, Nest는 어떠한 특별한 테스팅 툴을 강제하지 않습니다. 간단하게 필요한 요소 ( 예를들어 테스트 러너 ) 를 교체하면 됩니다, 그럼 기존에 사용하던 그대로 Nest의 ready-made 테스트 시설들을 이용할 수 있습니다.\n\n#### 설치방법\n\n시작에 앞서, 필요한 패키지를 설치하여야 합니다:\n\n```bash\n$ npm i --save-dev @nestjs/testing\n```\n\n#### Unit Testing\n\n이하 예시에서는, 두가지 Case를 테스트해볼 예정입니다.: `CatsController` 그리고 `CatsService`. 언급했듯이, [Jest](https://github.com/facebook/jest) 는 기본으로 제공되는 테스팅 프레임워크입니다. 테스트 러너 역할을 하며 assert function 기능과 mocking 과 spying, 및 기타 기능을 제공하는 test-double uttilities 기능을 제공합니다 . 이하 기본 테스트를 통해, 다음 기본 테스트에서, 이러한 클래스를 수동으로 인스턴스화하고 컨트롤러와 서비스를 실행하여 API가 제대로 동작하는지 확인합니다.\n\n```typescript\n@@filename(cats.controller.spec)\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\ndescribe('CatsController', () => {\n  let catsController: CatsController;\n  let catsService: CatsService;\n\n  beforeEach(() => {\n    catsService = new CatsService();\n    catsController = new CatsController(catsService);\n  });\n\n  describe('findAll', () => {\n    it('should return an array of cats', async () => {\n      const result = ['test'];\n      jest.spyOn(catsService, 'findAll').mockImplementation(() => result);\n\n      expect(await catsController.findAll()).toBe(result);\n    });\n  });\n});\n@@switch\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\ndescribe('CatsController', () => {\n  let catsController;\n  let catsService;\n\n  beforeEach(() => {\n    catsService = new CatsService();\n    catsController = new CatsController(catsService);\n  });\n\n  describe('findAll', () => {\n    it('should return an array of cats', async () => {\n      const result = ['test'];\n      jest.spyOn(catsService, 'findAll').mockImplementation(() => result);\n\n      expect(await catsController.findAll()).toBe(result);\n    });\n  });\n});\n```\n\n> info **Hint** Keep your test files located near the classes they test. Testing files should have a `.spec` or `.test` suffix.\n\n위의 예시는 사소한 것이기 때문에, Nest-Specific 한것을 테스트했다고 볼수는 없습니다. 대신, \"실제로 우리는 의존성 주입을 사용하지도 않았습니다. ( `CatsService`를  `catsController` 로 건내주기만 했다는걸 기억해주시기 바랍니다). 이러한 형태의 테스트 - 테스트 하려는 클래스를 수동으로 인스턴수화 하는 것 - 이를 프레임워크에서 독립되어있다고 하여 **독립 테스트** 라고 명명하곤 합니다. Nest의 기능을 보다 광범위하게 사용하는, 애플리케이션 테스트에 도움되는 몇가지 고급 기능을 소개하겠습니다.\n\n#### 테스팅 도구\n\nThe `@nestjs/testing` 패키지는 보다 강력한 테스트 프로세스를 가능하게 하는 유틸리티를 제공합니다. 내장된 `Test` class 를 사용하여 이전 예제를 다시 작성해 보도록 하겠습니다.:\n\n```typescript\n@@filename(cats.controller.spec)\nimport { Test } from '@nestjs/testing';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\ndescribe('CatsController', () => {\n  let catsController: CatsController;\n  let catsService: CatsService;\n\n  beforeEach(async () => {\n    const moduleRef = await Test.createTestingModule({\n        controllers: [CatsController],\n        providers: [CatsService],\n      }).compile();\n\n    catsService = moduleRef.get<CatsService>(CatsService);\n    catsController = moduleRef.get<CatsController>(CatsController);\n  });\n\n  describe('findAll', () => {\n    it('should return an array of cats', async () => {\n      const result = ['test'];\n      jest.spyOn(catsService, 'findAll').mockImplementation(() => result);\n\n      expect(await catsController.findAll()).toBe(result);\n    });\n  });\n});\n@@switch\nimport { Test } from '@nestjs/testing';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\ndescribe('CatsController', () => {\n  let catsController;\n  let catsService;\n\n  beforeEach(async () => {\n    const moduleRef = await Test.createTestingModule({\n        controllers: [CatsController],\n        providers: [CatsService],\n      }).compile();\n\n    catsService = moduleRef.get(CatsService);\n    catsController = moduleRef.get(CatsController);\n  });\n\n  describe('findAll', () => {\n    it('should return an array of cats', async () => {\n      const result = ['test'];\n      jest.spyOn(catsService, 'findAll').mockImplementation(() => result);\n\n      expect(await catsController.findAll()).toBe(result);\n    });\n  });\n});\n```\n\nThe `Test` 클래스는 전체 Nest 런타임을 모의화하는 애플리케이션 실행 컨텍스트를 제공하는데 유용합니다, 이는  클래스 인스턴스 관리 와 mocking, overriding 을 쉽게 관리 할 수 있는 hook 을 제공합니다. The `Test` 클래스는 `createTestingModule()` 모듈 메타데이터 개체를 인수로 사용하는 메서드 ( `@Module()` decorator 로 전달되는 동일한 객체 ) 를 사용합니다.  `TestingModule` 메소드는  몇 가지 메서드를 차례로 제공하는 인스턴스를 반환합니다. 유닛 테스트를 위해서, 무엇보다 중요한건 `compile()` 메소드 입니다. 이 메소드는 종속성이 있는 모듈을 bootstrap 합니다 (응용 프로그램이 기존의 `main.ts` 파일의 `NestFactory.create()`), 그리고 테스트가 준비된 모듈을 반환합니다.\n\n> 정보) **힌트** The `compile()` 메소드는 **비동기 함수**로, await 되어야 합니다. 모듈이 compile 되면, `get()` 메소드를 이용하여 정의된 **static** instance ( 컨트롤러 그리고 프로바이더들) 을 가져올 수 있습니다.\n\n`TestingModule` 은  [module reference](/fundamentals/module-ref) 클래스로 부터 상속되었습니다, 따라서 scoped provider(transient or request-scoped)를 동적으로 가져올수 있습니다. `resolve()` 함수로 가능합니다. (the `get()` 메소드는 정적인 인스턴스를 가져올 수 있습니다)\n\n```typescript\nconst moduleRef = await Test.createTestingModule({\n  controllers: [CatsController],\n  providers: [CatsService],\n}).compile();\n\ncatsService = await moduleRef.resolve(CatsService);\n```\n\n> 주의 **주의** The `resolve()` 메소드는 공급자의 고유한 인스턴스를 **DI 컨테이너 하위 트리** 에서 반환합니다. 각 하위 트리에는 고유한 컨텍스트 식별자가 존재합니다. 따라서 이 메서드를 두 번 이상 호출하고 인스턴스 참조를 비교하면 동일하지 않음을 알 수 있습니다.\n\n> 정보 **힌트** 모듈 참조 기능에 대해 자세히 알아보기 [here](/fundamentals/module-ref).\n\n공급자의 프로덕션 버전을 사용하는 대신 테스트를 위해 다음으로 재정의 할 수 있습니다 [custom provider](/fundamentals/custom-providers). 예를 들어, live 데이터베이스에 접속하는 대신, 데이터베이스 서비스를 mock 합니다. Mocking은 다음 섹션에서 다루지만 단위 테스트에서도 사용할 수 있습니다.\n\n<app-banner-courses></app-banner-courses>\n\n#### Auto mocking\n\nNest는 또한 누락된 모든 종속성에 적용할 mock factory를 정의할 수 있습니다. 클래스에 많은 수의 종속성이 있고 모든 종속성을 mocking 하는 데 오랜 시간과 많은 설정이 필요한 경우 유용합니다. 이 기능을 사용하려면, the `createTestingModule()` 과 `useMocker()` 메소드의  연결이 필요합니다,  의존성 mock 을 위한 factory 데이터 전달. 이 factory는 선택적으로 토큰을 가질 수 있습니다, Nest 제공자에 대한 유효한 모든 토큰인 instance 토큰이며 mock 구현을 반환합니다. 다음은 mocker 인  [`jest-mock`](https://www.npmjs.com/package/jest-mock) 을 사용하여  `CatsService`의 `jest.fn()`를 사용한 generic mocker 구현 예시입니다.\n\n```typescript\nconst moduleMocker = new ModuleMocker(global);\n\ndescribe('CatsController', () => {\n  let controller: CatsController;\n\n  beforeEach(async () => {\n    const moduleRef = await Test.createTestingModule({\n      controllers: [CatsController],\n    })\n    .useMocker((token) => {\n      if (token === CatsService) {\n        return { findAll: jest.fn().mockResolveValue(results) };\n      }\n      if (typeof token === 'function') {\n        const mockMetadata = moduleMocker.getMetadata(token) as MockFunctionMetadata<any, any>;\n        const Mock = moduleMocker.generateFromMetadata(mockMetadata);\n        return new Mock();\n      }\n    })\n    .compile();\n    \n    controller = moduleRef.get(CatsController);\n  });\n})\n```\n\n> 정보 **힌트** 일반적인 mock factory, like `createMock` from [`@golevelup/ts-jest`](https://github.com/golevelup/nestjs/tree/master/packages/testing) can also be passed directly.\n\nYou can also retrieve these mocks out of the testing container as you normally would custom providers, `moduleRef.get(CatsService)`.\n\n#### End-to-end testing\n\n단위 테스트와는 달리, 개별 모듈 및 클래스에 중점을 둡니다, 엔드 투 엔드 ( e2e ) 테스트는 보다 종합적인 스준에서 클래스와 모듈의 상호 작용을 다룹니다 -- 최종 사용자가 생산 시스템과 갖게 될 상호 작용 유형에 보다 가깝습니다. 애플리케이션이 커질수록, API endpoint를 수동으로 테스트 한다는것은 불가능에 가깝습니다. 자동화된 종단 간 테스트는 시스템의 전반적인 동작이 정확하고 프로젝트 요구 사항을 충족하는지 확인하는 데 도움이 됩니다. e2e 테스트를 수행하기 위해 **단위 테스트**에서 다룬 것과 유사한 구성을 사용합니다. 추가적으로NEST 는 [Supertest](https://github.com/visionmedia/supertest) 라이브러리를 사용하여 HTTP requests 를 시뮬레이션 합니다.\n\n```typescript\n@@filename(cats.e2e-spec)\nimport * as request from 'supertest';\nimport { Test } from '@nestjs/testing';\nimport { CatsModule } from '../../src/cats/cats.module';\nimport { CatsService } from '../../src/cats/cats.service';\nimport { INestApplication } from '@nestjs/common';\n\ndescribe('Cats', () => {\n  let app: INestApplication;\n  let catsService = { findAll: () => ['test'] };\n\n  beforeAll(async () => {\n    const moduleRef = await Test.createTestingModule({\n      imports: [CatsModule],\n    })\n      .overrideProvider(CatsService)\n      .useValue(catsService)\n      .compile();\n\n    app = moduleRef.createNestApplication();\n    await app.init();\n  });\n\n  it(`/GET cats`, () => {\n    return request(app.getHttpServer())\n      .get('/cats')\n      .expect(200)\n      .expect({\n        data: catsService.findAll(),\n      });\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n@@switch\nimport * as request from 'supertest';\nimport { Test } from '@nestjs/testing';\nimport { CatsModule } from '../../src/cats/cats.module';\nimport { CatsService } from '../../src/cats/cats.service';\nimport { INestApplication } from '@nestjs/common';\n\ndescribe('Cats', () => {\n  let app: INestApplication;\n  let catsService = { findAll: () => ['test'] };\n\n  beforeAll(async () => {\n    const moduleRef = await Test.createTestingModule({\n      imports: [CatsModule],\n    })\n      .overrideProvider(CatsService)\n      .useValue(catsService)\n      .compile();\n\n    app = moduleRef.createNestApplication();\n    await app.init();\n  });\n\n  it(`/GET cats`, () => {\n    return request(app.getHttpServer())\n      .get('/cats')\n      .expect(200)\n      .expect({\n        data: catsService.findAll(),\n      });\n  });\n\n  afterAll(async () => {\n    await app.close();\n  });\n});\n```\n\n> 정보 **힌트** 만약 [Fastify](/techniques/performance) 를 HTTP adapter 로 사용하신다면, 약간 다른 구성이 필요하며, 내장된 테스트 기능이 있습니다.\n>\n> ```ts\n> let app: NestFastifyApplication;\n> \n> beforeAll(async () => {\n> app = moduleRef.createNestApplication<NestFastifyApplication>(\n>  new FastifyAdapter(),\n> );\n> \n> await app.init();\n> await app.getHttpAdapter().getInstance().ready();\n> });\n> \n> it(`/GET cats`, () => {\n> return app\n>  .inject({\n>    method: 'GET',\n>    url: '/cats',\n>  })\n>  .then((result) => {\n>    expect(result.statusCode).toEqual(200);\n>    expect(result.payload).toEqual(/* expectedPayload */);\n>  });\n> });\n> \n> afterAll(async () => {\n> await app.close();\n> });\n> ```\n\n이 예제에서는,앞에서 설명한 몇가지 개념을 기반으로 합니다. 이전에 사용한 `compile()` 메서드 외에도, `createNestApplication()` 메서드를 사용하여 전체 Nest 런타임 환경을 인스턴스화합니다. 실행중인 앱에 대한 참조를 `app` 변수에 저장하여 HTTP request 에 대한 요청을 시뮬레이션하는데 사용할 수 있습니다.\n\nSupertest의  `request()` 함수를 사용하여 HTTP 테스트를 시뮬레이션 합니다. 이러한 HTTP 요청이 실행중인 Nest 앱으로 라우팅되기를 원하므로, `request()` 함수에 의해 HTTP 수신측에 참조를 전달합니다 (Express 플램폼에 의해 제공될 수 있음). 따라서 `request(app.getHttpServer())` 는 HTTP SERVER를 구성.  `request()`를 호출하면 이제 Nest 앱에 연결된 Wrapping 된 HTTP 서버가 제공되며, 이 서버는 실제 HTTP 요청을 시뮬레이션하는 메서드를 제공합니다. 예를 들어 `request(...).get('/cats')`을 사용하면 `get '/cats'` 같은 **실제**  인터넷을 통한  HTTP 요청과 동일한 Nest 앱에 대한 요청이 이루어집니다.\n\n이 예에서는 테스트할 수 있는 하드 코딩된 값을 단순 히 반환하는 `CatsService`의 대체(이중 테스트) 구현도 제공합니다.  이러한 대체 구현을 사용하려면 `overrideProvider()` 를 사용하세요 . 마찬가지로, Nest는 각각 `overrideGuard()`, `overrideInterceptor()`, `overrideFilter()`, 및 `overridePipe()` 메서드를 사용하여 가드, 인터셉터, 필터 및 파이프를 재정의하는 메서드를 제공합니다..\n\n각 재정의 메서드는 다음에 대해 설명된 메서드를 미러링하는 3가지 다른 메서드가 잇는 개체를 반환합니다 [custom providers](https://docs.nestjs.com/fundamentals/custom-providers):\n\n- `useClass`: 개체를 재정의할 인스턴스를 제공하기 위해 인스턴스화 될 클래스 제공 (provider, guard, etc.).\n- `useValue`: 개체를 재정의할 인스턴스 제공.\n- `useFactory`: 객체를 재정의할 인스턴스를 반환하는 함수를 제공.\n\n각 재정의 메서드 유형은 차례로 `TestingModule` 인스턴스를 반환하므로,  [fluent style](https://en.wikipedia.org/wiki/Fluent_interface). 의 다른 메서드와 연결할 수 있습니다. NEst가 모듈을 인스턴스화 하고 초기화하도록 하려면 이러한 체인의 끝에 `compile()` 을 사용해야 합니다.\n\n또한, 때로는 사용자 정의 로거를 사용하고자 할 수 있습니다. 예를들어. 테스트가 실행될 때 (예) CI 서버에서). `setLogger()` 메서드를 사용하고 `LoggerService` 인터페이스를 충족하는 객체를 전달하고 `TestModuleBuilder` 에 테스트 중 로그 방법을 지시합니다. (기본적으로, 'error'만 콘솔창에 표시됨).\n\n다음 표에 설명된 대로 컴파일된 모듈에는 몇 가지 유용한 메서드가 있습니다:\n\n<table>\n  <tr>\n    <td>\n      <code>createNestApplication()</code>\n    </td>\n    <td>\n      Creates and returns a Nest application (<code>INestApplication</code> instance) based on the given module.\n      Note that you must manually initialize the application using the <code>init()</code> method.\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>createNestMicroservice()</code>\n    </td>\n    <td>\n      Creates and returns a Nest microservice (<code>INestMicroservice</code> instance) based on the given module.\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>get()</code>\n    </td>\n    <td>\n      Retrieves a static instance of a controller or provider (including guards, filters, etc.) available in the application context. Inherited from the <a href=\"/fundamentals/module-ref\">module reference</a> class.\n    </td>\n  </tr>\n  <tr>\n     <td>\n      <code>resolve()</code>\n    </td>\n    <td>\n      Retrieves a dynamically created scoped instance (request or transient) of a controller or provider (including guards, filters, etc.) available in the application context. Inherited from the <a href=\"/fundamentals/module-ref\">module reference</a> class.\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>select()</code>\n    </td>\n    <td>\n      Navigates through the module's dependency graph; can be used to retrieve a specific instance from the selected module (used along with strict mode (<code>strict: true</code>) in <code>get()</code> method).\n    </td>\n  </tr>\n</table>\n\n> info **Hint** Keep your e2e test files inside the `test` directory. The testing files should have a `.e2e-spec` suffix.\n\n#### Overriding globally registered enhancers\n\nIf you have a globally registered guard (or pipe, interceptor, or filter), you need to take a few more steps to override that enhancer. To recap the original registration looks like this:\n\n```typescript\nproviders: [\n  {\n    provide: APP_GUARD,\n    useClass: JwtAuthGuard,\n  },\n],\n```\n\nThis is registering the guard as a \"multi\"-provider through the `APP_*` token. To be able to replace the `JwtAuthGuard` here, the registration needs to use an existing provider in this slot:\n\n```typescript\nproviders: [\n  {\n    provide: APP_GUARD,\n    useExisting: JwtAuthGuard,\n    // ^^^^^^^^ notice the use of 'useExisting' instead of 'useClass'\n  },\n  JwtAuthGuard,\n],\n```\n\n> info **Hint** Change the `useClass` to `useExisting` to reference a registered provider instead of having Nest instantiate it behind the token.\n\nNow the `JwtAuthGuard` is visible to Nest as a regular provider that can be overridden when creating the `TestingModule`:\n\n```typescript\nconst moduleRef = await Test.createTestingModule({\n  imports: [AppModule],\n})\n  .overrideProvider(JwtAuthGuard)\n  .useClass(MockAuthGuard)\n  .compile();\n```\n\nNow all your tests will use the `MockAuthGuard` on every request.\n\n#### Testing request-scoped instances\n\n[Request-scoped](/fundamentals/injection-scopes) providers are created uniquely for each incoming **request**. The instance is garbage-collected after the request has completed processing. This poses a problem, because we can't access a dependency injection sub-tree generated specifically for a tested request.\n\nWe know (based on the sections above) that the `resolve()` method can be used to retrieve a dynamically instantiated class. Also, as described <a href=\"https://docs.nestjs.com/fundamentals/module-ref#resolving-scoped-providers\">here</a>, we know we can pass a unique context identifier to control the lifecycle of a DI container sub-tree. How do we leverage this in a testing context?\n\nThe strategy is to generate a context identifier beforehand and force Nest to use this particular ID to create a sub-tree for all incoming requests. In this way we'll be able to retrieve instances created for a tested request.\n\nTo accomplish this, use `jest.spyOn()` on the `ContextIdFactory`:\n\n```typescript\nconst contextId = ContextIdFactory.create();\njest\n  .spyOn(ContextIdFactory, 'getByRequest')\n  .mockImplementation(() => contextId);\n```\n\nNow we can use the `contextId` to access a single generated DI container sub-tree for any subsequent request.\n\n```typescript\ncatsService = await moduleRef.resolve(CatsService, contextId);\n```\n"
  },
  {
    "path": "content/graphql/cli-plugin.md",
    "content": "### CLI Plugin\n\n> warning **Warning** This chapter applies only to the code first approach.\n\nTypeScript's metadata reflection system has several limitations which make it impossible to, for instance, determine what properties a class consists of or recognize whether a given property is optional or required. However, some of these constraints can be addressed at compilation time. Nest provides a plugin that enhances the TypeScript compilation process to reduce the amount of boilerplate code required.\n\n> info **Hint** This plugin is **opt-in**. If you prefer, you can declare all decorators manually, or only specific decorators where you need them.\n\n#### Overview\n\nThe GraphQL plugin will automatically:\n\n- annotate all input object, object type and args classes properties with `@Field` unless `@HideField` is used\n- set the `nullable` property depending on the question mark (e.g. `name?: string` will set `nullable: true`)\n- set the `type` property depending on the type (supports arrays as well)\n- generate descriptions for properties based on comments (if `introspectComments` set to `true`)\n\nPlease, note that your filenames **must have** one of the following suffixes in order to be analyzed by the plugin: `['.input.ts', '.args.ts', '.entity.ts', '.model.ts']` (e.g., `author.entity.ts`). If you are using a different suffix, you can adjust the plugin's behavior by specifying the `typeFileNameSuffix` option (see below).\n\nWith what we've learned so far, you have to duplicate a lot of code to let the package know how your type should be declared in GraphQL. For example, you could define a simple `Author` class as follows:\n\n```typescript\n@@filename(authors/models/author.model)\n@ObjectType()\nexport class Author {\n  @Field(type => ID)\n  id: number;\n\n  @Field({ nullable: true })\n  firstName?: string;\n\n  @Field({ nullable: true })\n  lastName?: string;\n\n  @Field(type => [Post])\n  posts: Post[];\n}\n```\n\nWhile not a significant issue with medium-sized projects, it becomes verbose & hard to maintain once you have a large set of classes.\n\nBy enabling the GraphQL plugin, the above class definition can be declared simply:\n\n```typescript\n@@filename(authors/models/author.model)\n@ObjectType()\nexport class Author {\n  @Field(type => ID)\n  id: number;\n  firstName?: string;\n  lastName?: string;\n  posts: Post[];\n}\n```\n\nThe plugin adds appropriate decorators on-the-fly based on the **Abstract Syntax Tree**. Thus, you won't have to struggle with `@Field` decorators scattered throughout the code.\n\n> info **Hint** The plugin will automatically generate any missing GraphQL properties, but if you need to override them, simply set them explicitly via `@Field()`.\n\n#### Comments introspection\n\nWith the comments introspection feature enabled, CLI plugin will generate descriptions for fields based on comments.\n\nFor example, given an example `roles` property:\n\n```typescript\n/**\n * A list of user's roles\n */\n@Field(() => [String], {\n  description: `A list of user's roles`\n})\nroles: string[];\n```\n\nYou must duplicate description values. With `introspectComments` enabled, the CLI plugin can extract these comments and automatically provide descriptions for properties. Now, the above field can be declared simply as follows:\n\n```typescript\n/**\n * A list of user's roles\n */\nroles: string[];\n```\n\n#### Using the CLI plugin\n\nTo enable the plugin, open `nest-cli.json` (if you use [Nest CLI](/cli/overview)) and add the following `plugins` configuration:\n\n```javascript\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\"@nestjs/graphql\"]\n  }\n}\n```\n\nYou can use the `options` property to customize the behavior of the plugin.\n\n```javascript\n\"plugins\": [\n  {\n    \"name\": \"@nestjs/graphql\",\n    \"options\": {\n      \"typeFileNameSuffix\": [\".input.ts\", \".args.ts\"],\n      \"introspectComments\": true\n    }\n  }\n]\n```\n\nThe `options` property has to fulfill the following interface:\n\n```typescript\nexport interface PluginOptions {\n  typeFileNameSuffix?: string[];\n  introspectComments?: boolean;\n}\n```\n\n<table>\n  <tr>\n    <th>Option</th>\n    <th>Default</th>\n    <th>Description</th>\n  </tr>\n  <tr>\n    <td><code>typeFileNameSuffix</code></td>\n    <td><code>['.input.ts', '.args.ts', '.entity.ts', '.model.ts']</code></td>\n    <td>GraphQL types files suffix</td>\n  </tr>\n  <tr>\n    <td><code>introspectComments</code></td>\n      <td><code>false</code></td>\n      <td>If set to true, plugin will generate descriptions for properties based on comments</td>\n  </tr>\n</table>\n\nIf you don't use the CLI but instead have a custom `webpack` configuration, you can use this plugin in combination with `ts-loader`:\n\n```javascript\ngetCustomTransformers: (program: any) => ({\n  before: [require('@nestjs/graphql/plugin').before({}, program)]\n}),\n```\n\n#### Integration with `ts-jest` (e2e tests)\n\nWhen running e2e tests with this plugin enabled, you may run into issues with compiling schema. For example, one of the most common errors is:\n\n```json\nObject type <name> must define one or more fields.\n```\n\nThis happens because `jest` configuration does not import `@nestjs/graphql/plugin` plugin anywhere.\n\nTo fix this, create the following file in your e2e tests directory:\n\n```javascript\nconst transformer = require('@nestjs/graphql/plugin');\n\nmodule.exports.name = 'nestjs-graphql-transformer';\n// you should change the version number anytime you change the configuration below - otherwise, jest will not detect changes\nmodule.exports.version = 1;\n\nmodule.exports.factory = (cs) => {\n  return transformer.before(\n    {\n      // @nestjs/graphql/plugin options (can be empty)\n    },\n    cs.program, // \"cs.tsCompiler.program\" for older versions of Jest (<= v27)\n  );\n};\n```\n\nWith this in place, import AST transformer within your `jest` configuration file. By default (in the starter application), e2e tests configuration file is located under the `test` folder and is named `jest-e2e.json`.\n\n```json\n{\n  ... // other configuration\n  \"globals\": {\n    \"ts-jest\": {\n      \"astTransformers\": {\n        \"before\": [\"<path to the file created above>\"],\n      }\n    }\n  }\n}\n```\n"
  },
  {
    "path": "content/graphql/complexity.md",
    "content": "### Complexity\n\n> warning **Warning** This chapter applies only to the code first approach.\n\nQuery complexity allows you to define how complex certain fields are, and to restrict queries with a **maximum complexity**. The idea is to define how complex each field is by using a simple number. A common default is to give each field a complexity of `1`. In addition, the complexity calculation of a GraphQL query can be customized with so-called complexity estimators. A complexity estimator is a simple function that calculates the complexity for a field. You can add any number of complexity estimators to the rule, which are then executed one after another. The first estimator that returns a numeric complexity value determines the complexity for that field.\n\nThe `@nestjs/graphql` package integrates very well with tools like [graphql-query-complexity](https://github.com/slicknode/graphql-query-complexity) that provides a cost analysis-based solution. With this library, you can reject queries to your GraphQL server that are deemed too costly to execute.\n\n#### Installation\n\nTo begin using it, we first install the required dependency.\n\n```bash\n$ npm install --save graphql-query-complexity\n```\n\n#### Getting started\n\nOnce the installation process is complete, we can define the `ComplexityPlugin` class:\n\n```typescript\nimport { GraphQLSchemaHost, Plugin } from '@nestjs/graphql';\nimport {\n  ApolloServerPlugin,\n  GraphQLRequestListener,\n} from 'apollo-server-plugin-base';\nimport { GraphQLError } from 'graphql';\nimport {\n  fieldExtensionsEstimator,\n  getComplexity,\n  simpleEstimator,\n} from 'graphql-query-complexity';\n\n@Plugin()\nexport class ComplexityPlugin implements ApolloServerPlugin {\n  constructor(private gqlSchemaHost: GraphQLSchemaHost) {}\n\n  async requestDidStart(): Promise<GraphQLRequestListener> {\n    const maxComplexity = 20;\n    const { schema } = this.gqlSchemaHost;\n\n    return {\n      async didResolveOperation({ request, document }) {\n        const complexity = getComplexity({\n          schema,\n          operationName: request.operationName,\n          query: document,\n          variables: request.variables,\n          estimators: [\n            fieldExtensionsEstimator(),\n            simpleEstimator({ defaultComplexity: 1 }),\n          ],\n        });\n        if (complexity > maxComplexity) {\n          throw new GraphQLError(\n            `Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`,\n          );\n        }\n        console.log('Query Complexity:', complexity);\n      },\n    };\n  }\n}\n```\n\nFor demonstration purposes, we specified the maximum allowed complexity as `20`. In the example above, we used 2 estimators, the `simpleEstimator` and the `fieldExtensionsEstimator`.\n\n- `simpleEstimator`: the simple estimator returns a fixed complexity for each field\n- `fieldExtensionsEstimator`: the field extensions estimator extracts the complexity value for each field of your schema\n\n> info **Hint** Remember to add this class to the providers array in any module.\n\n#### Field-level complexity\n\nWith this plugin in place, we can now define the complexity for any field by specifying the `complexity` property in the options object passed into the `@Field()` decorator, as follows:\n\n```typescript\n@Field({ complexity: 3 })\ntitle: string;\n```\n\nAlternatively, you can define the estimator function:\n\n```typescript\n@Field({ complexity: (options: ComplexityEstimatorArgs) => ... })\ntitle: string;\n```\n\n#### Query/Mutation-level complexity\n\nIn addition, `@Query()` and `@Mutation()` decorators may have a `complexity` property specified like so:\n\n```typescript\n@Query({ complexity: (options: ComplexityEstimatorArgs) => options.args.count * options.childComplexity })\nitems(@Args('count') count: number) {\n  return this.itemsService.getItems({ count });\n}\n```\n"
  },
  {
    "path": "content/graphql/directives.md",
    "content": "### Directives\n\nA directive can be attached to a field or fragment inclusion, and can affect execution of the query in any way the server desires (read more [here](https://graphql.org/learn/queries/#directives)). The GraphQL specification provides several default directives:\n\n- `@include(if: Boolean)` - only include this field in the result if the argument is true\n- `@skip(if: Boolean)` - skip this field if the argument is true\n- `@deprecated(reason: String)` - marks field as deprecated with message\n\nA directive is an identifier preceded by a `@` character, optionally followed by a list of named arguments, which can appear after almost any element in the GraphQL query and schema languages.\n\n#### Custom directives\n\nTo create a custom schema directive, declare a class which extends the `SchemaDirectiveVisitor` class exported from the `@graphql-tools/utils` package.\n\n```typescript\nimport { SchemaDirectiveVisitor } from '@graphql-tools/utils';\nimport { defaultFieldResolver, GraphQLField } from 'graphql';\n\nexport class UpperCaseDirective extends SchemaDirectiveVisitor {\n  visitFieldDefinition(field: GraphQLField<any, any>) {\n    const { resolve = defaultFieldResolver } = field;\n    field.resolve = async function(...args) {\n      const result = await resolve.apply(this, args);\n      if (typeof result === 'string') {\n        return result.toUpperCase();\n      }\n      return result;\n    };\n  }\n}\n```\n\n> info **Hint** Note that directives cannot be decorated with the `@Injectable()` decorator. Thus, they are not able to inject dependencies.\n\n> warning **Warning** `SchemaDirectiveVisitor` is exported from the `@graphql-tools/utils` package. Note that the 8.x release of `graphql-tools` removes this export and provides a different and incompatible approach to directives, so make sure to install `@graphql-tools/utils@^7` in your project.\n\nNow, register the `UpperCaseDirective` in the `GraphQLModule.forRoot()` method:\n\n```typescript\nGraphQLModule.forRoot({\n  // ...\n  schemaDirectives: {\n    upper: UpperCaseDirective,\n  },\n});\n```\n\nOnce registered, the `@upper` directive can be used in our schema. However, the way you apply the directive will vary depending on the approach you use (code first or schema first).\n\n#### Code first\n\nIn the code first approach, use the `@Directive()` decorator to apply the directive.\n\n```typescript\n@Directive('@upper')\n@Field()\ntitle: string;\n```\n\n> info **Hint** The `@Directive()` decorator is exported from the `@nestjs/graphql` package.\n\nDirectives can be applied on fields, field resolvers, input and object types, as well as queries, mutations, and subscriptions. Here's an example of the directive applied on the query handler level:\n\n```typescript\n@Directive('@deprecated(reason: \"This query will be removed in the next version\")')\n@Query(returns => Author, { name: 'author' })\nasync getAuthor(@Args({ name: 'id', type: () => Int }) id: number) {\n  return this.authorsService.findOneById(id);\n}\n```\n\nDirectives applied through the `@Directive()` decorator will not be reflected in the generated schema definition file.\n\n#### Schema first\n\nIn the schema first approach, apply directives directly in SDL.\n\n```graphql\ndirective @upper on FIELD_DEFINITION\n\ntype Post {\n  id: Int!\n  title: String! @upper\n  votes: Int\n}\n```\n"
  },
  {
    "path": "content/graphql/extensions.md",
    "content": "### Extensions\n\n> warning **Warning** This chapter applies only to the code first approach.\n\nExtensions is an **advanced, low-level feature** that lets you define arbitrary data in the types configuration. Attaching custom metadata to certain fields allows you to create more sophisticated, generic solutions. For example, with extensions, you can define field-level roles required to access particular fields. Such roles can be reflected at runtime to determine whether the caller has sufficient permissions to retrieve a specific field.\n\n#### Adding custom metadata\n\nTo attach custom metadata for a field, use the `@Extensions()` decorator exported from the `@nestjs/graphql` package.\n\n```typescript\n@Field()\n@Extensions({ role: Role.ADMIN })\npassword: string;\n```\n\nIn the example above, we assigned the `role` metadata property the value of `Role.ADMIN`. `Role` is a simple TypeScript enum that groups all the user roles available in our system.\n\nNote, in addition to setting metadata on fields, you can use the `@Extensions()` decorator at the class level and method level (e.g., on the query handler).\n\n#### Using custom metadata\n\nLogic that leverages the custom metadata can be as complex as needed. For example, you can create a simple interceptor that stores/logs events per method invocation, or a [field middleware](/graphql/field-middleware) that matches roles required to retrieve a field with the caller permissions (field-level permissions system).\n\nFor illustration purposes, let's define a `checkRoleMiddleware` that compares a user's role (hardcoded here) with a role required to access a target field:\n\n```typescript\nexport const checkRoleMiddleware: FieldMiddleware = async (\n  ctx: MiddlewareContext,\n  next: NextFn,\n) => {\n  const { info } = ctx;\n  const { extensions } = info.parentType.getFields()[info.fieldName];\n\n  /**\n   * In a real-world application, the \"userRole\" variable\n   * should represent the caller's (user) role (for example, \"ctx.user.role\").\n   */\n  const userRole = Role.USER;\n  if (userRole === extensions.role) {\n    // or just \"return null\" to ignore\n    throw new ForbiddenException(\n      `User does not have sufficient permissions to access \"${info.fieldName}\" field.`,\n    );\n  }\n  return next();\n};\n```\n\nWith this in place, we can register a middleware for the `password` field, as follows:\n\n```typescript\n@Field({ middleware: [checkRoleMiddleware] })\n@Extensions({ role: Role.ADMIN })\npassword: string;\n```\n"
  },
  {
    "path": "content/graphql/federation.md",
    "content": "### Federation\n\n[Apollo Federation](https://www.apollographql.com/docs/apollo-server/federation/introduction/) offers a means of splitting your monolithic GraphQL server into independent microservices. It consists of two components: a gateway and one or more federated microservices. Each microservice holds part of the schema and the gateway merges the schemas into a single schema that can be consumed by the client.\n\nTo quote the [Apollo docs](https://blog.apollographql.com/apollo-federation-f260cf525d21), Federation is designed with these core principles:\n\n- Building a graph should be **declarative.** With federation, you compose a graph declaratively from within your schema instead of writing imperative schema stitching code.\n- Code should be separated by **concern**, not by types. Often no single team controls every aspect of an important type like a User or Product, so the definition of these types should be distributed across teams and codebases, rather than centralized.\n- The graph should be simple for clients to consume. Together, federated services can form a complete, product-focused graph that accurately reflects how it’s being consumed on the client.\n- It’s just **GraphQL**, using only spec-compliant features of the language. Any language, not just JavaScript, can implement federation.\n\n> warning **Warning** Apollo Federation currently does not support subscriptions.\n\nIn the next example, we'll set up a demo application with a gateway and two federated endpoints: a Users service and a Posts service.\n\n#### Federated example: Users\n\nFirst, install the optional dependency for federation:\n\n```bash\n$ npm install --save @apollo/federation @apollo/subgraph\n```\n\n#### Schema first\n\nThe User service has a simple schema. Note the `@key` directive: it tells the Apollo query planner that a particular instance of User can be fetched if you have its `id`. Also, note that we extend the `Query` type.\n\n```graphql\ntype User @key(fields: \"id\") {\n  id: ID!\n  name: String!\n}\n\nextend type Query {\n  getUser(id: ID!): User\n}\n```\n\nOur resolver has one extra method: `resolveReference()`. It's called by the Apollo Gateway whenever a related resource requires a User instance. We'll see an example of this in the Posts service later on. Please note the `@ResolveReference()` decorator.\n\n```typescript\nimport { Args, Query, Resolver, ResolveReference } from '@nestjs/graphql';\nimport { UsersService } from './users.service';\n\n@Resolver('User')\nexport class UsersResolvers {\n  constructor(private usersService: UsersService) {}\n\n  @Query()\n  getUser(@Args('id') id: string) {\n    return this.usersService.findById(id);\n  }\n\n  @ResolveReference()\n  resolveReference(reference: { __typename: string; id: string }) {\n    return this.usersService.findById(reference.id);\n  }\n}\n```\n\nFinally, we hook everything up in a module together with a `GraphQLFederationModule`. This module accepts the same options as the regular `GraphQLModule`.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { GraphQLFederationModule } from '@nestjs/graphql';\nimport { UsersResolvers } from './users.resolvers';\n\n@Module({\n  imports: [\n    GraphQLFederationModule.forRoot({\n      typePaths: ['**/*.graphql'],\n    }),\n  ],\n  providers: [UsersResolvers],\n})\nexport class AppModule {}\n```\n\n#### Code first\n\nCode first federation is very similar to regular code first GraphQL. We simply add some extra decorators to the `User` entity.\n\n```ts\nimport { Directive, Field, ID, ObjectType } from '@nestjs/graphql';\n\n@ObjectType()\n@Directive('@key(fields: \"id\")')\nexport class User {\n  @Field((type) => ID)\n  id: number;\n\n  @Field()\n  name: string;\n}\n```\n\nOur resolver has one extra method: `resolveReference()`. It's called by the Apollo Gateway whenever a related resource requires a `User` instance. We'll see an example of this in the Posts service later on. Please note the `@ResolveReference()` decorator.\n\n```ts\nimport { Args, Query, Resolver, ResolveReference } from '@nestjs/graphql';\nimport { User } from './user.entity';\nimport { UsersService } from './users.service';\n\n@Resolver((of) => User)\nexport class UsersResolvers {\n  constructor(private usersService: UsersService) {}\n\n  @Query((returns) => User)\n  getUser(@Args('id') id: number): User {\n    return this.usersService.findById(id);\n  }\n\n  @ResolveReference()\n  resolveReference(reference: { __typename: string; id: number }): User {\n    return this.usersService.findById(reference.id);\n  }\n}\n```\n\nFinally, we hook everything up in a module together with a `GraphQLFederationModule`. This module accepts the same options as the regular `GraphQLModule`.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { GraphQLFederationModule } from '@nestjs/graphql';\nimport { UsersResolvers } from './users.resolvers';\nimport { UsersService } from './users.service'; // Not included in this example\n\n@Module({\n  imports: [\n    GraphQLFederationModule.forRoot({\n      autoSchemaFile: true,\n    }),\n  ],\n  providers: [UsersResolvers, UsersService],\n})\nexport class AppModule {}\n```\n\n#### Federated example: Posts\n\nOur Post service serves aggregated posts via a `getPosts` query, but also extends our `User` type with `user.posts`\n\n#### Schema first\n\nThe Posts service references the User type in its schema by marking it with the `extend` keyword. It also adds one property to the User type. Note the `@key` directive used for matching instances of User, and the `@external` directive indicating that the `id` field is managed elsewhere.\n\n```graphql\ntype Post @key(fields: \"id\") {\n  id: ID!\n  title: String!\n  body: String!\n  user: User\n}\n\nextend type User @key(fields: \"id\") {\n  id: ID! @external\n  posts: [Post]\n}\n\nextend type Query {\n  getPosts: [Post]\n}\n```\n\nOur resolver has one method of interest here: `getUser()`. It returns a reference containing `__typename` and any additional properties your application needs to resolve the reference, in this case only an `id`. The `__typename` is used by the GraphQL Gateway to pinpoint the microservice responsible for the User type and request the instance. The Users service discussed above will be called on the `resolveReference()` method.\n\n```typescript\nimport { Query, Resolver, Parent, ResolveField } from '@nestjs/graphql';\nimport { PostsService } from './posts.service';\nimport { Post } from './posts.interfaces';\n\n@Resolver('Post')\nexport class PostsResolvers {\n  constructor(private postsService: PostsService) {}\n\n  @Query('getPosts')\n  getPosts() {\n    return this.postsService.findAll();\n  }\n\n  @ResolveField('user')\n  getUser(@Parent() post: Post) {\n    return { __typename: 'User', id: post.userId };\n  }\n}\n```\n\nThe Posts service has virtually the same module, but is included below for the sake of completeness:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { GraphQLFederationModule } from '@nestjs/graphql';\nimport { PostsResolvers } from './posts.resolvers';\n\n@Module({\n  imports: [\n    GraphQLFederationModule.forRoot({\n      typePaths: ['**/*.graphql'],\n    }),\n  ],\n  providers: [PostsResolvers],\n})\nexport class AppModule {}\n```\n\n#### Code first\n\nWe will need to create a class representing our `User` entity. Even though it lives in another service, we will be using and extending it. Note the `@extends` and `@external` directives.\n\n```ts\nimport { Directive, ObjectType, Field, ID } from '@nestjs/graphql';\nimport { Post } from './post.entity';\n\n@ObjectType()\n@Directive('@extends')\n@Directive('@key(fields: \"id\")')\nexport class User {\n  @Field((type) => ID)\n  @Directive('@external')\n  id: number;\n\n  @Field((type) => [Post])\n  posts?: Post[];\n}\n```\n\nWe create the resolver for our extension on the `User` entity as follows:\n\n```ts\nimport { Parent, ResolveField, Resolver } from '@nestjs/graphql';\nimport { PostsService } from './posts.service';\nimport { Post } from './post.entity';\nimport { User } from './user.entity';\n\n@Resolver((of) => User)\nexport class UsersResolvers {\n  constructor(private readonly postsService: PostsService) {}\n\n  @ResolveField((of) => [Post])\n  public posts(@Parent() user: User): Post[] {\n    return this.postsService.forAuthor(user.id);\n  }\n}\n```\n\nWe also need to create our `Post` entity:\n\n```ts\nimport { Directive, Field, ID, Int, ObjectType } from '@nestjs/graphql';\nimport { User } from './user.entity';\n\n@ObjectType()\n@Directive('@key(fields: \"id\")')\nexport class Post {\n  @Field((type) => ID)\n  id: number;\n\n  @Field()\n  title: string;\n\n  @Field((type) => Int)\n  authorId: number;\n\n  @Field((type) => User)\n  user?: User;\n}\n```\n\nAnd its resolver:\n\n```ts\nimport { Query, Args, ResolveField, Resolver, Parent } from '@nestjs/graphql';\nimport { PostsService } from './posts.service';\nimport { Post } from './post.entity';\nimport { User } from './user.entity';\n\n@Resolver((of) => Post)\nexport class PostsResolvers {\n  constructor(private readonly postsService: PostsService) {}\n\n  @Query((returns) => Post)\n  findPost(@Args('id') id: number): Post {\n    return this.postsService.findOne(id);\n  }\n\n  @Query((returns) => [Post])\n  getPosts(): Post[] {\n    return this.postsService.all();\n  }\n\n  @ResolveField((of) => User)\n  user(@Parent() post: Post): any {\n    return { __typename: 'User', id: post.authorId };\n  }\n}\n```\n\nAnd finally, tie it together in a module. Note the schema build options, where we specify that `User` is an outside type.\n\n```ts\nimport { Module } from '@nestjs/common';\nimport { GraphQLFederationModule } from '@nestjs/graphql';\nimport { User } from './user.entity';\nimport { PostsResolvers } from './posts.resolvers';\nimport { UsersResolvers } from './users.resolvers';\nimport { PostsService } from './posts.service'; // Not included in example\n\n@Module({\n  imports: [\n    GraphQLFederationModule.forRoot({\n      autoSchemaFile: true,\n      buildSchemaOptions: {\n        orphanedTypes: [User],\n      },\n    }),\n  ],\n  providers: [PostsResolvers, UsersResolvers, PostsService],\n})\nexport class AppModule {}\n```\n\n#### Federated example: Gateway\n\nFirst, install the optional dependency for the gateway:\n\n```bash\n$ npm install --save @apollo/gateway\n```\n\nOur gateway only needs a list of endpoints and will auto-discover the schemas from there. Therefore it is the same for code and schema first, and the code for our gateway is very short:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { GraphQLGatewayModule } from '@nestjs/graphql';\n\n@Module({\n  imports: [\n    GraphQLGatewayModule.forRoot({\n      server: {\n        // ... Apollo server options\n        cors: true,\n      },\n      gateway: {\n        serviceList: [\n          { name: 'users', url: 'http://user-service/graphql' },\n          { name: 'posts', url: 'http://post-service/graphql' },\n        ],\n      },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n> info **Hint** Apollo recommends that you don't rely on the service discovery in a production environment but use their [Graph Manager](https://www.apollographql.com/docs/graph-manager/federation/) instead.\n\n#### Sharing context\n\nYou can customize the requests between the gateway and federated services using a build service. This allows you to share context about the request. You can easily extend the default `RemoteGraphQLDataSource` and implement one of the hooks. Please refer to [Apollo Docs](https://www.apollographql.com/docs/apollo-server/api/apollo-gateway/#remotegraphqldatasource) on `RemoteGraphQLDataSource` for more information about the possibilities.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { GATEWAY_BUILD_SERVICE, GraphQLGatewayModule } from '@nestjs/graphql';\nimport { RemoteGraphQLDataSource } from '@apollo/gateway';\nimport { decode } from 'jsonwebtoken';\n\nclass AuthenticatedDataSource extends RemoteGraphQLDataSource {\n  async willSendRequest({ request, context }) {\n    const { userId } = await decode(context.jwt);\n    request.http.headers.set('x-user-id', userId);\n  }\n}\n\n@Module({\n  providers: [\n    {\n      provide: AuthenticatedDataSource,\n      useValue: AuthenticatedDataSource,\n    },\n    {\n      provide: GATEWAY_BUILD_SERVICE,\n      useFactory: (AuthenticatedDataSource) => {\n        return ({ name, url }) => new AuthenticatedDataSource({ url });\n      },\n      inject: [AuthenticatedDataSource],\n    },\n  ],\n  exports: [GATEWAY_BUILD_SERVICE],\n})\nclass BuildServiceModule {}\n\n@Module({\n  imports: [\n    GraphQLGatewayModule.forRootAsync({\n      useFactory: async () => ({\n        gateway: {\n          serviceList: [\n            /* services */\n          ],\n        },\n        server: {\n          context: ({ req }) => ({\n            jwt: req.headers.authorization,\n          }),\n        },\n      }),\n      imports: [BuildServiceModule],\n      inject: [GATEWAY_BUILD_SERVICE],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n#### Async configuration\n\nBoth the Federation and Gateway modules support asynchronous initialization using the same `forRootAsync` that's documented in [Quick start](/graphql/quick-start#async-configuration).\n"
  },
  {
    "path": "content/graphql/field-middleware.md",
    "content": "### Field middleware\n\n> warning **Warning** This chapter applies only to the code first approach.\n\nField Middleware lets you run arbitrary code **before or after** a field is resolved. A field middleware can be used to convert the result of a field, validate the arguments of a field, or even check field-level roles (for example, required to access a target field for which a middleware function is executed).\n\nYou can connect multiple middleware functions to a field. In this case, they will be called sequentially along the chain where the previous middleware decides to call the next one. The order of the middleware functions in the `middleware` array is important. The first resolver is the \"most-outer\" layer, so it gets executed first and last (similarly to the `graphql-middleware` package). The second resolver is the \"second-outer\" layer, so it gets executed second and second to last.\n\n#### Getting started\n\nLet's start off by creating a simple middleware that will log a field value before it's sent back to the client:\n\n```typescript\nimport { FieldMiddleware, MiddlewareContext, NextFn } from '@nestjs/graphql';\n\nconst loggerMiddleware: FieldMiddleware = async (\n  ctx: MiddlewareContext,\n  next: NextFn,\n) => {\n  const value = await next();\n  console.log(value);\n  return value;\n};\n```\n\n> info **Hint** The `MiddlewareContext` is an object that consist of the same arguments that are normally received by the GraphQL resolver function (`{{ '{' }} source, args, context, info {{ '}' }}`), while `NextFn` is a function that let you execute the next middleware in the stack (bound to this field) or the actual field resolver.\n\n> warning **Warning** Field middleware functions cannot inject dependencies nor access Nest's DI container as they are designed to be very lightweight and shouldn't perform any potentially time-consuming operations (like retrieving data from the database). If you need to call external services/query data from the data source, you should do it in a guard/interceptor bounded to a root query/mutation handler and assign it to `context` object which you can access from within the field middleware (specifically, from the `MiddlewareContext` object).\n\nNote that field middleware must match the `FieldMiddleware` interface. In the example above, we first run the `next()` function (which executes the actual field resolver and returns a field value) and then, we log this value to our terminal. Also, the value returned from the middleware function completely overrides the previous value and since we don't want to perform any changes, we simply return the original value.\n\nWith this in place, we can register our middleware directly in the `@Field()` decorator, as follows:\n\n```typescript\n@ObjectType()\nexport class Recipe {\n  @Field({ middleware: [loggerMiddleware] })\n  title: string;\n}\n```\n\nNow whenever we request the `title` field of `Recipe` object type, the original field's value will be logged to the console.\n\n> info **Hint** To learn how you can implement a field-level permissions system with the use of [extensions](/graphql/extensions) feature, check out this [section](/graphql/extensions#using-custom-metadata).\n\nAlso, as mentioned above, we can control the field's value from within the middleware function. For demonstration purposes, let's capitalise a recipe's title (if present):\n\n```typescript\nconst value = await next();\nreturn value?.toUpperCase();\n```\n\nIn this case, every title will be automatically uppercased, when requested.\n\nLikewise, you can bind a field middleware to a custom field resolver (a method annotated with the `@ResolveField()` decorator), as follows:\n\n```typescript\n@ResolveField(() => String, { middleware: [loggerMiddleware] })\ntitle() {\n  return 'Placeholder';\n}\n```\n\n> warning **Warning** In case enhancers are enabled at the field resolver level ([read more](/graphl//other-features#execute-enhancers-at-the-field-resolver-level)), field middleware functions will run before any interceptors, guards, etc., **bounded to the method** (but after the root-level enhancers registered for query or mutation handlers).\n\n#### Global field middleware\n\nIn addition to binding a middleware directly to a specific field, you can also register one or multiple middleware functions globally. In this case, they will be automatically connected to all fields of your object types.\n\n```typescript\nGraphQLModule.forRoot({\n  autoSchemaFile: 'schema.gql',\n  buildSchemaOptions: {\n    fieldMiddleware: [loggerMiddleware],\n  },\n}),\n```\n\n> info **Hint** Globally registered field middleware functions will be executed **before** locally registered ones (those bound directly to specific fields).\n"
  },
  {
    "path": "content/graphql/guards-interceptors.md",
    "content": "### Other features\n\nIn the GraphQL world, there is a lot of debate about handling issues like **authentication**, or **side-effects** of operations. Should we handle things inside the business logic? Should we use a higher-order function to enhance queries and mutations with authorization logic? Or should we use [schema directives](https://www.apollographql.com/docs/apollo-server/schema/directives/)? There is no single one-size-fits-all answer to these questions.\n\nNest helps address these issues with its cross-platform features like [guards](/guards) and [interceptors](/interceptors). The philosophy is to reduce redundancy and provide tooling that helps create well-structured, readable, and consistent applications.\n\n#### Overview\n\nYou can use standard [guards](/guards), [interceptors](/interceptors), [filters](/exception-filters) and [pipes](/pipes) in the same fashion with GraphQL as with any RESTful application. Additionally, you can easily create your own decorators by leveraging the [custom decorators](/custom-decorators) feature. Let's take a look at a sample GraphQL query handler.\n\n```typescript\n@Query('author')\n@UseGuards(AuthGuard)\nasync getAuthor(@Args('id', ParseIntPipe) id: number) {\n  return this.authorsService.findOneById(id);\n}\n```\n\nAs you can see, GraphQL works with both guards and pipes in the same way as HTTP REST handlers. Because of this, you can move your authentication logic to a guard; you can even reuse the same guard class across both a REST and GraphQL API interface. Similarly, interceptors work across both types of applications in the same way:\n\n```typescript\n@Mutation()\n@UseInterceptors(EventsInterceptor)\nasync upvotePost(@Args('postId') postId: number) {\n  return this.postsService.upvoteById({ id: postId });\n}\n```\n\n#### Execution context\n\nSince GraphQL receives a different type of data in the incoming request, the [execution context](https://docs.nestjs.com/fundamentals/execution-context) received by both guards and interceptors is somewhat different with GraphQL vs. REST. GraphQL resolvers have a distinct set of arguments: `root`, `args`, `context`, and `info`. Thus guards and interceptors must transform the generic `ExecutionContext` to a `GqlExecutionContext`. This is straightforward:\n\n```typescript\nimport { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  canActivate(context: ExecutionContext): boolean {\n    const ctx = GqlExecutionContext.create(context);\n    return true;\n  }\n}\n```\n\nThe GraphQL context object returned by `GqlExecutionContext.create()` exposes a **get** method for each GraphQL resolver argument (e.g., `getArgs()`, `getContext()`, etc). Once transformed, we can easily pick out any GraphQL argument for the current request.\n\n#### Exception filters\n\nNest standard [exception filters](/exception-filters) are compatible with GraphQL applications as well. As with `ExecutionContext`, GraphQL apps should transform the `ArgumentsHost` object to a `GqlArgumentsHost` object.\n\n```typescript\n@Catch(HttpException)\nexport class HttpExceptionFilter implements GqlExceptionFilter {\n  catch(exception: HttpException, host: ArgumentsHost) {\n    const gqlHost = GqlArgumentsHost.create(host);\n    return exception;\n  }\n}\n```\n\n> info **Hint** Both `GqlExceptionFilter` and `GqlArgumentsHost` are imported from the `@nestjs/graphql` package.\n\nNote that unlike the REST case, you don't use the native `response` object to generate a response.\n\n#### Custom decorators\n\nAs mentioned, the [custom decorators](/custom-decorators) feature works as expected with GraphQL resolvers.\n\n```typescript\nexport const User = createParamDecorator(\n  (data: unknown, ctx: ExecutionContext) =>\n    GqlExecutionContext.create(ctx).getContext().user,\n);\n```\n\nUse the `@User()` custom decorator as follows:\n\n```typescript\n@Mutation()\nasync upvotePost(\n  @User() user: UserEntity,\n  @Args('postId') postId: number,\n) {}\n```\n\n> info **Hint** In the above example, we have assumed that the `user` object is assigned to the context of your GraphQL application.\n\n#### Execute enhancers at the field resolver level\n\nIn the GraphQL context, Nest does not run **enhancers** (the generic name for interceptors, guards and filters) at the field level [see this issue](https://github.com/nestjs/graphql/issues/320#issuecomment-511193229): they only run for the top level `@Query()`/`@Mutation()` method. You can tell Nest to execute interceptors, guards or filters for methods annotated with `@ResolveField()` by setting the `fieldResolverEnhancers` option in `GqlModuleOptions`.  Pass it a list of `'interceptors'`, `'guards'`, and/or `'filters'` as appropriate:\n\n```typescript\nGraphQLModule.forRoot({\n  fieldResolverEnhancers: ['interceptors']\n}),\n```\n\n> **Warning** Enabling enhancers for field resolvers can cause performance issues when you are returning lots of records and your field resolver is executed thousands of times. For this reason, when you enable `fieldResolverEnhancers`, we advise you to skip execution of enhancers that are not strictly necessary for your field resolvers. You can do this using the following helper function:\n\n```typescript\nexport function isResolvingGraphQLField(context: ExecutionContext): boolean {\n  if (context.getType<GqlContextType>() === 'graphql') {\n    const gqlContext = GqlExecutionContext.create(context);\n    const info = gqlContext.getInfo();\n    const parentType = info.parentType.name;\n    return parentType !== 'Query' && parentType !== 'Mutation';\n  }\n  return false;\n}\n```\n"
  },
  {
    "path": "content/graphql/interfaces.md",
    "content": "### Interfaces\n\nLike many type systems, GraphQL supports interfaces. An **Interface** is an abstract type that includes a certain set of fields that a type must include to implement the interface (read more [here](https://graphql.org/learn/schema/#interfaces)).\n\n#### Code first\n\nWhen using the code first approach, you define a GraphQL interface by creating an abstract class annotated with the `@InterfaceType()` decorator exported from the `@nestjs/graphql`.\n\n```typescript\nimport { Field, ID, InterfaceType } from '@nestjs/graphql';\n\n@InterfaceType()\nexport abstract class Character {\n  @Field(type => ID)\n  id: string;\n\n  @Field()\n  name: string;\n}\n```\n\n> warning **Warning** TypeScript interfaces cannot be used to define GraphQL interfaces.\n\nThis will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ninterface Character {\n  id: ID!\n  name: String!\n}\n```\n\nNow, to implement the `Character` interface, use the `implements` key:\n\n```typescript\n@ObjectType({\n  implements: () => [Character],\n})\nexport class Human implements Character {\n  id: string;\n  name: string;\n}\n```\n\n> info **Hint** The `@ObjectType()` decorator is exported from the `@nestjs/graphql` package.\n\nThe default `resolveType()` function generated by the library extracts the type based on the value returned from the resolver method. This means that you must return class instances (you cannot return literal JavaScript objects).\n\nTo provide a customized `resolveType()` function, pass the `resolveType` property to the options object passed into the `@InterfaceType()` decorator, as follows:\n\n```typescript\n@InterfaceType({\n  resolveType(book) {\n    if (book.colors) {\n      return ColoringBook;\n    }\n    return TextBook;\n  },\n})\nexport abstract class Book {\n  @Field(type => ID)\n  id: string;\n\n  @Field()\n  title: string;\n}\n```\n\n#### Schema first\n\nTo define an interface in the schema first approach, simply create a GraphQL interface with SDL.\n\n```graphql\ninterface Character {\n  id: ID!\n  name: String!\n}\n```\n\nThen, you can use the typings generation feature (as shown in the [quick start](/graphql/quick-start) chapter) to generate corresponding TypeScript definitions:\n\n```typescript\nexport interface Character {\n  id: string;\n  name: string;\n}\n```\n\nInterfaces require an extra `__resolveType` field in the resolver map to determine which type the interface should resolve to. Let's create a `CharactersResolver` class and define the `__resolveType` method:\n\n```typescript\n@Resolver('Character')\nexport class CharactersResolver {\n  @ResolveField()\n  __resolveType(value) {\n    if ('age' in value) {\n      return Person;\n    }\n    return null;\n  }\n}\n```\n\n> info **Hint** All decorators are exported from the `@nestjs/graphql` package.\n"
  },
  {
    "path": "content/graphql/mapped-types.md",
    "content": "### Mapped types\n\n> warning **Warning** This chapter applies only to the code first approach.\n\nAs you build out features like CRUD (Create/Read/Update/Delete) it's often useful to construct variants on a base entity type. Nest provides several utility functions that perform type transformations to make this task more convenient.\n\n#### Partial\n\nWhen building input validation types (also called DTOs), it's often useful to build **create** and **update** variations on the same type. For example, the **create** variant may require all fields, while the **update** variant may make all fields optional.\n\nNest provides the `PartialType()` utility function to make this task easier and minimize boilerplate.\n\nThe `PartialType()` function returns a type (class) with all the properties of the input type set to optional. For example, suppose we have a **create** type as follows:\n\n```typescript\n@InputType()\nclass CreateUserInput {\n  @Field()\n  email: string;\n\n  @Field()\n  password: string;\n\n  @Field()\n  firstName: string;\n}\n```\n\nBy default, all of these fields are required. To create a type with the same fields, but with each one optional, use `PartialType()` passing the class reference (`CreateUserInput`) as an argument:\n\n```typescript\n@InputType()\nexport class UpdateUserInput extends PartialType(CreateUserInput) {}\n```\n\n> info **Hint** The `PartialType()` function is imported from the `@nestjs/graphql` package.\n\nThe `PartialType()` function takes an optional second argument that is a reference to a decorator factory.  This argument can be used to change the decorator function applied to the resulting (child) class.  If not specified, the child class effectively uses the same decorator as the **parent** class (the class referenced in the first argument). In the example above, we are extending `CreateUserInput` which is annotated with the `@InputType()` decorator.  Since we want `UpdateUserInput` to also be treated as if it were decorated with `@InputType()`, we didn't need to pass `InputType` as the second argument. If the parent and child types are different, (e.g., the parent is decorated with `@ObjectType`), we would  pass `InputType` as the second argument. For example:\n\n```typescript\n@InputType()\nexport class UpdateUserInput extends PartialType(User, InputType) {}\n```\n\n#### Pick\n\nThe `PickType()` function constructs a new type (class) by picking a set of properties from an input type. For example, suppose we start with a type like:\n\n```typescript\n@InputType()\nclass CreateUserInput {\n  @Field()\n  email: string;\n\n  @Field()\n  password: string;\n\n  @Field()\n  firstName: string;\n}\n```\n\nWe can pick a set of properties from this class using the `PickType()` utility function:\n\n```typescript\n@InputType()\nexport class UpdateEmailInput extends PickType(CreateUserInput, ['email'] as const) {}\n```\n\n> info **Hint** The `PickType()` function is imported from the `@nestjs/graphql` package.\n\n#### Omit\n\nThe `OmitType()` function constructs a type by picking all properties from an input type and then removing a particular set of keys. For example, suppose we start with a type like:\n\n```typescript\n@InputType()\nclass CreateUserInput {\n  @Field()\n  email: string;\n\n  @Field()\n  password: string;\n\n  @Field()\n  firstName: string;\n}\n```\n\nWe can generate a derived type that has every property **except** `email` as shown below. In this construct, the second argument to `OmitType` is an array of property names.\n\n```typescript\n@InputType()\nexport class UpdateUserInput extends OmitType(CreateUserInput, ['email'] as const) {}\n```\n\n> info **Hint** The `OmitType()` function is imported from the `@nestjs/graphql` package.\n\n#### Intersection\n\nThe `IntersectionType()` function combines two types into one new type (class). For example, suppose we start with two types like:\n\n```typescript\n@InputType()\nclass CreateUserInput {\n  @Field()\n  email: string;\n\n  @Field()\n  password: string;\n}\n\n@ObjectType()\nexport class AdditionalUserInfo {\n  @Field()\n  firstName: string;\n  \n  @Field()\n  lastName: string;\n}\n```\n\nWe can generate a new type that combines all properties in both types.\n\n```typescript\n@InputType()\nexport class UpdateUserInput extends IntersectionType(CreateUserInput, AdditionalUserInfo) {}\n```\n\n> info **Hint** The `IntersectionType()` function is imported from the `@nestjs/graphql` package.\n\n#### Composition\n\nThe type mapping utility functions are composable. For example, the following will produce a type (class) that has all of the properties of the `CreateUserInput` type except for `email`, and those properties will be set to optional:\n\n```typescript\n@InputType()\nexport class UpdateUserInput extends PartialType(\n  OmitType(CreateUserInput, ['email'] as const),\n) {}\n```\n"
  },
  {
    "path": "content/graphql/mutations.md",
    "content": "### Mutations\n\nMost discussions of GraphQL focus on data fetching, but any complete data platform needs a way to modify server-side data as well. In REST, any request could end up causing side-effects on the server, but best practice suggests we should not modify data in GET requests. GraphQL is similar - technically any query could be implemented to cause a data write. However, like REST, it's recommended to observe the convention that any operations that cause writes should be sent explicitly via a mutation (read more [here](https://graphql.org/learn/queries/#mutations)).\n\nThe official [Apollo](https://www.apollographql.com/docs/graphql-tools/generate-schema.html) documentation uses an `upvotePost()` mutation example. This mutation implements a method to increase a post's `votes` property value. To create an equivalent mutation in Nest, we'll make use of the `@Mutation()` decorator.\n\n#### Code first\n\nLet's add another method to the `AuthorResolver` used in the previous section (see [resolvers](/graphql/resolvers)).\n\n```typescript\n@Mutation(returns => Post)\nasync upvotePost(@Args({ name: 'postId', type: () => Int }) postId: number) {\n  return this.postsService.upvoteById({ id: postId });\n}\n```\n\n> info **Hint** All decorators (e.g., `@Resolver`, `@ResolveField`, `@Args`, etc.) are exported from the `@nestjs/graphql` package.\n\nThis will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ntype Mutation {\n  upvotePost(postId: Int!): Post\n}\n```\n\nThe `upvotePost()` method takes `postId` (`Int`) as an argument and returns an updated `Post` entity. For the reasons explained in the [resolvers](/graphql/resolvers) section, we have to explicitly set the expected type.\n\nIf the mutation needs to take an object as an argument, we can create an **input type**. The input type is a special kind of object type that can be passed in as an argument (read more [here](https://graphql.org/learn/schema/#input-types)). To declare an input type, use the `@InputType()` decorator.\n\n```typescript\nimport { InputType, Field } from '@nestjs/graphql';\n\n@InputType()\nexport class UpvotePostInput {\n  @Field()\n  postId: number;\n}\n```\n\n> info **Hint** The `@InputType()` decorator takes an options object as an argument, so you can, for example, specify the input type's description. Note that, due to TypeScript's metadata reflection system limitations, you must either use the `@Field` decorator to manually indicate a type, or use a [CLI plugin](/graphql/cli-plugin).\n\nWe can then use this type in the resolver class:\n\n```typescript\n@Mutation(returns => Post)\nasync upvotePost(\n  @Args('upvotePostData') upvotePostData: UpvotePostInput,\n) {}\n```\n\n#### Schema first\n\nLet's extend our `AuthorResolver` used in the previous section (see [resolvers](/graphql/resolvers)).\n\n```typescript\n@Mutation()\nasync upvotePost(@Args('postId') postId: number) {\n  return this.postsService.upvoteById({ id: postId });\n}\n```\n\nNote that we assumed above that the business logic has been moved to the `PostsService` (querying the post and incrementing its `votes` property). The logic inside the `PostsService` class can be as simple or sophisticated as needed. The main point of this example is to show how resolvers can interact with other providers.\n\nThe last step is to add our mutation to the existing types definition.\n\n```graphql\ntype Author {\n  id: Int!\n  firstName: String\n  lastName: String\n  posts: [Post]\n}\n\ntype Post {\n  id: Int!\n  title: String\n  votes: Int\n}\n\ntype Query {\n  author(id: Int!): Author\n}\n\ntype Mutation {\n  upvotePost(postId: Int!): Post\n}\n```\n\nThe `upvotePost(postId: Int!): Post` mutation is now available to be called as part of our application's GraphQL API.\n"
  },
  {
    "path": "content/graphql/plugins.md",
    "content": "### Plugins\n\nPlugins enable you to extend Apollo Server's core functionality by performing custom operations in response to certain events. Currently, these events correspond to individual phases of the GraphQL request lifecycle, and to the startup of Apollo Server itself (read more [here](https://www.apollographql.com/docs/apollo-server/integrations/plugins/)). For example, a basic logging plugin might log the GraphQL query string associated with each request that's sent to Apollo Server.\n\n#### Custom plugins\n\nTo create a plugin, declare a class annotated with the `@Plugin` decorator exported from the `@nestjs/graphql` package. Also, for better code autocompletion, implement the `ApolloServerPlugin` interface from the `apollo-server-plugin-base` package.\n\n```typescript\nimport { Plugin } from '@nestjs/graphql';\nimport {\n  ApolloServerPlugin,\n  GraphQLRequestListener,\n} from 'apollo-server-plugin-base';\n\n@Plugin()\nexport class LoggingPlugin implements ApolloServerPlugin {\n  async requestDidStart(): Promise<GraphQLRequestListener> {\n    console.log('Request started');\n    return {\n      async willSendResponse() {\n        console.log('Will send response');\n      },\n    };\n  }\n}\n```\n\nWith this in place, we can register the `LoggingPlugin` as a provider.\n\n```typescript\n@Module({\n  providers: [LoggingPlugin],\n})\nexport class CommonModule {}\n```\n\nNest will automatically instantiate a plugin and apply it to the Apollo Server.\n\n#### Using external plugins\n\nThere are several plugins provided out-of-the-box. To use an existing plugin, simply import it and add it to the `plugins` array:\n\n```typescript\nGraphQLModule.forRoot({\n  // ...\n  plugins: [ApolloServerOperationRegistry({ /* options */})]\n}),\n```\n\n> info **Hint** The `ApolloServerOperationRegistry` plugin is exported from the `apollo-server-plugin-operation-registry` package.\n"
  },
  {
    "path": "content/graphql/quick-start.md",
    "content": "## TypeScript와 GraphQL의 강력한 기능 활용\n\n[GraphQL](https://graphql.org/) 은 API를 위한 강력한 쿼리 언어이며 기존 데이터로 쿼리를 수행할 수 있는 런타임입니다. GraphQL은 REST APIs 에서 흔히 발견되는 여러 문제들을 해결하는 우아한 접근 방식입니다. 배경지식을 위해 GraphQL과 REST를 [비교](https://dev-blog.apollodata.com/graphql-vs-rest-5d425123e34b)해 보는 것을 권장합니다. [TypeScript](https://www.typescriptlang.org/)와 결합된 GraphQL은 GraphQL query로 더 나은 type safety한 개발을 도와주고 종단 간 typing을 제공합니다.\n\n이번 챕터에서는 GraphQL에 대한 기본적인 이해를 가정하고 내장된 `@nestjs/graphql` 모듈로 작업하는 방법에 초점을 두겠습니다. `GraphQLModule`은 [Apollo](https://www.apollographql.com/) Server 로 이루어져 있습니다. 이러한 검증된 GraphQL package를 사용하여 Nest에서 GraphQL을 사용하는 방법에 대해 알아 보겠습니다.\n\n#### 설치\n\n필요한 패키지를 설치하는 것부터 시작합니다:\n\n```bash\n$ npm i @nestjs/graphql graphql@^15 apollo-server-express\n```\n\n> info **Hint** Fastify를 쓰고 있다면 `apollo-server-express` 대신 `apollo-server-fastify`를 설치하세요.\n\n> warning **Warning** `@nestjs/graphql@^9`는 **Apollo v3**(자세한 내용은 Apollo Server 3 [migration guide](https://www.apollographql.com/docs/apollo-server/migration/) 참조)과 호환되지만 `@nestjs/graphql@^8`은 **Apollo v2** (예: `apollo-server-express@2.x.x` package)만 지원합니다. 두 버전(v9 및 v8) 모두 Nest v8(`@nestjs/common@^8`, `@nestjs/core@^8` 등)과 완전히 호환됩니다.\n\n#### 개요\n\nNest는 GraphQL applications을 구축하는 두 가지 방법 즉, **code first**와 **schema first**를 제공합니다. 당신에게 가장 적합한 방법을 선택해야 합니다. 이 GraphQL 섹션의 중 대부분 챕터들은 오직 두 main part로 나뉘어 져 있습니다. 하나는 코드를 먼저 채택하는 경우 **code first** 방법을 따르고, 다른 하나는 스키마를 먼저 채택하는 경우 **schema first**를 사용해야 합니다.\n\n**code first** 접근법에서는 데코레이터 및 TypeScript 클래스를 사용하여 해당하는 GraphQL 스키마를 생성합니다. 이 방법은 TypeScript로만 작업하고 언어 구문 간의 context switching을 피하려는 경우 유용합니다.\n\n**schema first** 접근법에서 진실된 source는 GraphQL SDL(Schema Definition Language) 파일입니다. SDL은 서로 다른 플랫폼 간에 스키마 파일을 공유할 수 있는 language-agnostic한 방법입니다. Nest는 GraphQL schema를 기반으로 TypeScript definitions(클래스나 인터페이스를 사용하여)를 자동으로 생성하여 중복된 boilerplate code 작성할 필요성을 줄입니다.\n\n#### Getting started with GraphQL & TypeScript\n\nOnce the packages are installed, we can import the `GraphQLModule` and configure it with the `forRoot()` static method.\n\n```typescript\n@@filename()\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({}),\n  ],\n})\nexport class AppModule {}\n```\n\nThe `forRoot()` method takes an options object as an argument. These options are passed through to the underlying Apollo instance (read more about available settings [here](https://www.apollographql.com/docs/apollo-server/v2/api/apollo-server.html#constructor-options-lt-ApolloServer-gt)). For example, if you want to disable the `playground` and turn off `debug` mode, pass the following options:\n\n```typescript\n@@filename()\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      debug: false,\n      playground: false,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nAs mentioned, these options will be forwarded to the `ApolloServer` constructor.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### GraphQL playground\n\nThe playground is a graphical, interactive, in-browser GraphQL IDE, available by default on the same URL as the GraphQL server itself. To access the playground, you need a basic GraphQL server configured and running. To see it now, you can install and build the [working example here](https://github.com/nestjs/nest/tree/master/sample/23-graphql-code-first). Alternatively, if you're following along with these code samples, once you've completed the steps in the [Resolvers chapter](/graphql/resolvers-map), you can access the playground.\n\nWith that in place, and with your application running in the background, you can then open your web browser and navigate to `http://localhost:3000/graphql` (host and port may vary depending on your configuration). You will then see the GraphQL playground, as shown below.\n\n<figure>\n  <img src=\"/assets/playground.png\" alt=\"\" />\n</figure>\n\n#### Multiple endpoints\n\nAnother useful feature of the `@nestjs/graphql` module is the ability to serve multiple endpoints at once. This lets you decide which modules should be included in which endpoint. By default, `GraphQL` searches for resolvers throughout the whole app. To limit this scan to only a subset of modules, use the `include` property.\n\n```typescript\nGraphQLModule.forRoot({\n  include: [CatsModule],\n}),\n```\n\n> warning **Warning** If you use the `apollo-server-fastify` package with multiple GraphQL endpoints in a single application, make sure to enable the `disableHealthCheck` setting in the `GraphQLModule` configuration.\n\n#### Code first\n\nIn the **code first** approach, you use decorators and TypeScript classes to generate the corresponding GraphQL schema.\n\nTo use the code first approach, start by adding the `autoSchemaFile` property to the options object:\n\n```typescript\nGraphQLModule.forRoot({\n  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n}),\n```\n\nThe `autoSchemaFile` property value is the path where your automatically generated schema will be created. Alternatively, the schema can be generated on-the-fly in memory. To enable this, set the `autoSchemaFile` property to `true`:\n\n```typescript\nGraphQLModule.forRoot({\n  autoSchemaFile: true,\n}),\n```\n\nBy default, the types in the generated schema will be in the order they are defined in the included modules. To sort the schema lexicographically, set the `sortSchema` property to `true`:\n\n```typescript\nGraphQLModule.forRoot({\n  autoSchemaFile: join(process.cwd(), 'src/schema.gql'),\n  sortSchema: true,\n}),\n```\n\n#### Example\n\nA fully working code first sample is available [here](https://github.com/nestjs/nest/tree/master/sample/23-graphql-code-first).\n\n#### Schema first\n\nTo use the schema first approach, start by adding a `typePaths` property to the options object. The `typePaths` property indicates where the `GraphQLModule` should look for GraphQL SDL schema definition files you'll be writing. These files will be combined in memory; this allows you to split your schemas into several files and locate them near their resolvers.\n\n```typescript\nGraphQLModule.forRoot({\n  typePaths: ['./**/*.graphql'],\n}),\n```\n\nYou will typically also need to have TypeScript definitions (classes and interfaces) that correspond to the GraphQL SDL types. Creating the corresponding TypeScript definitions by hand is redundant and tedious. It leaves us without a single source of truth -- each change made within SDL forces us to adjust TypeScript definitions as well. To address this, the `@nestjs/graphql` package can **automatically generate** TypeScript definitions from the abstract syntax tree ([AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree)). To enable this feature, add the `definitions` options property when configuring the `GraphQLModule`.\n\n```typescript\nGraphQLModule.forRoot({\n  typePaths: ['./**/*.graphql'],\n  definitions: {\n    path: join(process.cwd(), 'src/graphql.ts'),\n  },\n}),\n```\n\nThe path property of the `definitions` object indicates where to save generated TypeScript output. By default, all generated TypeScript types are created as interfaces. To generate classes instead, specify the `outputAs` property with a value of `'class'`.\n\n```typescript\nGraphQLModule.forRoot({\n  typePaths: ['./**/*.graphql'],\n  definitions: {\n    path: join(process.cwd(), 'src/graphql.ts'),\n    outputAs: 'class',\n  },\n}),\n```\n\nThe above approach dynamically generates TypeScript definitions each time the application starts. Alternatively, it may be preferable to build a simple script to generate these on demand. For example, assume we create the following script as `generate-typings.ts`:\n\n```typescript\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory();\ndefinitionsFactory.generate({\n  typePaths: ['./src/**/*.graphql'],\n  path: join(process.cwd(), 'src/graphql.ts'),\n  outputAs: 'class',\n});\n```\n\nNow you can run this script on demand:\n\n```bash\n$ ts-node generate-typings\n```\n\n> info **Hint** You can compile the script beforehand (e.g., with `tsc`) and use `node` to execute it.\n\nTo enable watch mode for the script (to automatically generate typings whenever any `.graphql` file changes), pass the `watch` option to the `generate()` method.\n\n```typescript\ndefinitionsFactory.generate({\n  typePaths: ['./src/**/*.graphql'],\n  path: join(process.cwd(), 'src/graphql.ts'),\n  outputAs: 'class',\n  watch: true,\n});\n```\n\nTo automatically generate the additional `__typename` field for every object type, enable the `emitTypenameField` option.\n\n```typescript\ndefinitionsFactory.generate({\n  // ...,\n  emitTypenameField: true,\n});\n```\n\nTo generate resolvers (queries, mutations, subscriptions) as plain fields without arguments, enable the `skipResolverArgs` option.\n\n```typescript\ndefinitionsFactory.generate({\n  // ...,\n  skipResolverArgs: true,\n});\n```\n\n#### Apollo Sandbox\n\nTo use [Apollo Sandbox](https://www.apollographql.com/blog/announcement/platform/apollo-sandbox-an-open-graphql-ide-for-local-development/) instead of the `graphql-playground` as a GraphQL IDE for local development, use the following configuration:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloServerPluginLandingPageLocalDefault } from 'apollo-server-core';\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      playground: false,\n      plugins: [ApolloServerPluginLandingPageLocalDefault()],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n#### Example\n\nA fully working schema first sample is available [here](https://github.com/nestjs/nest/tree/master/sample/12-graphql-schema-first).\n\n#### Accessing generated schema\n\nIn some circumstances (for example end-to-end tests), you may want to get a reference to the generated schema object. In end-to-end tests, you can then run queries using the `graphql` object without using any HTTP listeners.\n\nYou can access the generated schema (in either the code first or schema first approach), using the `GraphQLSchemaHost` class:\n\n```typescript\nconst { schema } = app.get(GraphQLSchemaHost);\n```\n\n> info **Hint** You must call the `GraphQLSchemaHost#schema` getter after the application has been initialized (after the `onModuleInit` hook has been triggered by either the `app.listen()` or `app.init()` method).\n\n#### Async configuration\n\nWhen you need to pass module options asynchronously instead of statically, use the `forRootAsync()` method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.\n\nOne technique is to use a factory function:\n\n```typescript\nGraphQLModule.forRootAsync({\n  useFactory: () => ({\n    typePaths: ['./**/*.graphql'],\n  }),\n}),\n```\n\nLike other factory providers, our factory function can be <a href=\"https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory\">async</a> and can inject dependencies through `inject`.\n\n```typescript\nGraphQLModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    typePaths: configService.getString('GRAPHQL_TYPE_PATHS'),\n  }),\n  inject: [ConfigService],\n}),\n```\n\nAlternatively, you can configure the `GraphQLModule` using a class instead of a factory, as shown below:\n\n```typescript\nGraphQLModule.forRootAsync({\n  useClass: GqlConfigService,\n}),\n```\n\nThe construction above instantiates `GqlConfigService` inside `GraphQLModule`, using it to create options object. Note that in this example, the `GqlConfigService` has to implement the `GqlOptionsFactory` interface, as shown below. The `GraphQLModule` will call the `createGqlOptions()` method on the instantiated object of the supplied class.\n\n```typescript\n@Injectable()\nclass GqlConfigService implements GqlOptionsFactory {\n  createGqlOptions(): GqlModuleOptions {\n    return {\n      typePaths: ['./**/*.graphql'],\n    };\n  }\n}\n```\n\nIf you want to reuse an existing options provider instead of creating a private copy inside the `GraphQLModule`, use the `useExisting` syntax.\n\n```typescript\nGraphQLModule.forRootAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n}),\n```\n"
  },
  {
    "path": "content/graphql/resolvers-map.md",
    "content": "### Resolvers\n\nResolvers provide the instructions for turning a [GraphQL](https://graphql.org/) operation (a query, mutation, or subscription) into data. They return the same shape of data we specify in our schema -- either synchronously or as a promise that resolves to a result of that shape. Typically, you create a **resolver map** manually. The `@nestjs/graphql` package, on the other hand, generates a resolver map automatically using the metadata provided by decorators you use to annotate classes. To demonstrate the process of using the package features to create a GraphQL API, we'll create a simple authors API.\n\n#### Code first\n\nIn the code first approach, we don't follow the typical process of creating our GraphQL schema by writing GraphQL SDL by hand. Instead, we use TypeScript decorators to generate the SDL from TypeScript class definitions. The `@nestjs/graphql` package reads the metadata defined through the decorators and automatically generates the schema for you.\n\n#### Object types\n\nMost of the definitions in a GraphQL schema are **object types**. Each object type you define should represent a domain object that an application client might need to interact with. For example, our sample API needs to be able to fetch a list of authors and their posts, so we should define the `Author` type and `Post` type to support this functionality.\n\nIf we were using the schema first approach, we'd define such a schema with SDL like this:\n\n```graphql\ntype Author {\n  id: Int!\n  firstName: String\n  lastName: String\n  posts: [Post!]!\n}\n```\n\nIn this case, using the code first approach, we define schemas using TypeScript classes and using TypeScript decorators to annotate the fields of those classes. The equivalent of the above SDL in the code first approach is:\n\n```typescript\n@@filename(authors/models/author.model)\nimport { Field, Int, ObjectType } from '@nestjs/graphql';\nimport { Post } from './post';\n\n@ObjectType()\nexport class Author {\n  @Field(type => Int)\n  id: number;\n\n  @Field({ nullable: true })\n  firstName?: string;\n\n  @Field({ nullable: true })\n  lastName?: string;\n\n  @Field(type => [Post])\n  posts: Post[];\n}\n```\n\n> info **Hint** TypeScript's metadata reflection system has several limitations which make it impossible, for instance, to determine what properties a class consists of or recognize whether a given property is optional or required. Because of these limitations, we must either explicitly use the `@Field()` decorator in our schema definition classes to provide metadata about each field's GraphQL type and optionality, or use a [CLI plugin](/graphql/cli-plugin) to generate these for us.\n\nThe `Author` object type, like any class, is made of a collection of fields, with each field declaring a type. A field's type corresponds to a [GraphQL type](https://graphql.org/learn/schema/). A field's GraphQL type can be either another object type or a scalar type. A GraphQL scalar type is a primitive (like `ID`, `String`, `Boolean`, or `Int`) that resolves to a single value.\n\n> info **Hint** In addition to GraphQL's built-in scalar types, you can define custom scalar types (read [more](/graphql/scalars)).\n\nThe above `Author` object type definition will cause Nest to **generate** the SDL we showed above:\n\n```graphql\ntype Author {\n  id: Int!\n  firstName: String\n  lastName: String\n  posts: [Post!]!\n}\n```\n\nThe `@Field()` decorator accepts an optional type function (e.g., `type => Int`), and optionally an options object.\n\nThe type function is required when there's the potential for ambiguity between the TypeScript type system and the GraphQL type system. Specifically: it is **not** required for `string` and `boolean` types; it **is** required for `number` (which must be mapped to either a GraphQL `Int` or `Float`). The type function should simply return the desired GraphQL type (as shown in various examples in these chapters).\n\nThe options object can have any of the following key/value pairs:\n\n- `nullable`: for specifying whether a field is nullable (in SDL, each field is non-nullable by default); `boolean`\n- `description`: for setting a field description; `string`\n- `deprecationReason`: for marking a field as deprecated; `string`\n\nFor example:\n\n```typescript\n@Field({ description: `Book title`, deprecationReason: 'Not useful in v2 schema' })\ntitle: string;\n```\n\n> info **Hint** You can also add a description to, or deprecate, the whole object type: `@ObjectType({{ '{' }} description: 'Author model' {{ '}' }})`.\n\nWhen the field is an array, we must manually indicate the array type in the `Field()` decorator's type function, as shown below:\n\n```typescript\n@Field(type => [Post])\nposts: Post[];\n```\n\n> info **Hint** Using array bracket notation (`[ ]`), we can indicate the depth of the array. For example, using `[[Int]]` would represent an integer matrix.\n\nTo declare that an array's items (not the array itself) are nullable, set the `nullable` property to `'items'` as shown below:\n\n```typescript\n@Field(type => [Post], { nullable: 'items' })\nposts: Post[];\n```\n\n> info **Hint** If both the array and its items are nullable, set `nullable` to `'itemsAndList'` instead.\n\nNow that the `Author` object type is created, let's define the `Post` object type.\n\n```typescript\n@@filename(posts/models/post.model)\nimport { Field, Int, ObjectType } from '@nestjs/graphql';\n\n@ObjectType()\nexport class Post {\n  @Field(type => Int)\n  id: number;\n\n  @Field()\n  title: string;\n\n  @Field(type => Int, { nullable: true })\n  votes?: number;\n}\n```\n\nThe `Post` object type will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ntype Post {\n  id: Int!\n  title: String!\n  votes: Int\n}\n```\n\n#### Code first resolver\n\nAt this point, we've defined the objects (type definitions) that can exist in our data graph, but clients don't yet have a way to interact with those objects. To address that, we need to create a resolver class. In the code first method, a resolver class both defines resolver functions **and** generates the **Query type**. This will be clear as we work through the example below:\n\n```typescript\n@@filename(authors/authors.resolver)\n@Resolver(of => Author)\nexport class AuthorsResolver {\n  constructor(\n    private authorsService: AuthorsService,\n    private postsService: PostsService,\n  ) {}\n\n  @Query(returns => Author)\n  async author(@Args('id', { type: () => Int }) id: number) {\n    return this.authorsService.findOneById(id);\n  }\n\n  @ResolveField()\n  async posts(@Parent() author: Author) {\n    const { id } = author;\n    return this.postsService.findAll({ authorId: id });\n  }\n}\n```\n\n\n> info **Hint** All decorators (e.g., `@Resolver`, `@ResolveField`, `@Args`, etc.) are exported from the `@nestjs/graphql` package.\n\nYou can define multiple resolver classes. Nest will combine these at run time. See the [module](/graphql/resolvers#module) section below for more on code organization.\n\n> warning **Note** The logic inside the `AuthorsService` and `PostsService` classes can be as simple or sophisticated as needed. The main point of this example is to show how to construct resolvers and how they can interact with other providers.\n\nIn the example above, we created the `AuthorsResolver` which defines one query resolver function and one field resolver function. To create a resolver, we create a class with resolver functions as methods, and annotate the class with the `@Resolver()` decorator.\n\nIn this example, we defined a query handler to get the author object based on the `id` sent in the request. To specify that the method is a query handler, use the `@Query()` decorator.\n\nThe argument passed to the `@Resolver()` decorator is optional, but comes into play when our graph becomes non-trivial. It's used to supply a parent object used by field resolver functions as they traverse down through an object graph.\n\nIn our example, since the class includes a **field resolver** function (for the `posts` property of the `Author` object type), we **must** supply the `@Resolver()` decorator with a value to indicate which class is the parent type (i.e., the corresponding `ObjectType` class name) for all field resolvers defined within this class. As should be clear from the example, when writing a field resolver function, it's necessary to access the parent object (the object the field being resolved is a member of). In this example, we populate an author's posts array with a field resolver that calls a service which takes the author's `id` as an argument. Hence the need to identify the parent object in the `@Resolver()` decorator. Note the corresponding use of the `@Parent()` method parameter decorator to then extract a reference to that parent object in the field resolver.\n\nWe can define multiple `@Query()` resolver functions (both within this class, and in any other resolver class), and they will be aggregated into a single **Query type** definition in the generated SDL along with the appropriate entries in the resolver map. This allows you to define queries close to the models and services that they use, and to keep them well organized in modules.\n\n> info **Hint** Nest CLI provides a generator (schematic) that automatically generates **all the boilerplate code** to help us avoid doing all of this, and make the developer experience much simpler. Read more about this feature [here](/recipes/crud-generator).\n\n#### Query type names\n\nIn the above examples, the `@Query()` decorator generates a GraphQL schema query type name based on the method name. For example, consider the following construction from the example above:\n\n```typescript\n@Query(returns => Author)\nasync author(@Args('id', { type: () => Int }) id: number) {\n  return this.authorsService.findOneById(id);\n}\n```\n\nThis generates the following entry for the author query in our schema (the query type uses the same name as the method name):\n\n```graphql\ntype Query {\n  author(id: Int!): Author\n}\n```\n\n> info **Hint** Learn more about GraphQL queries [here](https://graphql.org/learn/queries/).\n\nConventionally, we prefer to decouple these names; for example, we prefer to use a name like `getAuthor()` for our query handler method, but still use `author` for our query type name. The same applies to our field resolvers. We can easily do this by passing the mapping names as arguments of the `@Query()` and `@ResolveField()` decorators, as shown below:\n\n```typescript\n@@filename(authors/authors.resolver)\n@Resolver(of => Author)\nexport class AuthorsResolver {\n  constructor(\n    private authorsService: AuthorsService,\n    private postsService: PostsService,\n  ) {}\n\n  @Query(returns => Author, { name: 'author' })\n  async getAuthor(@Args('id', { type: () => Int }) id: number) {\n    return this.authorsService.findOneById(id);\n  }\n\n  @ResolveField('posts', returns => [Post])\n  async getPosts(@Parent() author: Author) {\n    const { id } = author;\n    return this.postsService.findAll({ authorId: id });\n  }\n}\n```\n\nThe `getAuthor` handler method above will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ntype Query {\n  author(id: Int!): Author\n}\n```\n\n#### Query decorator options\n\nThe `@Query()` decorator's options object (where we pass `{{ '{' }}name: 'author'{{ '}' }}` above) accepts a number of key/value pairs:\n\n- `name`: name of the query; a `string`\n- `description`: a description that will be used to generate GraphQL schema documentation (e.g., in GraphQL playground); a `string`\n- `deprecationReason`: sets query metadata to show the query as deprecated (e.g., in GraphQL playground); a `string`\n- `nullable`: whether the query can return a null data response; `boolean` or `'items'` or `'itemsAndList'` (see above for details of `'items'` and `'itemsAndList'`)\n\n#### Args decorator options\n\nUse the `@Args()` decorator to extract arguments from a request for use in the method handler. This works in a very similar fashion to [REST route parameter argument extraction](/controllers#route-parameters).\n\nUsually your `@Args()` decorator will be simple, and not require an object argument as seen with the `getAuthor()` method above. For example, if the type of an identifier is string, the following construction is sufficient, and simply plucks the named field from the inbound GraphQL request for use as a method argument.\n\n```typescript\n@Args('id') id: string\n```\n\nIn the `getAuthor()` case, the `number` type is used, which presents a challenge. The `number` TypeScript type doesn't give us enough information about the expected GraphQL representation (e.g., `Int` vs. `Float`). Thus we have to **explicitly** pass the type reference. We do that by passing a second argument to the `Args()` decorator, containing argument options, as shown below:\n\n```typescript\n@Query(returns => Author, { name: 'author' })\nasync getAuthor(@Args('id', { type: () => Int }) id: number) {\n  return this.authorsService.findOneById(id);\n}\n```\n\nThe options object allows us to specify the following optional key value pairs:\n\n- `type`: a function returning the GraphQL type\n- `defaultValue`: a default value; `any`\n- `description`: description metadata; `string`\n- `deprecationReason`: to deprecate a field and provide meta data describing why; `string`\n- `nullable`: whether the field is nullable\n\nQuery handler methods can take multiple arguments. Let's imagine that we want to fetch an author based on its `firstName` and `lastName`. In this case, we can call `@Args` twice:\n\n```typescript\ngetAuthor(\n  @Args('firstName', { nullable: true }) firstName?: string,\n  @Args('lastName', { defaultValue: '' }) lastName?: string,\n) {}\n```\n\n#### Dedicated arguments class\n\nWith inline `@Args()` calls, code like the example above becomes bloated. Instead, you can create a dedicated `GetAuthorArgs` arguments class and access it in the handler method as follows:\n\n```typescript\n@Args() args: GetAuthorArgs\n```\n\nCreate the `GetAuthorArgs` class using `@ArgsType()` as shown below:\n\n```typescript\n@@filename(authors/dto/get-author.args)\nimport { MinLength } from 'class-validator';\nimport { Field, ArgsType } from '@nestjs/graphql';\n\n@ArgsType()\nclass GetAuthorArgs {\n  @Field({ nullable: true })\n  firstName?: string;\n\n  @Field({ defaultValue: '' })\n  @MinLength(3)\n  lastName: string;\n}\n```\n\n> info **Hint** Again, due to TypeScript's metadata reflection system limitations, it's required to either use the `@Field` decorator to manually indicate type and optionality, or use a [CLI plugin](/graphql/cli-plugin).\n\nThis will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ntype Query {\n  author(firstName: String, lastName: String = ''): Author\n}\n```\n\n> info **Hint** Note that arguments classes like `GetAuthorArgs` play very well with the `ValidationPipe` (read [more](/techniques/validation)).\n\n#### Class inheritance\n\nYou can use standard TypeScript class inheritance to create base classes with generic utility type features (fields and field properties, validations, etc.) that can be extended. For example, you may have a set of pagination related arguments that always include the standard `offset` and `limit` fields, but also other index fields that are type-specific. You can set up a class hierarchy as shown below.\n\nBase `@ArgsType()` class:\n\n```typescript\n@ArgsType()\nclass PaginationArgs {\n  @Field((type) => Int)\n  offset: number = 0;\n\n  @Field((type) => Int)\n  limit: number = 10;\n}\n```\n\nType specific sub-class of the base `@ArgsType()` class:\n\n```typescript\n@ArgsType()\nclass GetAuthorArgs extends PaginationArgs {\n  @Field({ nullable: true })\n  firstName?: string;\n\n  @Field({ defaultValue: '' })\n  @MinLength(3)\n  lastName: string;\n}\n```\n\nThe same approach can be taken with `@ObjectType()` objects. Define generic properties on the base class:\n\n```typescript\n@ObjectType()\nclass Character {\n  @Field((type) => Int)\n  id: number;\n\n  @Field()\n  name: string;\n}\n```\n\nAdd type-specific properties on sub-classes:\n\n```typescript\n@ObjectType()\nclass Warrior extends Character {\n  @Field()\n  level: number;\n}\n```\n\nYou can use inheritance with a resolver as well. You can ensure type safety by combining inheritance and TypeScript generics. For example, to create a base class with a generic `findAll` query, use a construction like this:\n\n```typescript\nfunction BaseResolver<T extends Type<unknown>>(classRef: T): any {\n  @Resolver({ isAbstract: true })\n  abstract class BaseResolverHost {\n    @Query((type) => [classRef], { name: `findAll${classRef.name}` })\n    async findAll(): Promise<T[]> {\n      return [];\n    }\n  }\n  return BaseResolverHost;\n}\n```\n\nNote the following:\n\n- an explicit return type (`any` above) is required: otherwise TypeScript complains about the usage of a private class definition. Recommended: define an interface instead of using `any`.\n- `Type` is imported from the `@nestjs/common` package\n- The `isAbstract: true` property indicates that SDL (Schema Definition Language statements) shouldn't be generated for this class. Note, you can set this property for other types as well to suppress SDL generation.\n\nHere's how you could generate a concrete sub-class of the `BaseResolver`:\n\n```typescript\n@Resolver((of) => Recipe)\nexport class RecipesResolver extends BaseResolver(Recipe) {\n  constructor(private recipesService: RecipesService) {\n    super();\n  }\n}\n```\n\nThis construct would generated the following SDL:\n\n```graphql\ntype Query {\n  findAllRecipe: [Recipe!]!\n}\n```\n\n#### Generics\n\nWe saw one use of generics above. This powerful TypeScript feature can be used to create useful abstractions. For example, here's a sample cursor-based pagination implementation based on [this documentation](https://graphql.org/learn/pagination/#pagination-and-edges):\n\n```typescript\nimport { Field, ObjectType, Int } from '@nestjs/graphql';\nimport { Type } from '@nestjs/common';\n\ninterface IEdgeType<T> {\n  cursor: string;\n  node: T;\n}\n\nexport interface IPaginatedType<T> {\n  edges: IEdgeType<T>[];\n  nodes: T[];\n  totalCount: number;\n  hasNextPage: boolean;\n}\n\nexport function Paginated<T>(classRef: Type<T>): Type<IPaginatedType<T>> {\n  @ObjectType(`${classRef.name}Edge`)\n  abstract class EdgeType {\n    @Field((type) => String)\n    cursor: string;\n\n    @Field((type) => classRef)\n    node: T;\n  }\n\n  @ObjectType({ isAbstract: true })\n  abstract class PaginatedType implements IPaginatedType<T> {\n    @Field((type) => [EdgeType], { nullable: true })\n    edges: EdgeType[];\n\n    @Field((type) => [classRef], { nullable: true })\n    nodes: T[];\n\n    @Field((type) => Int)\n    totalCount: number;\n\n    @Field()\n    hasNextPage: boolean;\n  }\n  return PaginatedType as Type<IPaginatedType<T>>;\n}\n```\n\nWith the above base class defined, we can now easily create specialized types that inherit this behavior. For example:\n\n```typescript\n@ObjectType()\nclass PaginatedAuthor extends Paginated(Author) {}\n```\n\n#### Schema first\n\nAs mentioned in the [previous](/graphql/quick-start) chapter, in the schema first approach we start by manually defining schema types in SDL (read [more](https://graphql.org/learn/schema/#type-language)). Consider the following SDL type definitions.\n\n> info **Hint** For convenience in this chapter, we've aggregated all of the SDL in one location (e.g., one `.graphql` file, as shown below). In practice, you may find it appropriate to organize your code in a modular fashion. For example, it can be helpful to create individual SDL files with type definitions representing each domain entity, along with related services, resolver code, and the Nest module definition class, in a dedicated directory for that entity. Nest will aggregate all the individual schema type definitions at run time.\n\n```graphql\ntype Author {\n  id: Int!\n  firstName: String\n  lastName: String\n  posts: [Post]\n}\n\ntype Post {\n  id: Int!\n  title: String!\n  votes: Int\n}\n\ntype Query {\n  author(id: Int!): Author\n}\n```\n\n#### Schema first resolver\n\nThe schema above exposes a single query - `author(id: Int!): Author`.\n\n> info **Hint** Learn more about GraphQL queries [here](https://graphql.org/learn/queries/).\n\nLet's now create an `AuthorsResolver` class that resolves author queries:\n\n```typescript\n@@filename(authors/authors.resolver)\n@Resolver('Author')\nexport class AuthorsResolver {\n  constructor(\n    private authorsService: AuthorsService,\n    private postsService: PostsService,\n  ) {}\n\n  @Query()\n  async author(@Args('id') id: number) {\n    return this.authorsService.findOneById(id);\n  }\n\n  @ResolveField()\n  async posts(@Parent() author) {\n    const { id } = author;\n    return this.postsService.findAll({ authorId: id });\n  }\n}\n```\n\n> info **Hint** All decorators (e.g., `@Resolver`, `@ResolveField`, `@Args`, etc.) are exported from the `@nestjs/graphql` package.\n\n> warning **Note** The logic inside the `AuthorsService` and `PostsService` classes can be as simple or sophisticated as needed. The main point of this example is to show how to construct resolvers and how they can interact with other providers.\n\nThe `@Resolver()` decorator is required. It takes an optional string argument with the name of a class. This class name is required whenever the class includes `@ResolveField()` decorators to inform Nest that the decorated method is associated with a parent type (the `Author` type in our current example). Alternatively, instead of setting `@Resolver()` at the top of the class, this can be done for each method:\n\n```typescript\n@Resolver('Author')\n@ResolveField()\nasync posts(@Parent() author) {\n  const { id } = author;\n  return this.postsService.findAll({ authorId: id });\n}\n```\n\nIn this case (`@Resolver()` decorator at the method level), if you have multiple `@ResolveField()` decorators inside a class, you must add `@Resolver()` to all of them. This is not considered the best practice (as it creates extra overhead).\n\n> info **Hint** Any class name argument passed to `@Resolver()` **does not** affect queries (`@Query()` decorator) or mutations (`@Mutation()` decorator).\n\n> warning **Warning** Using the `@Resolver` decorator at the method level is not supported with the **code first** approach.\n\nIn the above examples, the `@Query()` and `@ResolveField()` decorators are associated with GraphQL schema types based on the method name. For example, consider the following construction from the example above:\n\n```typescript\n@Query()\nasync author(@Args('id') id: number) {\n  return this.authorsService.findOneById(id);\n}\n```\n\nThis generates the following entry for the author query in our schema (the query type uses the same name as the method name):\n\n```graphql\ntype Query {\n  author(id: Int!): Author\n}\n```\n\nConventionally, we would prefer to decouple these, using names like `getAuthor()` or `getPosts()` for our resolver methods. We can easily do this by passing the mapping name as an argument to the decorator, as shown below:\n\n```typescript\n@@filename(authors/authors.resolver)\n@Resolver('Author')\nexport class AuthorsResolver {\n  constructor(\n    private authorsService: AuthorsService,\n    private postsService: PostsService,\n  ) {}\n\n  @Query('author')\n  async getAuthor(@Args('id') id: number) {\n    return this.authorsService.findOneById(id);\n  }\n\n  @ResolveField('posts')\n  async getPosts(@Parent() author) {\n    const { id } = author;\n    return this.postsService.findAll({ authorId: id });\n  }\n}\n```\n\n> info **Hint** Nest CLI provides a generator (schematic) that automatically generates **all the boilerplate code** to help us avoid doing all of this, and make the developer experience much simpler. Read more about this feature [here](/recipes/crud-generator).\n\n#### Generating types\n\nAssuming that we use the schema first approach and have enabled the typings generation feature (with `outputAs: 'class'` as shown in the [previous](/graphql/quick-start) chapter), once you run the application it will generate the following file (in the location you specified in the `GraphQLModule.forRoot()` method). For example, in `src/graphql.ts`:\n\n```typescript\n@@filename(graphql)\nexport class Author {\n  id: number;\n  firstName?: string;\n  lastName?: string;\n  posts?: Post[];\n}\n\nexport class Post {\n  id: number;\n  title: string;\n  votes?: number;\n}\n\nexport abstract class IQuery {\n  abstract author(id: number): Author | Promise<Author>;\n}\n```\n\nBy generating classes (instead of the default technique of generating interfaces), you can use declarative validation **decorators** in combination with the schema first approach, which is an extremely useful technique (read [more](/techniques/validation)). For example, you could add `class-validator` decorators to the generated `CreatePostInput` class as shown below to enforce minimum and maximum string lengths on the `title` field:\n\n```typescript\nimport { MinLength, MaxLength } from 'class-validator';\n\nexport class CreatePostInput {\n  @MinLength(3)\n  @MaxLength(50)\n  title: string;\n}\n```\n\n> warning **Notice** To enable auto-validation of your inputs (and parameters), use `ValidationPipe`. Read more about validation [here](/techniques/validation) and more specifically about pipes [here](/pipes).\n\nHowever, if you add decorators directly to the automatically generated file, they will be **overwritten** each time the file is generated. Instead, create a separate file and simply extend the generated class.\n\n```typescript\nimport { MinLength, MaxLength } from 'class-validator';\nimport { Post } from '../../graphql.ts';\n\nexport class CreatePostInput extends Post {\n  @MinLength(3)\n  @MaxLength(50)\n  title: string;\n}\n```\n\n#### GraphQL argument decorators\n\nWe can access the standard GraphQL resolver arguments using dedicated decorators. Below is a comparison of the Nest decorators and the plain Apollo parameters they represent.\n\n<table>\n  <tbody>\n    <tr>\n      <td><code>@Root()</code> and <code>@Parent()</code></td>\n      <td><code>root</code>/<code>parent</code></td>\n    </tr>\n    <tr>\n      <td><code>@Context(param?: string)</code></td>\n      <td><code>context</code> / <code>context[param]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Info(param?: string)</code></td>\n      <td><code>info</code> / <code>info[param]</code></td>\n    </tr>\n    <tr>\n      <td><code>@Args(param?: string)</code></td>\n      <td><code>args</code> / <code>args[param]</code></td>\n    </tr>\n  </tbody>\n</table>\n\nThese arguments have the following meanings:\n\n- `root`: an object that contains the result returned from the resolver on the parent field, or, in the case of a top-level `Query` field, the `rootValue` passed from the server configuration.\n- `context`: an object shared by all resolvers in a particular query; typically used to contain per-request state.\n- `info`: an object that contains information about the execution state of the query.\n- `args`: an object with the arguments passed into the field in the query.\n\n<app-banner-shop></app-banner-shop>\n\n#### Module\n\nOnce we're done with the above steps, we have declaratively specified all the information needed by the `GraphQLModule` to generate a resolver map. The `GraphQLModule` uses reflection to introspect the meta data provided via the decorators, and transforms classes into the correct resolver map automatically.\n\nThe only other thing you need to take care of is to **provide** (i.e., list as a `provider` in some module) the resolver class(es) (`AuthorsResolver`), and importing the module (`AuthorsModule`) somewhere, so Nest will be able to utilize it.\n\nFor example, we can do this in an `AuthorsModule`, which can also provide other services needed in this context. Be sure to import `AuthorsModule` somewhere (e.g., in the root module, or some other module imported by the root module).\n\n```typescript\n@@filename(authors/authors.module)\n@Module({\n  imports: [PostsModule],\n  providers: [AuthorsService, AuthorsResolver],\n})\nexport class AuthorsModule {}\n```\n\n> info **Hint** It is helpful to organize your code by your so-called **domain model** (similar to the way you would organize entry points in a REST API). In this approach, keep your models (`ObjectType` classes), resolvers and services together within a Nest module representing the domain model. Keep all of these components in a single folder per module. When you do this, and use the [Nest CLI](/cli/overview) to generate each element, Nest will wire all of these parts together (locating files in appropriate folders, generating entries in `provider` and `imports` arrays, etc.) automatically for you.\n"
  },
  {
    "path": "content/graphql/scalars.md",
    "content": "### Scalars\n\nA GraphQL object type has a name and fields, but at some point those fields have to resolve to some concrete data. That's where the scalar types come in: they represent the leaves of the query (read more [here](https://graphql.org/learn/schema/#scalar-types)). GraphQL includes the following default types: `Int`, `Float`, `String`, `Boolean` and `ID`. In addition to these built-in types, you may need to support custom atomic data types (e.g., `Date`).\n\n#### Code first\n\nThe code-first approach ships with five scalars in which three of them are simple aliases for the existing GraphQL types.\n\n- `ID` (alias for `GraphQLID`) - represents a unique identifier, often used to refetch an object or as the key for a cache\n- `Int` (alias for `GraphQLInt`) - a signed 32‐bit integer\n- `Float` (alias for `GraphQLFloat`) - a signed double-precision floating-point value\n- `GraphQLISODateTime` - a date-time string at UTC (used by default to represent `Date` type)\n- `GraphQLTimestamp` - a signed integer which represents date and time as number of milliseconds from start of UNIX epoch\n\nThe `GraphQLISODateTime` (e.g. `2019-12-03T09:54:33Z`) is used by default to represent the `Date` type. To use the `GraphQLTimestamp` instead, set the `dateScalarMode` of the `buildSchemaOptions` object to `'timestamp'` as follows:\n\n```typescript\nGraphQLModule.forRoot({\n  buildSchemaOptions: {\n    dateScalarMode: 'timestamp',\n  }\n}),\n```\n\nLikewise, the `GraphQLFloat` is used by default to represent the `number` type. To use the `GraphQLInt` instead, set the `numberScalarMode` of the `buildSchemaOptions` object to `'integer'` as follows:\n\n```typescript\nGraphQLModule.forRoot({\n  buildSchemaOptions: {\n    numberScalarMode: 'integer',\n  }\n}),\n```\n\nIn addition, you can create custom scalars. For example, to create a `Date` scalar, simply create a new class.\n\n```typescript\nimport { Scalar, CustomScalar } from '@nestjs/graphql';\nimport { Kind, ValueNode } from 'graphql';\n\n@Scalar('Date', (type) => Date)\nexport class DateScalar implements CustomScalar<number, Date> {\n  description = 'Date custom scalar type';\n\n  parseValue(value: number): Date {\n    return new Date(value); // value from the client\n  }\n\n  serialize(value: Date): number {\n    return value.getTime(); // value sent to the client\n  }\n\n  parseLiteral(ast: ValueNode): Date {\n    if (ast.kind === Kind.INT) {\n      return new Date(ast.value);\n    }\n    return null;\n  }\n}\n```\n\nWith this in place, register `DateScalar` as a provider.\n\n```typescript\n@Module({\n  providers: [DateScalar],\n})\nexport class CommonModule {}\n```\n\nNow we can use the `Date` type in our classes.\n\n```typescript\n@Field()\ncreationDate: Date;\n```\n\n#### Schema first\n\nTo define a custom scalar (read more about scalars [here](https://www.apollographql.com/docs/graphql-tools/scalars.html)), create a type definition and a dedicated resolver. Here (as in the official documentation), we’ll use the `graphql-type-json` package for demonstration purposes. This npm package defines a `JSON` GraphQL scalar type.\n\nStart by installing the package:\n\n```bash\n$ npm i --save graphql-type-json\n```\n\nOnce the package is installed, we pass a custom resolver to the `forRoot()` method:\n\n```typescript\nimport GraphQLJSON from 'graphql-type-json';\n\n@Module({\n  imports: [\n    GraphQLModule.forRoot({\n      typePaths: ['./**/*.graphql'],\n      resolvers: { JSON: GraphQLJSON },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nNow we can use the `JSON` scalar in our type definitions:\n\n```graphql\nscalar JSON\n\ntype Foo {\n  field: JSON\n}\n```\n\nAnother method to define a scalar type is to create a simple class. Assume we want to enhance our schema with the `Date` type.\n\n```typescript\nimport { Scalar, CustomScalar } from '@nestjs/graphql';\nimport { Kind, ValueNode } from 'graphql';\n\n@Scalar('Date')\nexport class DateScalar implements CustomScalar<number, Date> {\n  description = 'Date custom scalar type';\n\n  parseValue(value: number): Date {\n    return new Date(value); // value from the client\n  }\n\n  serialize(value: Date): number {\n    return value.getTime(); // value sent to the client\n  }\n\n  parseLiteral(ast: ValueNode): Date {\n    if (ast.kind === Kind.INT) {\n      return new Date(ast.value);\n    }\n    return null;\n  }\n}\n```\n\nWith this in place, register `DateScalar` as a provider.\n\n```typescript\n@Module({\n  providers: [DateScalar],\n})\nexport class CommonModule {}\n```\n\nNow we can use the `Date` scalar in type definitions.\n\n```graphql\nscalar Date\n```\n\nBy default, the generated TypeScript definition for all scalars is `any` - which isn't particularly typesafe.\nBut, you can configure how Nest generates typings for your custom scalars when you specify how to generate types:\n\n```typescript\nimport { GraphQLDefinitionsFactory } from '@nestjs/graphql';\nimport { join } from 'path';\n\nconst definitionsFactory = new GraphQLDefinitionsFactory()\n\ndefinitionsFactory.generate({\n  typePaths: ['./src/**/*.graphql'],\n  path: join(process.cwd(), 'src/graphql.ts'),\n  outputAs: 'class',\n  defaultScalarType: 'unknown',\n  customScalarTypeMapping: {\n    DateTime: 'Date',\n    BigNumber: '_BigNumber',\n  },\n  additionalHeader: \"import _BigNumber from 'bignumber.js'\",\n})\n```\n\n> info **Hint** Alternatively, you can use a type reference instead, for example: `DateTime: Date`. In this case, `GraphQLDefinitionsFactory` will extract the name property of the specified type (`Date.name`) to generate TS definitions. Note: adding an import statement for non-built-in types (custom types) is required.\n\nNow, given the following GraphQL custom scalar types:\n\n```graphql\nscalar DateTime\nscalar BigNumber\nscalar Payload\n```\n\nWe will now see the following generated TypeScript definitions in `src/graphql.ts`:\n\n```typescript\nimport _BigNumber from 'bignumber.js'\n\nexport type DateTime = Date\nexport type BigNumber = _BigNumber\nexport type Payload = unknown\n```\n\nHere, we've used the `customScalarTypeMapping` property to supply a map of the types we wish to declare for our custom scalars. We've\nalso provided an `additionalHeader` property so that we can add any imports required for these type definitions. Lastly, we've added\na `defaultScalarType` of `'unknown'`, so that any custom scalars not specified in `customScalarTypeMapping` will be aliased to\n`unknown` instead of `any` (which [TypeScript recommends](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type) using since 3.0 for added type safety).\n\n> info **Hint** Note that we've imported `_BigNumber` from `bignumber.js`; this is to avoid [circular type references](https://github.com/Microsoft/TypeScript/issues/12525#issuecomment-263166239).\n"
  },
  {
    "path": "content/graphql/schema-generator.md",
    "content": "### Generating SDL\n\n> warning **Warning** This chapter applies only to the code first approach.\n\nTo manually generate a GraphQL SDL schema (i.e., without running an application, connecting to the database, hooking up resolvers, etc.), use the `GraphQLSchemaBuilderModule`.\n\n```typescript\nasync function generateSchema() {\n  const app = await NestFactory.create(GraphQLSchemaBuilderModule);\n  await app.init();\n\n  const gqlSchemaFactory = app.get(GraphQLSchemaFactory);\n  const schema = await gqlSchemaFactory.create([RecipesResolver]);\n  console.log(printSchema(schema));\n}\n```\n\n> info **Hint** The `GraphQLSchemaBuilderModule` and `GraphQLSchemaFactory` are imported from the `@nestjs/graphql` package. The `printSchema` function is imported from the `graphql` package.\n\n#### Usage\n\nThe `gqlSchemaFactory.create()` method takes an array of resolver class references. For example:\n\n```typescript\nconst schema = await gqlSchemaFactory.create([\n  RecipesResolver,\n  AuthorsResolver,\n  PostsResolvers,\n]);\n```\n\nIt also takes a second optional argument with an array of scalar classes:\n\n```typescript\nconst schema = await gqlSchemaFactory.create(\n  [RecipesResolver, AuthorsResolver, PostsResolvers],\n  [DurationScalar, DateScalar],\n);\n```\n\nLastly, you can pass an options object:\n\n```typescript\nconst schema = await gqlSchemaFactory.create([RecipesResolver], {\n  skipCheck: true,\n  orphanedTypes: [],\n});\n```\n\n- `skipCheck`: ignore schema validation; boolean, defaults to `false`\n- `orphanedTypes`: list of classes that are not explicitly referenced (not part of the object graph) to be generated. Normally, if a class is declared but isn't otherwise referenced in the graph, it's omitted. The property value is an array of class references.\n"
  },
  {
    "path": "content/graphql/subscriptions.md",
    "content": "### Subscriptions\n\nIn addition to fetching data using queries and modifying data using mutations, the GraphQL spec supports a third operation type, called `subscription`. GraphQL subscriptions are a way to push data from the server to the clients that choose to listen to real time messages from the server. Subscriptions are similar to queries in that they specify a set of fields to be delivered to the client, but instead of immediately returning a single answer, a channel is opened and a result is sent to the client every time a particular event happens on the server.\n\nA common use case for subscriptions is notifying the client side about particular events, for example the creation of a new object, updated fields and so on (read more [here](https://www.apollographql.com/docs/react/data/subscriptions)).\n\n#### Enable subscriptions\n\nTo enable subscriptions, set the `installSubscriptionHandlers` property to `true`.\n\n```typescript\nGraphQLModule.forRoot({\n  installSubscriptionHandlers: true,\n}),\n```\n\n> warning **Warning** The `installSubscriptionHandlers` configuration option has been removed from the latest version of Apollo server and will be soon deprecated in this package as well. By default, `installSubscriptionHandlers` will fallback to use the `subscriptions-transport-ws` ([read more](https://github.com/apollographql/subscriptions-transport-ws)) but we strongly recommend using the `graphql-ws`([read more](https://github.com/enisdenjo/graphql-ws)) library instead.\n\nTo switch to use the `graphql-ws` package instead, use the following configuration:\n\n```typescript\nGraphQLModule.forRoot({\n  subscriptions: {\n    'graphql-ws': true\n  },\n}),\n```\n\n> info **Hint** You can also use both packages (`subscriptions-transport-ws` and `graphql-ws`) at the same time, for example, for backward compatibility.\n\n#### Code first\n\nTo create a subscription using the code first approach, we use the `@Subscription()` decorator and the `PubSub` class from the `graphql-subscriptions` package, which provides a simple **publish/subscribe API**.\n\nThe following subscription handler takes care of **subscribing** to an event by calling `PubSub#asyncIterator`. This method takes a single argument, the `triggerName`, which corresponds to an event topic name.\n\n```typescript\nconst pubSub = new PubSub();\n\n@Resolver((of) => Author)\nexport class AuthorResolver {\n  // ...\n  @Subscription((returns) => Comment)\n  commentAdded() {\n    return pubSub.asyncIterator('commentAdded');\n  }\n}\n```\n\n> info **Hint** All decorators are exported from the `@nestjs/graphql` package, while the `PubSub` class is exported from the `graphql-subscriptions` package.\n\n> warning **Note** `PubSub` is a class that exposes a simple `publish` and `subscribe API`. Read more about it [here](https://www.apollographql.com/docs/graphql-subscriptions/setup.html). Note that the Apollo docs warn that the default implementation is not suitable for production (read more [here](https://github.com/apollographql/graphql-subscriptions#getting-started-with-your-first-subscription)). Production apps should use a `PubSub` implementation backed by an external store (read more [here](https://github.com/apollographql/graphql-subscriptions#pubsub-implementations)).\n\nThis will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ntype Subscription {\n  commentAdded(): Comment!\n}\n```\n\nNote that subscriptions, by definition, return an object with a single top level property whose key is the name of the subscription. This name is either inherited from the name of the subscription handler method (i.e., `commentAdded` above), or is provided explicitly by passing an option with the key `name` as the second argument to the `@Subscription()` decorator, as shown below.\n\n```typescript\n  @Subscription(returns => Comment, {\n    name: 'commentAdded',\n  })\n  addCommentHandler() {\n    return pubSub.asyncIterator('commentAdded');\n  }\n```\n\nThis construct produces the same SDL as the previous code sample, but allows us to decouple the method name from the subscription.\n\n#### Publishing\n\nNow, to publish the event, we use the `PubSub#publish` method. This is often used within a mutation to trigger a client-side update when a part of the object graph has changed. For example:\n\n```typescript\n@@filename(posts/posts.resolver)\n@Mutation(returns => Post)\nasync addComment(\n  @Args('postId', { type: () => Int }) postId: number,\n  @Args('comment', { type: () => Comment }) comment: CommentInput,\n) {\n  const newComment = this.commentsService.addComment({ id: postId, comment });\n  pubSub.publish('commentAdded', { commentAdded: newComment });\n  return newComment;\n}\n```\n\nThe `PubSub#publish` method takes a `triggerName` (again, think of this as an event topic name) as the first parameter, and an event payload as the second parameter. As mentioned, the subscription, by definition, returns a value and that value has a shape. Look again at the generated SDL for our `commentAdded` subscription:\n\n```graphql\ntype Subscription {\n  commentAdded(): Comment!\n}\n```\n\nThis tells us that the subscription must return an object with a top-level property name of `commentAdded` that has a value which is a `Comment` object. The important point to note is that the shape of the event payload emitted by the `PubSub#publish` method must correspond to the shape of the value expected to return from the subscription. So, in our example above, the `pubSub.publish('commentAdded', {{ '{' }} commentAdded: newComment {{ '}' }})` statement publishes a `commentAdded` event with the appropriately shaped payload. If these shapes don't match, your subscription will fail during the GraphQL validation phase.\n\n#### Filtering subscriptions\n\nTo filter out specific events, set the `filter` property to a filter function. This function acts similar to the function passed to an array `filter`. It takes two arguments: `payload` containing the event payload (as sent by the event publisher), and `variables` taking any arguments passed in during the subscription request. It returns a boolean determining whether this event should be published to client listeners.\n\n```typescript\n@Subscription(returns => Comment, {\n  filter: (payload, variables) =>\n    payload.commentAdded.title === variables.title,\n})\ncommentAdded(@Args('title') title: string) {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\n#### Mutating subscription payloads\n\nTo mutate the published event payload, set the `resolve` property to a function. The function receives the event payload (as sent by the event publisher) and returns the appropriate value.\n\n```typescript\n@Subscription(returns => Comment, {\n  resolve: value => value,\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\n> warning **Note** If you use the `resolve` option, you should return the unwrapped payload (e.g., with our example, return a `newComment` object directly, not a `{{ '{' }} commentAdded: newComment {{ '}' }}` object).\n\nIf you need to access injected providers (e.g., use an external service to validate the data), use the following construction.\n\n```typescript\n@Subscription(returns => Comment, {\n  resolve(this: AuthorResolver, value) {\n    // \"this\" refers to an instance of \"AuthorResolver\"\n    return value;\n  }\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\nThe same construction works with filters:\n\n```typescript\n@Subscription(returns => Comment, {\n  filter(this: AuthorResolver, payload, variables) {\n    // \"this\" refers to an instance of \"AuthorResolver\"\n    return payload.commentAdded.title === variables.title;\n  }\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\n#### Schema first\n\nTo create an equivalent subscription in Nest, we'll make use of the `@Subscription()` decorator.\n\n```typescript\nconst pubSub = new PubSub();\n\n@Resolver('Author')\nexport class AuthorResolver {\n  // ...\n  @Subscription()\n  commentAdded() {\n    return pubSub.asyncIterator('commentAdded');\n  }\n}\n```\n\nTo filter out specific events based on context and arguments, set the `filter` property.\n\n```typescript\n@Subscription('commentAdded', {\n  filter: (payload, variables) =>\n    payload.commentAdded.title === variables.title,\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\nTo mutate the published payload, we can use a `resolve` function.\n\n```typescript\n@Subscription('commentAdded', {\n  resolve: value => value,\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\nIf you need to access injected providers (e.g., use an external service to validate the data), use the following construction:\n\n```typescript\n@Subscription('commentAdded', {\n  resolve(this: AuthorResolver, value) {\n    // \"this\" refers to an instance of \"AuthorResolver\"\n    return value;\n  }\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\nThe same construction works with filters:\n\n```typescript\n@Subscription('commentAdded', {\n  filter(this: AuthorResolver, payload, variables) {\n    // \"this\" refers to an instance of \"AuthorResolver\"\n    return payload.commentAdded.title === variables.title;\n  }\n})\ncommentAdded() {\n  return pubSub.asyncIterator('commentAdded');\n}\n```\n\nThe last step is to update the type definitions file.\n\n```graphql\ntype Author {\n  id: Int!\n  firstName: String\n  lastName: String\n  posts: [Post]\n}\n\ntype Post {\n  id: Int!\n  title: String\n  votes: Int\n}\n\ntype Query {\n  author(id: Int!): Author\n}\n\ntype Comment {\n  id: String\n  content: String\n}\n\ntype Subscription {\n  commentAdded(title: String!): Comment\n}\n```\n\nWith this, we've created a single `commentAdded(title: String!): Comment` subscription. You can find a full sample implementation [here](https://github.com/nestjs/nest/blob/master/sample/12-graphql-schema-first).\n\n#### PubSub\n\nWe instantiated a local `PubSub` instance above. The preferred approach is to define `PubSub` as a [provider](/fundamentals/custom-providers) and inject it through the constructor (using the `@Inject()` decorator). This allows us to re-use the instance across the whole application. For example, define a provider as follows, then inject `'PUB_SUB'` where needed.\n\n```typescript\n{\n  provide: 'PUB_SUB',\n  useValue: new PubSub(),\n}\n```\n\n#### Customize subscriptions server\n\nTo customize the subscriptions server (e.g., change the path), use the `subscriptions` options property.\n\n```typescript\nGraphQLModule.forRoot({\n  installSubscriptionHandlers: true,\n  subscriptions: {\n    'subscriptions-transport-ws': {\n      path: '/graphql'\n    },\n  }\n}),\n```\n\nIf you're using the `graphql-ws` package for subscriptions, replace the `subscriptions-transport-ws` key with `graphql-ws`, as follows:\n\n```typescript\nGraphQLModule.forRoot({\n  installSubscriptionHandlers: true,\n  subscriptions: {\n    'graphql-ws': {\n      path: '/graphql'\n    },\n  }\n}),\n```\n\n#### Authentication over WebSocket\n\nChecking that the user is authenticated should be done inside the `onConnect` callback function that you can specify in the `subscriptions` options.\n\nThe `onConnect` will receive as a first argument the `connectionParams` passed to the `SubscriptionClient` (read [more](https://www.apollographql.com/docs/react/data/subscriptions/#5-authenticate-over-websocket-optional)).\n\n```typescript\nGraphQLModule.forRoot({\n  subscriptions: {\n    'subscriptions-transport-ws': {\n      onConnect: (connectionParams) => {\n        const authToken = connectionParams.authToken;\n        if (!isValid(authToken)) {\n          throw new Error('Token is not valid');\n        }\n        // extract user information from token\n        const user = parseToken(authToken);\n        // return user info to add them to the context later\n        return { user };\n      },\n    }\n  },\n  context: ({ connection }) => {\n    // connection.context will be equal to what was returned by the \"onConnect\" callback\n  },\n}),\n```\n\nThe `authToken` in this example is only sent once by the client, when the connection is first established.\nAll subscriptions made with this connection will have the same `authToken`, and thus the same user info.\n\n> warning **Note** There is a bug in `subscriptions-transport-ws` that allows connections to skip the `onConnect` phase (read [more](https://github.com/apollographql/subscriptions-transport-ws/issues/349)). You should not assume that `onConnect` was called when the user starts a subscription, and always check that the `context` is populated.\n\nIf you're using the `graphql-ws` package, the signature of the `onConnect` callback will be slightly different:\n\n```typescript\nsubscriptions: {\n  'graphql-ws': {\n    onConnect: (context: Context<any>) => {\n      const { connectionParams, extra } = context;\n      // user validation will remain the same as in the example above\n      // when using with graphql-ws, additional context value should be stored in the extra field\n      extra.user = { user: {} };\n    },\n  },\n  context: ({ extra }) => {\n    // you can now access your additional context value through the extra field\n  } \n},\n```\n"
  },
  {
    "path": "content/graphql/unions-and-enums.md",
    "content": "### Unions\n\nUnion types are very similar to interfaces, but they don't get to specify any common fields between the types (read more [here](https://graphql.org/learn/schema/#union-types)). Unions are useful for returning disjoint data types from a single field.\n\n#### Code first\n\nTo define a GraphQL union type, we must define classes that this union will be composed of. Following the [example](https://www.apollographql.com/docs/apollo-server/schema/unions-interfaces/#union-type) from the Apollo documentation, we'll create two classes. First, `Book`:\n\n```typescript\nimport { Field, ObjectType } from '@nestjs/graphql';\n\n@ObjectType()\nexport class Book {\n  @Field()\n  title: string;\n}\n```\n\nAnd then `Author`:\n\n```typescript\nimport { Field, ObjectType } from '@nestjs/graphql';\n\n@ObjectType()\nexport class Author {\n  @Field()\n  name: string;\n}\n```\n\nWith this in place, register the `ResultUnion` union using the `createUnionType` function exported from the `@nestjs/graphql` package:\n\n```typescript\nexport const ResultUnion = createUnionType({\n  name: 'ResultUnion',\n  types: () => [Author, Book],\n});\n```\n\nNow, we can reference the `ResultUnion` in our query:\n\n```typescript\n@Query(returns => [ResultUnion])\nsearch(): Array<typeof ResultUnion> {\n  return [new Author(), new Book()];\n}\n```\n\nThis will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\ntype Author {\n  name: String!\n}\n\ntype Book {\n  title: String!\n}\n\nunion ResultUnion = Author | Book\n\ntype Query {\n  search: [ResultUnion!]!\n}\n```\n\nThe default `resolveType()` function generated by the library will extract the type based on the value returned from the resolver method. That means returning class instances instead of literal JavaScript object is obligatory.\n\nTo provide a customized `resolveType()` function, pass the `resolveType` property to the options object passed into the `createUnionType()` function, as follows:\n\n```typescript\nexport const ResultUnion = createUnionType({\n  name: 'ResultUnion',\n  types: () => [Author, Book],\n  resolveType(value) {\n    if (value.name) {\n      return Author;\n    }\n    if (value.title) {\n      return Book;\n    }\n    return null;\n  },\n});\n```\n\n#### Schema first\n\nTo define a union in the schema first approach, simply create a GraphQL union with SDL.\n\n```graphql\ntype Author {\n  name: String!\n}\n\ntype Book {\n  title: String!\n}\n\nunion ResultUnion = Author | Book\n```\n\nThen, you can use the typings generation feature (as shown in the [quick start](/graphql/quick-start) chapter) to generate corresponding TypeScript definitions:\n\n```typescript\nexport class Author {\n  name: string;\n}\n\nexport class Book {\n  title: string;\n}\n\nexport type ResultUnion = Author | Book;\n```\n\nUnions require an extra `__resolveType` field in the resolver map to determine which type the union should resolve to. Also, note that the `ResultUnionResolver` class has to be registered as a provider in any module. Let's create a `ResultUnionResolver` class and define the `__resolveType` method. \n\n```typescript\n@Resolver('ResultUnion')\nexport class ResultUnionResolver {\n  @ResolveField()\n  __resolveType(value) {\n    if (value.name) {\n      return 'Author';\n    }\n    if (value.title) {\n      return 'Book';\n    }\n    return null;\n  }\n}\n```\n\n> info **Hint** All decorators are exported from the `@nestjs/graphql` package.\n\n### Enums\n\nEnumeration types are a special kind of scalar that is restricted to a particular set of allowed values (read more [here](https://graphql.org/learn/schema/#enumeration-types)). This allows you to:\n\n- validate that any arguments of this type are one of the allowed values\n- communicate through the type system that a field will always be one of a finite set of values\n\n#### Code first\n\nWhen using the code first approach, you define a GraphQL enum type by simply creating a TypeScript enum.\n\n```typescript\nexport enum AllowedColor {\n  RED,\n  GREEN,\n  BLUE,\n}\n```\n\nWith this in place, register the `AllowedColor` enum using the `registerEnumType` function exported from the `@nestjs/graphql` package:\n\n```typescript\nregisterEnumType(AllowedColor, {\n  name: 'AllowedColor',\n});\n```\n\nNow you can reference the `AllowedColor` in our types:\n\n```typescript\n@Field(type => AllowedColor)\nfavoriteColor: AllowedColor;\n```\n\nThis will result in generating the following part of the GraphQL schema in SDL:\n\n```graphql\nenum AllowedColor {\n  RED\n  GREEN\n  BLUE\n}\n```\n\nTo provide a description for the enum, pass the `description` property into the `registerEnumType()` function.\n\n```typescript\nregisterEnumType(AllowedColor, {\n  name: 'AllowedColor',\n  description: 'The supported colors.',\n});\n```\n\nTo provide a description for the enum values, or to mark a value as deprecated, pass the `valuesMap` property, as follows:\n\n```typescript\nregisterEnumType(AllowedColor, {\n  name: 'AllowedColor',\n  description: 'The supported colors.',\n  valuesMap: {\n    RED: {\n      description: 'The default color.',\n    },\n    BLUE: {\n      deprecationReason: 'Too blue.',\n    },\n  },\n});\n```\n\nThis will generate the following GraphQL schema in SDL:\n\n```graphql\n\"\"\"\nThe supported colors.\n\"\"\"\nenum AllowedColor {\n  \"\"\"\n  The default color.\n  \"\"\"\n  RED\n  GREEN\n  BLUE @deprecated(reason: \"Too blue.\")\n}\n```\n\n#### Schema first\n\nTo define an enumerator in the schema first approach, simply create a GraphQL enum with SDL.\n\n```graphql\nenum AllowedColor {\n  RED\n  GREEN\n  BLUE\n}\n```\n\nThen you can use the typings generation feature (as shown in the [quick start](/graphql/quick-start) chapter) to generate corresponding TypeScript definitions:\n\n```typescript\nexport enum AllowedColor {\n  RED\n  GREEN\n  BLUE\n}\n```\n\nSometimes a backend forces a different value for an enum internally than in the public API. In this example the API contains `RED`, however in resolvers we may use `#f00` instead (read more [here](https://www.apollographql.com/docs/apollo-server/schema/scalars-enums/#internal-values)). To accomplish this, declare a resolver object for the `AllowedColor` enum:\n\n```typescript\nexport const allowedColorResolver: Record<keyof typeof AllowedColor, any> = {\n  RED: '#f00',\n};\n```\n\n> info **Hint** All decorators are exported from the `@nestjs/graphql` package.\n\nThen use this resolver object together with the `resolvers` property of the `GraphQLModule#forRoot()` method, as follows:\n\n```typescript\nGraphQLModule.forRoot({\n  resolvers: {\n    AllowedColor: allowedColorResolver,\n  },\n});\n```\n"
  },
  {
    "path": "content/guards.md",
    "content": "### 가드\n\n가드는 `@Injectable()` 데코레이터가 붙는 클래스의 일종이며 `CanActivate` 인터페이스를 구현해야 합니다.\n\n<figure><img src=\"/assets/Guards_1.png\" /></figure>\n\n가드는 **하나의 책임**만 집니다. 런타임 환경에서 주어지는 특정 조건(권한, 역할, ACLs 등)을 고려하여 주어진 요청을 핸들러가 처리할지 말지를 결정하며, 대게는 **승인**의 용도로 사용됩니다. Express 애플리케이션에서 승인(보통 그 사촌인 '인증'과 협력하는)는 전형적으로 [미들웨어](/middleware)를 통해 이루어졌습니다. 미들웨어를 사용하여 인증하는 것은 좋은 선택이긴 합니다. 토큰을 검사하고 `요청` 객체에 프로퍼티들을 붙이는 작업들을 특정 라우트 컨텍스트와 그 메타데이터에 국한시킬 수 있기 때문입니다.\n\n하지만 원래 미들웨어는 조금 답답한 구석이 있습니다. 미들웨어는 입장에서는 어느 핸들러가 `next()`함수에 의해 호출되는지 모릅니다. 반면에, **가드**는 `ExecutionContext` 인스턴스에 접근할 수 있기 때문에 다음으로 무엇이 실행될지 정확하게 압니다. 가드는 예외 필터와 파이프, 인터셉터와 같이 요청부터 응답까지의 사이클 중 정확히 원하는 지점에 처리 로직을 아주 선언적으로 끼워 넣을 수 있도록 설계 되었습니다. 이 덕분에 더욱 DRY하고 선언적인 코드를 유지할 수 있습니다.\n\n> info **힌트** 가드는 미들웨어보다 **이후**에, 파이프와 인터셉터보다는 **이전**에 실행됩니다.\n\n#### 승인 가드\n\n위에서 언급했듯, **승인**은 가드를 활용하는 좋은 사례입니다. 요청하는 사용자(보통은 이미 인증된 상태)가 충분한 권한을 가지고 있을 때만 라우트를 이용할 수 있기 때문입니다. 이제부터 작성해볼 `AuthGuard`는 사용자가 이미 인증 되었다고 가정하기 때문에 요청 헤더에 토큰이 붙어있을 것이라 생각합니다. 이 가드는 토큰을 추출 및 검증하여 확보한 정보를 보고 요청을 처리할지 말지 결정합니다.\n\n```typescript\n@@filename(auth.guard)\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class AuthGuard implements CanActivate {\n  canActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    const request = context.switchToHttp().getRequest();\n    return validateRequest(request);\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class AuthGuard {\n  async canActivate(context) {\n    const request = context.switchToHttp().getRequest();\n    return validateRequest(request);\n  }\n}\n```\n\n> info **힌트** 만약 애플리케이션에서 인증 메커니즘을 어떻게 구현하는지에 대한 실제 사례는 [이 챕터](/security/authentication)에서 확인할 수 있습니다.\n\n`validateRequest()` 함수 내부의 로직은 필요에 따라 간단해질 수도 정교해질 수도 있습니다. 이번 예제의 핵심은 요청부터 응답까지의 사이클 속에서 알맞은 곳에 가드를 끼워넣는 것입니다.\n\n모든 가드는 `canActivate()` 함수를 구현해야 하며 이 함수는 boolean을 반환해야 합니다. 반환되는 값은 요청이 허용될지 말지를 나타냅니다. 결과는 `Promise`나 `Observable`을 이용하여 비동기적으로도 반환할 수 있습니다. Nest는 이 반환값을 통해 다음 작업을 제어합니다.\n\n- `true`를 반환하면 요청이 처리됩니다.\n- `false`를 반환하면 Nest가 요청을 거절합니다.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### 실행 컨텍스트\n\n`canActivate()` 함수는 `ExecutionContext` 인스턴스만 인자로 받습니다. `ExecutionContext`는 `ArgumentsHost`를 상속합니다. `AgumentsHost`는 이전에 예외 필터 챕터에 등장했었습니다. 위의 예제에서는 이전과 마찬가지로 `ArgumentsHost`에 정의되어 있는 헬퍼 메서드를 사용하여 `요청` 객체를 참조합니다. 이 주제에 대해 자세히 알고 싶다면 [예외 필터](https://docs.nestjs.com/exception-filters#arguments-host) 챕터의 **Arguments host** 섹션을 참조하세요.\n\n`ExecutionContext`는 `ArgumentsHost`를 상속받기 때문에 새로운 헬퍼 메서드를 생성하여 현재 실행 프로세스에 대한 추가적인 세부사항들을 제공할 수 있습니다. 이 세부사항들은 전반적인 컨트롤러와 메서드, 실행 컨텍스트들을 아울러 동작하는 범용적인 가드를 작성할 때 유용할 것입니다. `ExecutionContext`에 대한 자세한 내용은 [여기](fundamentals/execution-context)를 참조해 주세요.\n\n#### 역할 기반 인증\n\n더욱 기능적인 가드를 작성하여 특정한 역할을 가진 사용자에게만 접근을 허가하도록 만들어 봅시다. 기본 가드 템플릿에서 시작하여 아래 섹션들을 거치면서 구성하겠습니다. 따라서 우선 지금은 모든 요청을 수행하도록 허가하고 있습니다:\n\n```typescript\n@@filename(roles.guard)\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Observable } from 'rxjs';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  canActivate(\n    context: ExecutionContext,\n  ): boolean | Promise<boolean> | Observable<boolean> {\n    return true;\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class RolesGuard {\n  canActivate(context) {\n    return true;\n  }\n}\n```\n\n#### 가드 적용하기\n\n파이프나 예외 필터처럼 가드도 **컨트롤러 스코프**나 메서드 스코프, 전역 스코프를 가질 수 있습니다. 아래 예제에서는 `@UseGuards()` 데코레이터를 사용하여 컨트롤러 스코프를 가지는 가드를 적용했습니다. 이 데코레이터에는 단 하나의 값만 인자로 넘길 수도 있고, 여러 인자를 담은 배열을 인자로 넘길 수도 있습니다. 이 덕분에 하나의 데코레이터만으로도 적절한 가드들을 쉽게 적용할 수 있습니다.\n\n```typescript\n@@filename()\n@Controller('cats')\n@UseGuards(RolesGuard)\nexport class CatsController {}\n```\n\n> info **힌트** `@UseGuards()` 데코레이터는 `@nestjs/common` 패키지에서 import합니다.\n\n위 예제처럼, `RolesGuard` 의 인스턴스가 아닌 타입을 전달함으로써 인스턴스화에 대한 책임을 프레임워크에 맡기고 의존성 주입을 가능하게 합니다. 파이프나 예외 필터를 적용할 때처럼 인스턴스로 넘기는 것도 가능합니다:\n\n```typescript\n@@filename()\n@Controller('cats')\n@UseGuards(new RolesGuard())\nexport class CatsController {}\n```\n\n위처럼 컨트롤러 레벨에 가드를 생성하면 해당 컨트롤러의 모든 핸들러에게 가드가 붙습니다. 가드를 특정 메서드에만 적용하려면 `@UseGuards()` 데코레이터를 **메서드 레벨**에 적용해야 합니다.\n\n전역 가드를 적용하려면 Nest 애플리케이션 인스턴스의 `useGlobalGuards()`를 사용합니다.\n\n```typescript\n@@filename()\nconst app = await NestFactory.create(AppModule);\napp.useGlobalGuards(new RolesGuard());\n```\n\n> warning **주의** 하이브리드 앱의 경우 `useGlobalGuards()` 메서드는 기본적으로 게이트웨이 및 마이크로서비스에 대해 가드를 적용시키지 않습니다(이 동작을 변경하는 방법은 [하이브리드 애플리케이션](/faq/hybrid-application)을 참조하세요). 하이브리드가 아닌 \"표준\" 마이크로서비스 앱에서는 `useGlobalGuards()`가 가드를 전역적으로 마운트시킵니다.\n\n전역 가드는 모든 컨트롤러와 모든 라우트 핸들러, 즉 전체 애플리케이션의 어디에서나 사용됩니다. 의존성 주입 측면에서 볼 때, 위 예제에서 `useGlobalGuards()`할 때처럼 모든 모듈의 바깥에서 등록된 전역 가드는 의존성을 주입시킬 수 없습니다. 가드가 등록되는 일이 모든 모듈의 컨텍스트 바깥에서 일어나기 때문입니다. 이 이슈를 해결하려면 아래와 같이 모듈에서 가드를 직접 적용시켜야 합니다:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { APP_GUARD } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_GUARD,\n      useClass: RolesGuard,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n> info **힌트** 가드에 대한 의존성 주입을 위해 이러한 접근을 사용할 때 유념해야 할 점은 어느 모듈에서 적용하든 간에 그 가드는 사실 전역적이라는 것입니다. 그렇다면 위와 같은 작업은 어디서 해야 할까요? 우선 가드(위 에제에서는 `RolesGuard`)가 정의될 모듈을 선택합니다. 또한 `useClass`는 사용자 정의 프로바이더를 등록하는 유일한 방법이 아닙니다. 사용자 정의 프로바이더에 관한 자세한 정보는 [여기](/fundamentals/custom-providers)를 참조하세요.\n\n#### 핸들러마다 역할 지정하기\n\n우리의 `RolesGuard`는 동작은 하지만 아직은 그다지 똑똑하지 않습니다. 아직 가드의 중요한 기능인 [실행 컨텍스트](/fundamentals/execution-context)를 활용하지 않았기 때문이죠. 우리의 가드는 아직 각 핸들러마다 허용할 사용자의 역할에 대해 알지 못합니다. 예를 들어 `CatsController`의 각 라우터마다 다른 권한 규격을 가지게 하려고 합니다. 몇몇 핸들러는 관리자만 사용할 수 있고, 나머지는 모든 사용자가 이용할 수 있습니다. 어떻게 하면 유연하고 재사용 가능하게 관리자나 일반사용자 같은 역할을 라우트에 매칭시킬 수 있을까요?\n\n바로 여기에서 **사용자 정의 메타데이터**를 사용합니다(사용자 정의 메타데이터에 대한 자세한 내용은 [여기](https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata)를 참조하세요). Nest에서는 `@SetMetadata()` 데코레이터를 이용하여 라우트 핸들러에 사용자 정의 **메타데이터**를 붙일 수 있습니다. 이 메타데이터는 우리가 놓치고 있던 `role`데이터를 제공해 주며 우리의 가드는 비로소 똑똑하게 결정을 내릴 수 있게 됩니다. `@SetMetadata()`를 어떻게 사용하는 지 살펴봅시다:\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@SetMetadata('roles', ['admin'])\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@SetMetadata('roles', ['admin'])\n@Bind(Body())\nasync create(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n> info **힌트** `@SetMetadata()` 데코레이터는 `@nestjs/common` 패키지에서 import합니다.\n\n위와 같이 작성하면 `roles`라는 메타데이터(`roles`는 key이고, `['admin]`은 그 값입니다)가 `create()`메서드에 붙게 됩니다. 이러한 작업을 할 때, `@SetMetadata()`를 직접 라우트에 명시하는 것은 그다지 좋은 활용이 아닙니다. 대신에, 아래와 같이 자신만의 데코레이터를 작성합니다:\n\n```typescript\n@@filename(roles.decorator)\nimport { SetMetadata } from '@nestjs/common';\n\nexport const Roles = (...roles: string[]) => SetMetadata('roles', roles);\n@@switch\nimport { SetMetadata } from '@nestjs/common';\n\nexport const Roles = (...roles) => SetMetadata('roles', roles);\n```\n\n이와 같이 접근하면 훨씬 깔끔하고 가독성이 좋으며 타입을 더욱 엄격하게 관리할 수 있습니다. 이제 `@Roles()`라는 사용자 정의 데코레이터가 생겼고, 이를 `create()`메서드에 붙일 수 있습니다.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@Roles('admin')\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@Roles('admin')\n@Bind(Body())\nasync create(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n#### 지금까지의 모든 것들을 적용하기\n\n`RolesGuard`를 작성했던 곳으로 돌아가 봅시다. 아직까지는 단순하게 `true`만 반환하기 때문에 모든 요청이 처리됩니다. 이제는 **현재 사용자의 역할**과 처리될 예정인 라우트가 요구하는 역할을 비교하여 상황에 따라 다른 값을 반환하게 만들려고 합니다. 라우트의 역할(사용자 정의 메타데이터)에 접근하기 위해서는 `Reflector`라는 헬퍼 클래스를 사용해야 합니다. 이 클래스는 별도의 작업 없이 그저 `@nestjs/core`에서 가져다 사용하기만 하면 됩니다.\n\n```typescript\n@@filename(roles.guard)\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const roles = this.reflector.get<string[]>('roles', context.getHandler());\n    if (!roles) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const user = request.user;\n    return matchRoles(roles, user.roles);\n  }\n}\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\n@Dependencies(Reflector)\nexport class RolesGuard {\n  constructor(reflector) {\n    this.reflector = reflector;\n  }\n\n  canActivate(context) {\n    const roles = this.reflector.get('roles', context.getHandler());\n    if (!roles) {\n      return true;\n    }\n    const request = context.switchToHttp().getRequest();\n    const user = request.user;\n    return matchRoles(roles, user.roles);\n  }\n}\n```\n\n> info **힌트** node.js 세계에서는 `request`객체에 프로퍼티들을 붙이는 경험을 흔하게 합니다. 따라서, 위의 에제에서는 `request.user`에 사용자의 인스턴스와 역할이 포함되어 있다고 가정합니다. 사용자 정의 **인증 가드**(또는 미들웨어)에서 관련 기능을 구현하게 될 것입니다. 해당 주제에 대한 자세한 정보는 [이 챕터](/security/authentication)에서 확인해 주세요.\n\n> warning **주의** `matchRoels()` 함수 내부 로직은 필요에 따라 단순할 수도 복잡할 수도 있습니다. 중요한 건 이 예제는 그저 가드를 요청부터 응답까지의 사이클 속에 끼워 맞추는지 보여주기 위함입니다.\n\n`Reflector`를 컨텍스트에 따라 다르게 활용하는 방법과 같이 보다 세부적인 내용은 **실행 컨텍스트** 챕터의 <a href=\"https://docs.nestjs.com/fundamentals/execution-context#reflection-and-metadata\">Reflection과 메타데이터</a> 섹션에서 확인하실 수 있습니다.\n\n권한이 불충분한 사용자가 요청을 한다면 Nest가 알아서 다음의 응답을 보냅니다:\n\n```typescript\n{\n  \"statusCode\": 403,\n  \"message\": \"Forbidden resource\",\n  \"error\": \"Forbidden\"\n}\n```\n\n가드가 `false`를 반환하면 프레임워크 내부적으로 `ForbiddenException`예외를 발생시킨다는 것을 기억하시길 바랍니다. 다른 에러를 응답하고 싶다면 아래 예시처럼 원하는 예외를 발생시키면 됩니다.\n\n```typescript\nthrow new UnauthorizedException();\n```\n\n가드에서 발생시킨 예외는 [예외 계층](/exception-filters)(전역 예외 필터와 현재 컨텍스트에 적용된 예외 필터들)에서 처리됩니다.\n\n> info **힌트** 실무에서 승인을 어떻게 구현하는지 알고 싶다면 [이 챕터](/security/authorization)를 확인해 보세요.\n"
  },
  {
    "path": "content/interceptors.md",
    "content": "### Interceptors\n\nAn interceptor is a class annotated with the `@Injectable()` decorator. Interceptors should implement the `NestInterceptor` interface.\n\n<figure><img src=\"/assets/Interceptors_1.png\" /></figure>\n\nInterceptors have a set of useful capabilities which are inspired by the [Aspect Oriented Programming](https://en.wikipedia.org/wiki/Aspect-oriented_programming) (AOP) technique. They make it possible to:\n\n- bind extra logic before / after method execution\n- transform the result returned from a function\n- transform the exception thrown from a function\n- extend the basic function behavior\n- completely override a function depending on specific conditions (e.g., for caching purposes)\n\n#### Basics\n\nEach interceptor implements the `intercept()` method, which takes two arguments. The first one is the `ExecutionContext` instance (exactly the same object as for [guards](/guards)). The `ExecutionContext` inherits from `ArgumentsHost`. We saw `ArgumentsHost` before in the exception filters chapter. There, we saw that it's a wrapper around arguments that have been passed to the original handler, and contains different arguments arrays based on the type of the application. You can refer back to the [exception filters](https://docs.nestjs.com/exception-filters#arguments-host) for more on this topic.\n\n#### Execution context\n\nBy extending `ArgumentsHost`, `ExecutionContext` also adds several new helper methods that provide additional details about the current execution process. These details can be helpful in building more generic interceptors that can work across a broad set of controllers, methods, and execution contexts. Learn more about `ExecutionContext` [here](/fundamentals/execution-context).\n\n#### Call handler\n\nThe second argument is a `CallHandler`. The `CallHandler` interface implements the `handle()` method, which you can use to invoke the route handler method at some point in your interceptor. If you don't call the `handle()` method in your implementation of the `intercept()` method, the route handler method won't be executed at all.\n\nThis approach means that the `intercept()` method effectively **wraps** the request/response stream. As a result, you may implement custom logic **both before and after** the execution of the final route handler. It's clear that you can write code in your `intercept()` method that executes **before** calling `handle()`, but how do you affect what happens afterward? Because the `handle()` method returns an `Observable`, we can use powerful [RxJS](https://github.com/ReactiveX/rxjs) operators to further manipulate the response. Using Aspect Oriented Programming terminology, the invocation of the route handler (i.e., calling `handle()`) is called a [Pointcut](https://en.wikipedia.org/wiki/Pointcut), indicating that it's the point at which our additional logic is inserted.\n\nConsider, for example, an incoming `POST /cats` request. This request is destined for the `create()` handler defined inside the `CatsController`. If an interceptor which does not call the `handle()` method is called anywhere along the way, the `create()` method won't be executed. Once `handle()` is called (and its `Observable` has been returned), the `create()` handler will be triggered. And once the response stream is received via the `Observable`, additional operations can be performed on the stream, and a final result returned to the caller.\n\n<app-banner-shop></app-banner-shop>\n\n#### Aspect interception\n\nThe first use case we'll look at is to use an interceptor to log user interaction (e.g., storing user calls, asynchronously dispatching events or calculating a timestamp). We show a simple `LoggingInterceptor` below:\n\n```typescript\n@@filename(logging.interceptor)\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { tap } from 'rxjs/operators';\n\n@Injectable()\nexport class LoggingInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    console.log('Before...');\n\n    const now = Date.now();\n    return next\n      .handle()\n      .pipe(\n        tap(() => console.log(`After... ${Date.now() - now}ms`)),\n      );\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { tap } from 'rxjs/operators';\n\n@Injectable()\nexport class LoggingInterceptor {\n  intercept(context, next) {\n    console.log('Before...');\n\n    const now = Date.now();\n    return next\n      .handle()\n      .pipe(\n        tap(() => console.log(`After... ${Date.now() - now}ms`)),\n      );\n  }\n}\n```\n\n> info **Hint** The `NestInterceptor<T, R>` is a generic interface in which `T` indicates the type of an `Observable<T>` (supporting the response stream), and `R` is the type of the value wrapped by `Observable<R>`.\n\n> warning **Notice** Interceptors, like controllers, providers, guards, and so on, can **inject dependencies** through their `constructor`.\n\nSince `handle()` returns an RxJS `Observable`, we have a wide choice of operators we can use to manipulate the stream. In the example above, we used the `tap()` operator, which invokes our anonymous logging function upon graceful or exceptional termination of the observable stream, but doesn't otherwise interfere with the response cycle.\n\n#### Binding interceptors\n\nIn order to set up the interceptor, we use the `@UseInterceptors()` decorator imported from the `@nestjs/common` package. Like [pipes](/pipes) and [guards](/guards), interceptors can be controller-scoped, method-scoped, or global-scoped.\n\n```typescript\n@@filename(cats.controller)\n@UseInterceptors(LoggingInterceptor)\nexport class CatsController {}\n```\n\n> info **Hint** The `@UseInterceptors()` decorator is imported from the `@nestjs/common` package.\n\nUsing the above construction, each route handler defined in `CatsController` will use `LoggingInterceptor`. When someone calls the `GET /cats` endpoint, you'll see the following output in your standard output:\n\n```typescript\nBefore...\nAfter... 1ms\n```\n\nNote that we passed the `LoggingInterceptor` type (instead of an instance), leaving responsibility for instantiation to the framework and enabling dependency injection. As with pipes, guards, and exception filters, we can also pass an in-place instance:\n\n```typescript\n@@filename(cats.controller)\n@UseInterceptors(new LoggingInterceptor())\nexport class CatsController {}\n```\n\nAs mentioned, the construction above attaches the interceptor to every handler declared by this controller. If we want to restrict the interceptor's scope to a single method, we simply apply the decorator at the **method level**.\n\nIn order to set up a global interceptor, we use the `useGlobalInterceptors()` method of the Nest application instance:\n\n```typescript\nconst app = await NestFactory.create(AppModule);\napp.useGlobalInterceptors(new LoggingInterceptor());\n```\n\nGlobal interceptors are used across the whole application, for every controller and every route handler. In terms of dependency injection, global interceptors registered from outside of any module (with `useGlobalInterceptors()`, as in the example above) cannot inject dependencies since this is done outside the context of any module. In order to solve this issue, you can set up an interceptor **directly from any module** using the following construction:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: LoggingInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n> info **Hint** When using this approach to perform dependency injection for the interceptor, note that regardless of the\n> module where this construction is employed, the interceptor is, in fact, global. Where should this be done? Choose the module\n> where the interceptor (`LoggingInterceptor` in the example above) is defined. Also, `useClass` is not the only way of dealing with custom provider registration. Learn more [here](/fundamentals/custom-providers).\n\n#### Response mapping\n\nWe already know that `handle()` returns an `Observable`. The stream contains the value **returned** from the route handler, and thus we can easily mutate it using RxJS's `map()` operator.\n\n> warning **Warning** The response mapping feature doesn't work with the library-specific response strategy (using the `@Res()` object directly is forbidden).\n\nLet's create the `TransformInterceptor`, which will modify each response in a trivial way to demonstrate the process. It will use RxJS's `map()` operator to assign the response object to the `data` property of a newly created object, returning the new object to the client.\n\n```typescript\n@@filename(transform.interceptor)\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nexport interface Response<T> {\n  data: T;\n}\n\n@Injectable()\nexport class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {\n    return next.handle().pipe(map(data => ({ data })));\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class TransformInterceptor {\n  intercept(context, next) {\n    return next.handle().pipe(map(data => ({ data })));\n  }\n}\n```\n\n> info **Hint** Nest interceptors work with both synchronous and asynchronous `intercept()` methods. You can simply switch the method to `async` if necessary.\n\nWith the above construction, when someone calls the `GET /cats` endpoint, the response would look like the following (assuming that route handler returns an empty array `[]`):\n\n```json\n{\n  \"data\": []\n}\n```\n\nInterceptors have great value in creating re-usable solutions to requirements that occur across an entire application.\nFor example, imagine we need to transform each occurrence of a `null` value to an empty string `''`. We can do it using one line of code and bind the interceptor globally so that it will automatically be used by each registered handler.\n\n```typescript\n@@filename()\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class ExcludeNullInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next\n      .handle()\n      .pipe(map(value => value === null ? '' : value ));\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\nimport { map } from 'rxjs/operators';\n\n@Injectable()\nexport class ExcludeNullInterceptor {\n  intercept(context, next) {\n    return next\n      .handle()\n      .pipe(map(value => value === null ? '' : value ));\n  }\n}\n```\n\n#### Exception mapping\n\nAnother interesting use-case is to take advantage of RxJS's `catchError()` operator to override thrown exceptions:\n\n```typescript\n@@filename(errors.interceptor)\nimport {\n  Injectable,\n  NestInterceptor,\n  ExecutionContext,\n  BadGatewayException,\n  CallHandler,\n} from '@nestjs/common';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\n@Injectable()\nexport class ErrorsInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next\n      .handle()\n      .pipe(\n        catchError(err => throwError(new BadGatewayException())),\n      );\n  }\n}\n@@switch\nimport { Injectable, BadGatewayException } from '@nestjs/common';\nimport { throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\n@Injectable()\nexport class ErrorsInterceptor {\n  intercept(context, next) {\n    return next\n      .handle()\n      .pipe(\n        catchError(err => throwError(new BadGatewayException())),\n      );\n  }\n}\n```\n\n#### Stream overriding\n\nThere are several reasons why we may sometimes want to completely prevent calling the handler and return a different value instead. An obvious example is to implement a cache to improve response time. Let's take a look at a simple **cache interceptor** that returns its response from a cache. In a realistic example, we'd want to consider other factors like TTL, cache invalidation, cache size, etc., but that's beyond the scope of this discussion. Here we'll provide a basic example that demonstrates the main concept.\n\n```typescript\n@@filename(cache.interceptor)\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';\nimport { Observable, of } from 'rxjs';\n\n@Injectable()\nexport class CacheInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    const isCached = true;\n    if (isCached) {\n      return of([]);\n    }\n    return next.handle();\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\nimport { of } from 'rxjs';\n\n@Injectable()\nexport class CacheInterceptor {\n  intercept(context, next) {\n    const isCached = true;\n    if (isCached) {\n      return of([]);\n    }\n    return next.handle();\n  }\n}\n```\n\nOur `CacheInterceptor` has a hardcoded `isCached` variable and a hardcoded response `[]` as well. The key point to note is that we return a new stream here, created by the RxJS `of()` operator, therefore the route handler **won't be called** at all. When someone calls an endpoint that makes use of `CacheInterceptor`, the response (a hardcoded, empty array) will be returned immediately. In order to create a generic solution, you can take advantage of `Reflector` and create a custom decorator. The `Reflector` is well described in the [guards](/guards) chapter.\n\n#### More operators\n\nThe possibility of manipulating the stream using RxJS operators gives us many capabilities. Let's consider another common use case. Imagine you would like to handle **timeouts** on route requests. When your endpoint doesn't return anything after a period of time, you want to terminate with an error response. The following construction enables this:\n\n```typescript\n@@filename(timeout.interceptor)\nimport { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';\nimport { Observable, throwError, TimeoutError } from 'rxjs';\nimport { catchError, timeout } from 'rxjs/operators';\n\n@Injectable()\nexport class TimeoutInterceptor implements NestInterceptor {\n  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {\n    return next.handle().pipe(\n      timeout(5000),\n      catchError(err => {\n        if (err instanceof TimeoutError) {\n          return throwError(new RequestTimeoutException());\n        }\n        return throwError(err);\n      }),\n    );\n  };\n};\n@@switch\nimport { Injectable, RequestTimeoutException } from '@nestjs/common';\nimport { Observable, throwError, TimeoutError } from 'rxjs';\nimport { catchError, timeout } from 'rxjs/operators';\n\n@Injectable()\nexport class TimeoutInterceptor {\n  intercept(context, next) {\n    return next.handle().pipe(\n      timeout(5000),\n      catchError(err => {\n        if (err instanceof TimeoutError) {\n          return throwError(new RequestTimeoutException());\n        }\n        return throwError(err);\n      }),\n    );\n  };\n};\n```\n\nAfter 5 seconds, request processing will be canceled. You can also add custom logic before throwing `RequestTimeoutException` (e.g. release resources).\n"
  },
  {
    "path": "content/introduction.md",
    "content": "### Introduction\n\nNest(NestJS)는 효율적이고 확장 가능한 [Node.js](https://nodejs.org/) 서버 어플리케이션을 구축하기 위한 프레임워크입니다. 프로그레시브 자바스크립트를 사용하고, [타입스크립트](http://www.typescriptlang.org/)를 완벽히 지원하며 빌드에 사용합니다. (하지만 여전히 순수한 자바스크립트로도 코딩할 수 있습니다.) 또한 OOP(Object Oriented Programming), FP(Functional Reactive Programming) 및 FRP(Functional Reactive Programming)의 요소들을 결합하고 있습니다.\n\n내부적으로 Nest는 [Express](https://expressjs.com/)(기본값)와 같은 강력한 HTTP 서버 프레임워크를 사용하며, 선택적으로 [Fastify](https://github.com/fastify/fastify)를 사용하도록 구성할 수도 있습니다!\n\nNest는 일반적인 Node.js 프레임워크(Express/Fastify) 위에 일정 수준의 추상화를 제공하지만, 또한 개발자에게 직접 프레임워크 API를 노출하기도 합니다. 이것을 통해 개발자들이 기반 플랫폼에서 이용 가능한 무수한 서드 파티 모듈을 자유롭게 사용할 수 있게 해줍니다.\n\n#### Philosophy\n\n최근에 들어서 Node.js 덕분에 자바스크립트는 프론트엔드 및 백엔드 어플리케이션 모두에서 웹의 \"공용어\"가 되었습니다. 이로 인해 [Angular](https://angular.io/), [React](https://github.com/facebook/react) 및 [Vue](https://github.com/vuejs/vue)와 같이 개발자의 생산성을 높여주며, 빠르고, 테스트 할 수 있고, 확장성 있는 프론트엔드 어플리케이션을 만들 수 있는 멋진 프로젝트들이 생겨났습니다. 그러나 백엔드는 Node(및 서버측 JavaScript)의 우수한 라이브러리, 헬퍼 및 도구가 많이 존재함에도, **구조적인** 주요 문제를 효과적으로 해결하는 프로젝트가 없습니다.\n\nNest는 개발자와 팀에게 테스트 가능하며, 확장성 있고, 느슨하게 결합되고, 유지 및 보수가 용이한 어플리케이션을 만들 수 있는, 즉시 사용 가능한 어플리케이션 아키텍처를 제공합니다. 이 아키텍처는 Angular에서 많은 영감을 받았습니다.\n\n#### Installation\n\nNest를 시작하기 위해 [Nest CLI](/cli/overview)를 사용해 프로젝트를 스캐폴드 하거나, 또는 스타터 프로젝트를 클론할 수 있습니다. (두 가지 방법 모두 같은 결과물을 도출합니다.)\n\nNest CLI를 사용하여 프로젝트를 스캐폴드 하려면 다음 명령을 실행합니다. 이는 새 프로젝트 디렉토리를 생성하고, 디렉토리 내부에 Nest 초기 핵심 파일들과 지원 모듈을 생성하여 프로젝트에 대한 기본 구조를 잡아줍니다. 처음 사용자는 **Nest CLI**를 사용하여 새 프로젝트를 생성하는 것을 추천합니다. 이 방법은 [First Steps](first-steps)에서 계속 진행하겠습니다.\n\n```bash\n$ npm i -g @nestjs/cli\n$ nest new project-name\n```\n\n#### Alternatives\n\n**Git**을 이용해 타입스크립트 스타터 프로젝트를 설치하려면:\n\n```bash\n$ git clone https://github.com/nestjs/typescript-starter.git project\n$ cd project\n$ npm install\n$ npm run start\n```\n\n> info **힌트** 만약 git history 없이 clone 하고 싶다면, [degit](https://github.com/Rich-Harris/degit)을 사용할 수 있습니다.\n\n브라우저를 열고 [`http://localhost:3000/`](http://localhost:3000/)로 이동합니다.\n\n자바스크립트 버전의 스타터 프로젝트를 설치하고자 한다면, 위의 커맨드에 `javascript-starter.git`를 사용하십시오.\n\n또한 **npm** (또는 **yarn**)을 사용하여 Nest 코어와 지원 파일을 설치하면 처음부터 수동으로 새 프로젝트를 생성할 수도 있습니다. 물론 이 경우에는 프로젝트의 보일러 플레이트 파일을 직접 생성해야 합니다.\n\n```bash\n$ npm i --save @nestjs/core @nestjs/common rxjs reflect-metadata\n```\n"
  },
  {
    "path": "content/microservices/basics.md",
    "content": "### 개요\n\nNest는 모놀리식 아키텍쳐라 불리우는 전통적인 방식의 어플리케이션 아키텍쳐 방식 뿐만 아니라 마이크로서비스 아키텍쳐 방식의 개발을 기본적으로 지원합니다. 이 문서에 다루는 모든 것들 -- 예를 들어, 의존성 주입, 데코레이터, 예외 처리, 파이프, 가드와 인터셉터 -- 은 마이크로서비스 아키텍쳐에 동일하게 적용이 됩니다. 가능한 모든 상황에서, Nest는 구현에 관한 세부적인 부분들을 추상화하여 동일한 컴포넌트를 HTTP기반의 플랫폼, 웹소켓 및 마이크로서비스에서 실행할 수 있도록 합니다. 이 섹션에서는 Nest의 마이크로서비스 관련한 부분을 설명합니다.\n\nNest에서는, 마이크로서비스는 기본적으로는 HTTP와 다른 **전송** 계층을 사용하는 어플리케이션입니다.\n\n<figure><img src=\"/assets/Microservices_1.png\" /></figure>\n\nNest는 **트랜스포터**라 불리우는 전송 계층 구현체들을 지원합니다. 트랜스포터란 각각의 마이크로서비스 인스턴스들간의 메시지 전송을 담당하고 있습니다. 대부분의 트랜스포터들은 기본적으로 **요청-응답** 과 **이벤트 기반**의 메시지 전송 스타일을 지원합니다. Nest는 각 트랜스포터의 구현에 대한 세부적인 정보를 추상화하여 요청-응답 및 이벤트 기반 메시지 전송을 지원합니다. 이는 어플리케이션에 영향이 없이 한 전송 계층에서 다른 전송 계층으로의 변환 -- 예로 특정 전송 계층의 확실한 신뢰도나 성능 향상을 위해서 -- 을 쉽게 해줍니다. \n\n#### 설치\n\n마이크로서비스를 시작하려면, 다음 필수 패키지를 설치해야합니다:\n\n```bash\n$ npm i --save @nestjs/microservices\n```\n\n#### 시작하기\n\n마이크로서비스를 시작하려면, `NestFactory` 클래스의 `createMicroservice()` 메서드를 사용합니다:\n\n```typescript\n@@filename(main)\nimport { NestFactory } from '@nestjs/core';\nimport { Transport, MicroserviceOptions } from '@nestjs/microservices';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice<MicroserviceOptions>(\n    AppModule,\n    {\n      transport: Transport.TCP,\n    },\n  );\n  app.listen();\n}\nbootstrap();\n@@switch\nimport { NestFactory } from '@nestjs/core';\nimport { Transport, MicroserviceOptions } from '@nestjs/microservices';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.createMicroservice(AppModule, {\n    transport: Transport.TCP,\n  });\n  app.listen(() => console.log('Microservice is listening'));\n}\nbootstrap();\n```\n\n> 정보 **힌트** 마이크로서비스는 기본값으로 **TCP** 전송 계층을 사용합니다.\n\n`createMicroservice()` 메서드의 두번째 인자는 `options` 객체입니다. 이 인자는 두 개의 멤버로 구성될 수 있습니다:\n\n<table>\n  <tr>\n    <td><code>transport</code></td>\n    <td>특정 트랜스포터 (예로, <code>Transport.NATS</code>)</td>\n  </tr>\n  <tr>\n    <td><code>options</code></td>\n    <td>트랜스포터의 행동을 결정하는 `options` 객체</td>\n  </tr>\n</table>\n<p>\n  <code>options</code> 객체는 선택된 트랜스포터에 따라 특정됩니다. <strong>TCP</strong> 트랜스포터의 경우에는 다음과 같은 프로퍼티를 제공합니다. 다른 트랜스포터의 경우는 (예를 들어, Redis, MQTT, 기타등등), 해당 관련있는 챕터의 설명을 참조하세요.\n</p>\n<table>\n  <tr>\n    <td><code>host</code></td>\n    <td>Connection 호스트 이름</td>\n  </tr>\n  <tr>\n    <td><code>port</code></td>\n    <td>Connection 포트</td>\n  </tr>\n  <tr>\n    <td><code>retryAttempts</code></td>\n    <td>메시지 재시도 횟수 (기본값: <code>0</code>)</td>\n  </tr>\n  <tr>\n    <td><code>retryDelay</code></td>\n    <td>메시지 재시도 횟수간의 시간 간격 (ms) (기본값: <code>0</code>)</td>\n  </tr>\n</table>\n\n#### 패턴\n\n마이크로서비스는 **패턴들**을 통해서 메시지들과 이벤트들을 인식합니다. 패턴이란 문자열, 객체 리터럴와 같은 평범한 값입니다. 패턴들은 자동적으로 직럴화되고 메시지의 데이터 부분과 함께 네트워크에 전송됩니다. 이러한 방식으로 메시지 송신자와 수신자가 어떤 요청을 어떤 핸들러를 통해 처리할지 조정할 수 있습니다.\n\n#### Request-response\n\nThe request-response message style is useful when you need to **exchange** messages between various external services. With this paradigm, you can be certain that the service has actually received the message (without the need to manually implement a message ACK protocol). However, the request-response paradigm is not always the best choice. For example, streaming transporters that use log-based persistence, such as [Kafka](https://docs.confluent.io/3.0.0/streams/) or [NATS streaming](https://github.com/nats-io/node-nats-streaming), are optimized for solving a different range of issues, more aligned with an event messaging paradigm (see [event-based messaging](https://docs.nestjs.com/microservices/basics#event-based) below for more details).\n\nTo enable the request-response message type, Nest creates two logical channels - one is responsible for transferring the data while the other waits for incoming responses. For some underlying transports, such as [NATS](https://nats.io/), this dual-channel support is provided out-of-the-box. For others, Nest compensates by manually creating separate channels. There can be overhead for this, so if you do not require a request-response message style, you should consider using the event-based method.\n\nTo create a message handler based on the request-response paradigm use the `@MessagePattern()` decorator, which is imported from the `@nestjs/microservices` package. This decorator should be used only within the [controller](https://docs.nestjs.com/controllers) classes since they are the entry points for your application. Using them inside providers won't have any effect as they are simply ignored by Nest runtime.\n\n```typescript\n@@filename(math.controller)\nimport { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\n\n@Controller()\nexport class MathController {\n  @MessagePattern({ cmd: 'sum' })\n  accumulate(data: number[]): number {\n    return (data || []).reduce((a, b) => a + b);\n  }\n}\n@@switch\nimport { Controller } from '@nestjs/common';\nimport { MessagePattern } from '@nestjs/microservices';\n\n@Controller()\nexport class MathController {\n  @MessagePattern({ cmd: 'sum' })\n  accumulate(data) {\n    return (data || []).reduce((a, b) => a + b);\n  }\n}\n```\n\nIn the above code, the `accumulate()` **message handler** listens for messages that fulfill the `{{ '{' }} cmd: 'sum' {{ '}' }}` message pattern. The message handler takes a single argument, the `data` passed from the client. In this case, the data is an array of numbers which are to be accumulated.\n\n#### Asynchronous responses\n\nMessage handlers are able to respond either synchronously or **asynchronously**. Hence, `async` methods are supported.\n\n```typescript\n@@filename()\n@MessagePattern({ cmd: 'sum' })\nasync accumulate(data: number[]): Promise<number> {\n  return (data || []).reduce((a, b) => a + b);\n}\n@@switch\n@MessagePattern({ cmd: 'sum' })\nasync accumulate(data) {\n  return (data || []).reduce((a, b) => a + b);\n}\n```\n\nA message handler is also able to return an `Observable`, in which case the result values will be emitted until the stream is completed.\n\n```typescript\n@@filename()\n@MessagePattern({ cmd: 'sum' })\naccumulate(data: number[]): Observable<number> {\n  return from([1, 2, 3]);\n}\n@@switch\n@MessagePattern({ cmd: 'sum' })\naccumulate(data: number[]): Observable<number> {\n  return from([1, 2, 3]);\n}\n```\n\nIn the example above, the message handler will respond **3 times** (with each item from the array).\n\n#### Event-based\n\nWhile the request-response method is ideal for exchanging messages between services, it is less suitable when your message style is event-based - when you just want to publish **events** without waiting for a response. In that case, you do not want the overhead required by request-response for maintaining two channels.\n\nSuppose you would like to simply notify another service that a certain condition has occurred in this part of the system. This is the ideal use case for the event-based message style.\n\nTo create an event handler, we use the `@EventPattern()` decorator, which is imported from the `@nestjs/microservices` package.\n\n```typescript\n@@filename()\n@EventPattern('user_created')\nasync handleUserCreated(data: Record<string, unknown>) {\n  // business logic\n}\n@@switch\n@EventPattern('user_created')\nasync handleUserCreated(data) {\n  // business logic\n}\n```\n\n> info **Hint** You can register multiple event handlers for a **single** event pattern and all of them will be automatically triggered in parallel.\n\nThe `handleUserCreated()` **event handler** listens for the `'user_created'` event. The event handler takes a single argument, the `data` passed from the client (in this case, an event payload which has been sent over the network).\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Decorators\n\nIn more sophisticated scenarios, you may want to access more information about the incoming request. For example, in the case of NATS with wildcard subscriptions, you may want to get the original subject that the producer has sent the message to. Likewise, in Kafka you may want to access the message headers. In order to accomplish that, you can use built-in decorators as follows:\n\n```typescript\n@@filename()\n@MessagePattern('time.us.*')\ngetDate(@Payload() data: number[], @Ctx() context: NatsContext) {\n  console.log(`Subject: ${context.getSubject()}`); // e.g. \"time.us.east\"\n  return new Date().toLocaleTimeString(...);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('time.us.*')\ngetDate(data, context) {\n  console.log(`Subject: ${context.getSubject()}`); // e.g. \"time.us.east\"\n  return new Date().toLocaleTimeString(...);\n}\n```\n\n> info **Hint** `@Payload()`, `@Ctx()` and `NatsContext` are imported from `@nestjs/microservices`.\n\n> info **Hint** You can also pass in a property key to the `@Payload()` decorator to extract a specific property from the incoming payload object, for example, `@Payload('id')`.\n\n#### Client\n\nA client Nest application can exchange messages or publish events to a Nest microservice using the `ClientProxy` class. This class defines several methods, such as `send()` (for request-response messaging) and `emit()` (for event-driven messaging) that let you communicate with a remote microservice. Obtain an instance of this class in one of the following ways.\n\nOne technique is to import the `ClientsModule`, which exposes the static `register()` method. This method takes an argument which is an array of objects representing microservice transporters. Each such object has a `name` property, an optional `transport` property (default is `Transport.TCP`), and an optional transporter-specific `options` property.\n\nThe `name` property serves as an **injection token** that can be used to inject an instance of a `ClientProxy` where needed. The value of the `name` property, as an injection token, can be an arbitrary string or JavaScript symbol, as described [here](https://docs.nestjs.com/fundamentals/custom-providers#non-class-based-provider-tokens).\n\nThe `options` property is an object with the same properties we saw in the `createMicroservice()` method earlier.\n\n```typescript\n@Module({\n  imports: [\n    ClientsModule.register([\n      { name: 'MATH_SERVICE', transport: Transport.TCP },\n    ]),\n  ]\n  ...\n})\n```\n\nOnce the module has been imported, we can inject an instance of the `ClientProxy` configured as specified via the `'MATH_SERVICE'` transporter options shown above, using the `@Inject()` decorator.\n\n```typescript\nconstructor(\n  @Inject('MATH_SERVICE') private client: ClientProxy,\n) {}\n```\n\n> info **Hint** The `ClientsModule` and `ClientProxy` classes are imported from the `@nestjs/microservices` package.\n\nAt times we may need to fetch the transporter configuration from another service (say a `ConfigService`), rather than hard-coding it in our client application. To do this, we can register a [custom provider](/fundamentals/custom-providers) using the `ClientProxyFactory` class. This class has a static `create()` method, which accepts a transporter options object, and returns a customized `ClientProxy` instance.\n\n```typescript\n@Module({\n  providers: [\n    {\n      provide: 'MATH_SERVICE',\n      useFactory: (configService: ConfigService) => {\n        const mathSvcOptions = configService.getMathSvcOptions();\n        return ClientProxyFactory.create(mathSvcOptions);\n      },\n      inject: [ConfigService],\n    }\n  ]\n  ...\n})\n```\n\n> info **Hint** The `ClientProxyFactory` is imported from the `@nestjs/microservices` package.\n\nAnother option is to use the `@Client()` property decorator.\n\n```typescript\n@Client({ transport: Transport.TCP })\nclient: ClientProxy;\n```\n\n> info **Hint** The `@Client()` decorator is imported from the `@nestjs/microservices` package.\n\nUsing the `@Client()` decorator is not the preferred technique, as it is harder to test and harder to share a client instance.\n\nThe `ClientProxy` is **lazy**. It doesn't initiate a connection immediately. Instead, it will be established before the first microservice call, and then reused across each subsequent call. However, if you want to delay the application bootstrapping process until a connection is established, you can manually initiate a connection using the `ClientProxy` object's `connect()` method inside the `OnApplicationBootstrap` lifecycle hook.\n\n```typescript\n@@filename()\nasync onApplicationBootstrap() {\n  await this.client.connect();\n}\n```\n\nIf the connection cannot be created, the `connect()` method will reject with the corresponding error object.\n\n#### Sending messages\n\nThe `ClientProxy` exposes a `send()` method. This method is intended to call the microservice and returns an `Observable` with its response. Thus, we can subscribe to the emitted values easily.\n\n```typescript\n@@filename()\naccumulate(): Observable<number> {\n  const pattern = { cmd: 'sum' };\n  const payload = [1, 2, 3];\n  return this.client.send<number>(pattern, payload);\n}\n@@switch\naccumulate() {\n  const pattern = { cmd: 'sum' };\n  const payload = [1, 2, 3];\n  return this.client.send(pattern, payload);\n}\n```\n\nThe `send()` method takes two arguments, `pattern` and `payload`. The `pattern` should match one defined in a `@MessagePattern()` decorator. The `payload` is a message that we want to transmit to the remote microservice. This method returns a **cold `Observable`**, which means that you have to explicitly subscribe to it before the message will be sent.\n\n#### Publishing events\n\nTo send an event, use the `ClientProxy` object's `emit()` method. This method publishes an event to the message broker.\n\n```typescript\n@@filename()\nasync publish() {\n  this.client.emit<number>('user_created', new UserCreatedEvent());\n}\n@@switch\nasync publish() {\n  this.client.emit('user_created', new UserCreatedEvent());\n}\n```\n\nThe `emit()` method takes two arguments, `pattern` and `payload`. The `pattern` should match one defined in an `@EventPattern()` decorator. The `payload` is an event payload that we want to transmit to the remote microservice. This method returns a **hot `Observable`** (unlike the cold `Observable` returned by `send()`), which means that whether or not you explicitly subscribe to the observable, the proxy will immediately try to deliver the event.\n\n<app-banner-shop></app-banner-shop>\n\n#### Scopes\n\nFor people coming from different programming language backgrounds, it might be unexpected to learn that in Nest, almost everything is shared across incoming requests. We have a connection pool to the database, singleton services with global state, etc. Remember that Node.js doesn't follow the request/response Multi-Threaded Stateless Model in which every request is processed by a separate thread. Hence, using singleton instances is fully **safe** for our applications.\n\nHowever, there are edge-cases when request-based lifetime of the handler may be the desired behavior, for instance per-request caching in GraphQL applications, request tracking or multi-tenancy. Learn how to control scopes [here](/fundamentals/injection-scopes).\n\nRequest-scoped handlers and providers can inject `RequestContext` using the `@Inject()` decorator in combination with `CONTEXT` token:\n\n```typescript\nimport { Injectable, Scope, Inject } from '@nestjs/common';\nimport { CONTEXT, RequestContext } from '@nestjs/microservices';\n\n@Injectable({ scope: Scope.REQUEST })\nexport class CatsService {\n  constructor(@Inject(CONTEXT) private ctx: RequestContext) {}\n}\n```\n\nThis provides access to the `RequestContext` object, which has two properties:\n\n```typescript\nexport interface RequestContext<T = any> {\n  pattern: string | Record<string, any>;\n  data: T;\n}\n```\n\nThe `data` property is the message payload sent by the message producer. The `pattern` property is the pattern used to identify an appropriate handler to handle the incoming message.\n\n#### Handling timeouts\n\nIn distributed systems, sometimes microservices might be down or not available. To avoid infinitely long waiting, you can use Timeouts. A timeout is an incredibly useful pattern when communicating with other services. To apply timeouts to your microservice calls, you can use the `RxJS` timeout operator. If the microservice does not respond to the request within a certain time, an exception is thrown, which can be caught and handled appropriately.\n\nTo solve this problem you have to use [rxjs](https://github.com/ReactiveX/rxjs) package. Just use the `timeout` operator in the pipe:\n\n```typescript\n@@filename()\nthis.client\n      .send<TResult, TInput>(pattern, data)\n      .pipe(timeout(5000))\n      .toPromise();\n@@switch\nthis.client\n      .send(pattern, data)\n      .pipe(timeout(5000))\n      .toPromise();\n```\n\n> info **Hint** The `timeout` operator is imported from the `rxjs/operators` package.\n\nAfter 5 seconds, if the microservice isn't responding, it will throw an error.\n"
  },
  {
    "path": "content/microservices/custom-transport.md",
    "content": "### Custom transporters\n\nNest provides a variety of **transporters** out-of-the-box, as well as an API allowing developers to build new custom transport strategies.\nTransporters enable you to connect components over a network using a pluggable communications layer and a very simple application-level message protocol (read full [article](https://dev.to/nestjs/integrate-nestjs-with-external-services-using-microservice-transporters-part-1-p3)).\n\n> info **Hint** Building a microservice with Nest does not necessarily mean you must use the `@nestjs/microservices` package. For example, if you want to communicate with external services (let's say other microservices written in different languages), you may not need all the features provided by `@nestjs/microservice` library.\n> In fact, if you don't need decorators (`@EventPattern` or `@MessagePattern`) that let you declaratively define subscribers, running a [Standalone Application](/application-context) and manually maintaining connection/subscribing to channels should be enough for most use-cases and will provide you with more flexibility.\n\nWith a custom transporter, you can integrate any messaging system/protocol (including Google Cloud Pub/Sub, Amazon Kinesis, and others) or extend the existing one, adding extra features on top (for example, [QoS](https://github.com/mqttjs/MQTT.js/blob/master/README.md#qos) for MQTT).\n\n> info **Hint** To better understand how Nest microservices work and how you can extend the capabilities of existing transporters, we recommend reading the [NestJS Microservices in Action](https://dev.to/johnbiundo/series/4724) and [Advanced NestJS Microservices](https://dev.to/nestjs/part-1-introduction-and-setup-1a2l) article series.\n\n#### Creating a strategy\n\nFirst, let's define a class representing our custom transporter.\n\n```typescript\nimport { CustomTransportStrategy, Server } from '@nestjs/microservices';\n\nclass GoogleCloudPubSubServer\n  extends Server\n  implements CustomTransportStrategy {\n  /**\n   * This method is triggered when you run \"app.listen()\".\n   */\n  listen(callback: () => void) {\n    callback();\n  }\n\n  /**\n   * This method is triggered on application shutdown.\n   */\n  close() {}\n}\n```\n\n> warning **Warning** Please, note we won't be implementing a fully-featured Google Cloud Pub/Sub server in this chapter as this would require diving into transporter specific technical details.\n\nIn our example above, we declared the `GoogleCloudPubSubServer` class and provided `listen()` and `close()` methods enforced by the `CustomTransportStrategy` interface.\nAlso, our class extends the `Server` class imported from the `@nestjs/microservices` package that provides a few useful methods, for example, methods used by Nest runtime to register message handlers. Alternatively, in case you want to extend the capabilities of an existing transport strategy, you could extend the corresponding server class, for example, `ServerRedis`.\nConventionally, we added the `\"Server\"` suffix to our class as it will be responsible for subscribing to messages/events (and responding to them, if necessary).\n\nWith this in place, we can now use our custom strategy instead of using a built-in transporter, as follows:\n\n```typescript\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(\n  AppModule,\n  {\n    strategy: new GoogleCloudPubSubServer(),\n  },\n);\n```\n\nBasically, instead of passing the normal transporter options object with `transport` and `options` properties, we pass a single property, `strategy`, whose value is an instance of our custom transporter class.\n\nBack to our `GoogleCloudPubSubServer` class, in a real-world application, we would be establishing a connection to our message broker/external service and registering subscribers/listening to specific channels in `listen()` method (and then removing subscriptions & closing the connection in the `close()` teardown method),\nbut since this requires a good understanding of how Nest microservices communicate with each other, we recommend reading this [article series](https://dev.to/nestjs/part-1-introduction-and-setup-1a2l).\nIn this chapter instead, we'll focus on the capabilities the `Server` class provides and how you can leverage them to build custom strategies.\n\nFor example, let's say that somewhere in our application, the following message handler is defined:\n\n```typescript\n@MessagePattern('echo')\necho(@Payload() data: object) {\n  return data;\n}\n```\n\nThis message handler will be automatically registered by Nest runtime. With `Server` class, you can see what message patterns have been registered and also, access and execute the actual methods that were assigned to them.\nTo test this out, let's add a simple `console.log` inside `listen()` method before `callback` function is called:\n\n```typescript\nlisten(callback: () => void) {\n  console.log(this.messageHandlers);\n  callback();\n}\n```\n\nAfter your application restarts, you'll see the following log in your terminal:\n\n```typescript\nMap { 'echo' => [AsyncFunction] { isEventHandler: false } }\n```\n\n> info **Hint** If we used the `@EventPattern` decorator, you would see the same output, but with the `isEventHandler` property set to `true`.\n\nAs you can see, the `messageHandlers` property is a `Map` collection of all message (and event) handlers, in which patterns are being used as keys.\nNow, you can use a key (for example, `\"echo\"`) to receive a reference to the message handler:\n\n```typescript\nasync listen(callback: () => void) {\n  const echoHandler = this.messageHandlers.get('echo');\n  console.log(await echoHandler('Hello world!'));\n  callback();\n}\n```\n\nOnce we execute the `echoHandler` passing an arbitrary string as an argument (`\"Hello world!\"` here), we should see it in the console:\n\n```json\nHello world!\n```\n\nWhich means that our method handler was properly executed.\n\n#### Client proxy\n\nAs we mentioned in the first section, you don't necessarily need to use the `@nestjs/microservices` package to create microservices, but if you decide to do so and you need to integrate a custom strategy, you will need to provide a \"client\" class too.\n\n> info **Hint** Again, implementing a fully-featured client class compatible with all `@nestjs/microservices` features (e.g., streaming) requires a good understading of communication techniques used by the framework. To learn more, check out this [article](https://dev.to/nestjs/part-4-basic-client-component-16f9).\n\nTo communicate with an external service/emit & publish messages (or events) you can either use a library-specific SDK package, or implement a custom client class that extends the `ClientProxy`, as follows:\n\n```typescript\nimport { ClientProxy, ReadPacket, WritePacket } from '@nestjs/microservices';\n\nclass GoogleCloudPubSubClient extends ClientProxy {\n  async connect(): Promise<any> {}\n  async close() {}\n  async dispatchEvent(packet: ReadPacket<any>): Promise<any> {}\n  publish(\n    packet: ReadPacket<any>,\n    callback: (packet: WritePacket<any>) => void,\n  ): Function {}\n}\n```\n\n> warning **Warning** Please, note we won't be implementing a fully-featured Google Cloud Pub/Sub client in this chapter as this would require diving into transporter specific technical details.\n\nAs you can see, `ClientProxy` class requires us to provide several methods for establishing & closing the connection and publishing messages (`publish`) and events (`dispatchEvent`).\nNote, if you don't need a request-response communication style support, you can leave the `publish()` method empty. Likewise, if you don't need to support event-based communication, skip the `dispatchEvent()` method.\n\nTo observe what and when those methods are executed, let's add multiple `console.log` calls, as follows:\n\n```typescript\nclass GoogleCloudPubSubClient extends ClientProxy {\n  async connect(): Promise<any> {\n    console.log('connect');\n  }\n\n  async close() {\n    console.log('close');\n  }\n\n  async dispatchEvent(packet: ReadPacket<any>): Promise<any> {\n    return console.log('event to dispatch: ', packet);\n  }\n\n  publish(\n    packet: ReadPacket<any>,\n    callback: (packet: WritePacket<any>) => void,\n  ): Function {\n    console.log('message:', packet);\n\n    // In a real-world application, the \"callback\" function should be executed\n    // with payload sent back from the responder. Here, we'll simply simulate (5 seconds delay)\n    // that response came through by passing the same \"data\" as we've originally passed in.\n    setTimeout(() => callback({ response: packet.data }), 5000);\n\n    return () => console.log('teardown');\n  }\n}\n```\n\nWith this in place, let's create an instance of `GoogleCloudPubSubClient` class and run the `send()` method (which you might have seen in earlier chapters), subscribing to the returned observable stream.\n\n```typescript\nconst googlePubSubClient = new GoogleCloudPubSubClient();\ngooglePubSubClient\n  .send('pattern', 'Hello world!')\n  .subscribe((response) => console.log(response));\n```\n\nNow, you should see the following output in your terminal:\n\n```typescript\nconnect\nmessage: { pattern: 'pattern', data: 'Hello world!' }\nHello world! // <-- after 5 seconds\n```\n\nTo test if our \"teardown\" method (which our `publish()` method returns) is properly executed, let's apply a timeout operator to our stream, setting it to 2 seconds to make sure it throws earlier then our `setTimeout` calls the `callback` function.\n\n```typescript\nconst googlePubSubClient = new GoogleCloudPubSubClient();\ngooglePubSubClient\n  .send('pattern', 'Hello world!')\n  .pipe(timeout(2000))\n  .subscribe(\n    (response) => console.log(response),\n    (error) => console.error(error.message),\n  );\n```\n\n> info **Hint** The `timeout` operator is imported from the `rxjs/operators` package.\n\nWith `timeout` operator applied, your terminal output should look as follows:\n\n```typescript\nconnect\nmessage: { pattern: 'pattern', data: 'Hello world!' }\nteardown // <-- teardown\nTimeout has occurred\n```\n\nTo dispatch an event (instead of sending a message), use the `emit()` method:\n\n```typescript\ngooglePubSubClient.emit('event', 'Hello world!');\n```\n\nAnd that's what you should see in the console:\n\n```typescript\nconnect\nevent to dispatch:  { pattern: 'event', data: 'Hello world!' }\n```\n\n#### Message serialization\n\nIf you need to add some custom logic around the serialization of responses on the client side, you can use a custom class that extends the `ClientProxy` class or one of its child classes. For modifying successful requests you can override the `serializeResponse` method, and for modifying any errors that go through this client you can override the `serializeError` method. To make use of this custom class, you can pass the class itself to the `ClientsModule.register()` method using the `customClass` property. Below is an example of a custom `ClientProxy` that serializes each error into an `RpcException`.\n\n```typescript\n@@filename(error-handling.proxy)\nimport { ClientTcp, RpcException } from '@nestjs/microservices';\n\nclass ErrorHandlingProxy extends ClientTCP {\n  serializeError(err: Error) {\n    return new RpcException(err);\n  }\n}\n```\n\nand then use it in the `ClientsModule` like so:\n\n```typescript\n@@filename(app.module)\n@Module({\n  imports: [\n    ClientsModule.register({\n      name: 'CustomProxy',\n      customClass: ErrorHandlingProxy,\n    }),\n  ]\n})\nexport class AppModule\n```\n\n> info **hint** This is the class itself being passed to `customClass`, not an instance of the class. Nest will create the instance under the hood for you, and will pass any options given to the `options` property to the new `ClientProxy`.\n> \n"
  },
  {
    "path": "content/microservices/exception-filters.md",
    "content": "### Exception filters\n\nThe only difference between the HTTP [exception filter](/exception-filters) layer and the corresponding microservices layer is that instead of throwing `HttpException`, you should use `RpcException`.\n\n```typescript\nthrow new RpcException('Invalid credentials.');\n```\n\n> info **Hint** The `RpcException` class is imported from the `@nestjs/microservices` package.\n\nWith the sample above, Nest will handle the thrown exception and return the `error` object with the following structure:\n\n```json\n{\n  \"status\": \"error\",\n  \"message\": \"Invalid credentials.\"\n}\n```\n\n#### Filters\n\nMicroservice exception filters behave similarly to HTTP exception filters, with one small difference. The `catch()` method must return an `Observable`.\n\n```typescript\n@@filename(rpc-exception.filter)\nimport { Catch, RpcExceptionFilter, ArgumentsHost } from '@nestjs/common';\nimport { Observable, throwError } from 'rxjs';\nimport { RpcException } from '@nestjs/microservices';\n\n@Catch(RpcException)\nexport class ExceptionFilter implements RpcExceptionFilter<RpcException> {\n  catch(exception: RpcException, host: ArgumentsHost): Observable<any> {\n    return throwError(exception.getError());\n  }\n}\n@@switch\nimport { Catch } from '@nestjs/common';\nimport { throwError } from 'rxjs';\n\n@Catch(RpcException)\nexport class ExceptionFilter {\n  catch(exception, host) {\n    return throwError(exception.getError());\n  }\n}\n```\n\n> warning **Warning** Global microservice exception filters aren't enabled by default when using a [hybrid application](/faq/hybrid-application).\n\nThe following example uses a manually instantiated method-scoped filter. Just as with HTTP based applications, you can also use controller-scoped filters (i.e., prefix the controller class with a `@UseFilters()` decorator).\n\n```typescript\n@@filename()\n@UseFilters(new ExceptionFilter())\n@MessagePattern({ cmd: 'sum' })\naccumulate(data: number[]): number {\n  return (data || []).reduce((a, b) => a + b);\n}\n@@switch\n@UseFilters(new ExceptionFilter())\n@MessagePattern({ cmd: 'sum' })\naccumulate(data) {\n  return (data || []).reduce((a, b) => a + b);\n}\n```\n\n#### Inheritance\n\nTypically, you'll create fully customized exception filters crafted to fulfill your application requirements. However, there might be use-cases when you would like to simply extend the **core exception filter**, and override the behavior based on certain factors.\n\nIn order to delegate exception processing to the base filter, you need to extend `BaseExceptionFilter` and call the inherited `catch()` method.\n\n```typescript\n@@filename()\nimport { Catch, ArgumentsHost } from '@nestjs/common';\nimport { BaseRpcExceptionFilter } from '@nestjs/microservices';\n\n@Catch()\nexport class AllExceptionsFilter extends BaseRpcExceptionFilter {\n  catch(exception: any, host: ArgumentsHost) {\n    return super.catch(exception, host);\n  }\n}\n@@switch\nimport { Catch } from '@nestjs/common';\nimport { BaseRpcExceptionFilter } from '@nestjs/microservices';\n\n@Catch()\nexport class AllExceptionsFilter extends BaseRpcExceptionFilter {\n  catch(exception, host) {\n    return super.catch(exception, host);\n  }\n}\n```\n\nThe above implementation is just a shell demonstrating the approach. Your implementation of the extended exception filter would include your tailored **business logic** (e.g., handling various conditions).\n"
  },
  {
    "path": "content/microservices/grpc.md",
    "content": "### gRPC\n\n[gRPC](https://github.com/grpc/grpc-node) is a modern, open source, high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication.\n\nLike many RPC systems, gRPC is based on the concept of defining a service in terms of functions (methods) that can be called remotely. For each method, you define the parameters and return types. Services, parameters, and return types are defined in `.proto` files using Google's open source language-neutral <a href=\"https://developers.google.com/protocol-buffers\">protocol buffers</a> mechanism.\n\nWith the gRPC transporter, Nest uses `.proto` files to dynamically bind clients and servers to make it easy to implement remote procedure calls, automatically serializing and deserializing structured data.\n\n#### Installation\n\nTo start building gRPC-based microservices, first install the required packages:\n\n```bash\n$ npm i --save @grpc/grpc-js @grpc/proto-loader\n```\n\n#### Overview\n\nLike other Nest microservices transport layer implementations, you select the gRPC transporter mechanism using the `transport` property of the options object passed to the `createMicroservice()` method. In the following example, we'll set up a hero service. The `options` property provides metadata about that service; its properties are described <a href=\"microservices/grpc#options\">below</a>.\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n  transport: Transport.GRPC,\n  options: {\n    package: 'hero',\n    protoPath: join(__dirname, 'hero/hero.proto'),\n  },\n});\n@@switch\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.GRPC,\n  options: {\n    package: 'hero',\n    protoPath: join(__dirname, 'hero/hero.proto'),\n  },\n});\n```\n\n> info **Hint** The `join()` function is imported from the `path` package; the `Transport` enum is imported from the `@nestjs/microservices` package.\n\nIn the `nest-cli.json` file, we add the `assets` property that allows us to distribute non-TypeScript files, and `watchAssets` - to turn on watching all non-TypeScript assets. In our case, we want `.proto` files to be automatically copied to the `dist` folder. \n\n```json\n{\n  \"compilerOptions\": {\n    \"assets\": [\"**/*.proto\"],\n    \"watchAssets\": true\n  }\n}\n```\n\n#### Options\n\nThe <strong>gRPC</strong> transporter options object exposes the properties described below.\n\n<table>\n  <tr>\n    <td><code>package</code></td>\n    <td>Protobuf package name (matches <code>package</code> setting from <code>.proto</code> file).  Required</td>\n  </tr>\n  <tr>\n    <td><code>protoPath</code></td>\n    <td>\n      Absolute (or relative to the root dir) path to the\n      <code>.proto</code> file. Required\n    </td>\n  </tr>\n  <tr>\n    <td><code>url</code></td>\n    <td>Connection url.  String in the format <code>ip address/dns name:port</code> (for example, <code>'localhost:50051'</code>) defining the address/port on which the transporter establishes a connection.  Optional.  Defaults to <code>'localhost:5000'</code></td>\n  </tr>\n  <tr>\n    <td><code>protoLoader</code></td>\n    <td>NPM package name for the utility to load <code>.proto</code> files.  Optional.  Defaults to <code>'@grpc/proto-loader'</code></td>\n  </tr>\n  <tr>\n    <td><code>loader</code></td>\n    <td>\n      <code>@grpc/proto-loader</code> options. These provide detailed control over the behavior of <code>.proto</code> files. Optional. See\n      <a\n        href=\"https://github.com/grpc/grpc-node/blob/master/packages/proto-loader/README.md\"\n        rel=\"nofollow\"\n        target=\"_blank\"\n        >here</a\n      > for more details\n    </td>\n  </tr>\n  <tr>\n    <td><code>credentials</code></td>\n    <td>\n      Server credentials.  Optional. <a\n        href=\"https://grpc.io/grpc/node/grpc.ServerCredentials.html\"\n        rel=\"nofollow\"\n        target=\"_blank\"\n        >Read more here</a\n      >\n    </td>\n  </tr>\n</table>\n\n#### Sample gRPC service\n\nLet's define our sample gRPC service called `HeroesService`. In the above `options` object, the`protoPath` property sets a path to the `.proto` definitions file `hero.proto`. The `hero.proto` file is structured using <a href=\"https://developers.google.com/protocol-buffers\">protocol buffers</a>. Here's what it looks like:\n\n```typescript\n// hero/hero.proto\nsyntax = \"proto3\";\n\npackage hero;\n\nservice HeroesService {\n  rpc FindOne (HeroById) returns (Hero) {}\n}\n\nmessage HeroById {\n  int32 id = 1;\n}\n\nmessage Hero {\n  int32 id = 1;\n  string name = 2;\n}\n```\n\nOur `HeroesService` exposes a `FindOne()` method. This method expects an input argument of type `HeroById` and returns a `Hero` message (protocol buffers use `message` elements to define both parameter types and return types).\n\nNext, we need to implement the service. To define a handler that fulfills this definition, we use the `@GrpcMethod()` decorator in a controller, as shown below. This decorator provides the metadata needed to declare a method as a gRPC service method.\n\n> info **Hint** The `@MessagePattern()` decorator (<a href=\"microservices/basics#request-response\">read more</a>) introduced in previous microservices chapters is not used with gRPC-based microservices. The `@GrpcMethod()` decorator effectively takes its place for gRPC-based microservices.\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesController {\n  @GrpcMethod('HeroesService', 'FindOne')\n  findOne(data: HeroById, metadata: Metadata, call: ServerUnaryCall<any>): Hero {\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n    return items.find(({ id }) => id === data.id);\n  }\n}\n@@switch\n@Controller()\nexport class HeroesController {\n  @GrpcMethod('HeroesService', 'FindOne')\n  findOne(data, metadata, call) {\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n    return items.find(({ id }) => id === data.id);\n  }\n}\n```\n\n> info **Hint** The `@GrpcMethod()` decorator is imported from the `@nestjs/microservices` package, while `Metadata` and `ServerUnaryCall` from the `grpc` package.\n\nThe decorator shown above takes two arguments. The first is the service name (e.g., `'HeroesService'`), corresponding to the `HeroesService` service definition in `hero.proto`. The second (the string `'FindOne'`) corresponds to the `FindOne()` rpc method defined within `HeroesService` in the `hero.proto` file.\n\nThe `findOne()` handler method takes three arguments, the `data` passed from the caller, `metadata` that stores gRPC\nrequest metadata and `call` to obtain the `GrpcCall` object properties such as `sendMetadata` for send metadata to client.\n\nBoth `@GrpcMethod()` decorator arguments are optional. If called without the second argument (e.g., `'FindOne'`), Nest will automatically associate the `.proto` file rpc method with the handler based on converting the handler name to upper camel case (e.g., the `findOne` handler is associated with the `FindOne` rpc call definition). This is shown below.\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesController {\n  @GrpcMethod('HeroesService')\n  findOne(data: HeroById, metadata: Metadata, call: ServerUnaryCall<any>): Hero {\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n    return items.find(({ id }) => id === data.id);\n  }\n}\n@@switch\n@Controller()\nexport class HeroesController {\n  @GrpcMethod('HeroesService')\n  findOne(data, metadata, call) {\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n    return items.find(({ id }) => id === data.id);\n  }\n}\n```\n\nYou can also omit the first `@GrpcMethod()` argument. In this case, Nest automatically associates the handler with the service definition from the proto definitions file based on the **class** name where the handler is defined. For example, in the following code, class `HeroesService` associates its handler methods with the `HeroesService` service definition in the `hero.proto` file based on the matching of the name `'HeroesService'`.\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesService {\n  @GrpcMethod()\n  findOne(data: HeroById, metadata: Metadata, call: ServerUnaryCall<any>): Hero {\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n    return items.find(({ id }) => id === data.id);\n  }\n}\n@@switch\n@Controller()\nexport class HeroesService {\n  @GrpcMethod()\n  findOne(data, metadata, call) {\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n    return items.find(({ id }) => id === data.id);\n  }\n}\n```\n\n#### Client\n\nNest applications can act as gRPC clients, consuming services defined in `.proto` files. You access remote services through a `ClientGrpc` object. You can obtain a `ClientGrpc` object in several ways.\n\nThe preferred technique is to import the `ClientsModule`. Use the `register()` method to bind a package of services defined in a `.proto` file to an injection token, and to configure the service. The `name` property is the injection token. For gRPC services, use `transport: Transport.GRPC`. The `options` property is an object with the same properties described <a href=\"microservices/grpc#options\">above</a>.\n\n```typescript\nimports: [\n  ClientsModule.register([\n    {\n      name: 'HERO_PACKAGE',\n      transport: Transport.GRPC,\n      options: {\n        package: 'hero',\n        protoPath: join(__dirname, 'hero/hero.proto'),\n      },\n    },\n  ]),\n];\n```\n\n> info **Hint** The `register()` method takes an array of objects. Register multiple packages by providing a comma separated list of registration objects.\n\nOnce registered, we can inject the configured `ClientGrpc` object with `@Inject()`. Then we use the `ClientGrpc` object's `getService()` method to retrieve the service instance, as shown below.\n\n```typescript\n@Injectable()\nexport class AppService implements OnModuleInit {\n  private heroesService: HeroesService;\n\n  constructor(@Inject('HERO_PACKAGE') private client: ClientGrpc) {}\n\n  onModuleInit() {\n    this.heroesService = this.client.getService<HeroesService>('HeroesService');\n  }\n\n  getHero(): Observable<string> {\n    return this.heroesService.findOne({ id: 1 });\n  }\n}\n```\n\n> error **Warning** gRPC Client will not send fields that contain underscore `_` in their names unless the `keepCase` options is set to `true` in the proto loader configuration (`options.loader.keepcase` in the microservice transporter configuration).\n\nNotice that there is a small difference compared to the technique used in other microservice transport methods. Instead of the `ClientProxy` class, we use the `ClientGrpc` class, which provides the `getService()` method. The `getService()` generic method takes a service name as an argument and returns its instance (if available).\n\nAlternatively, you can use the `@Client()` decorator to instantiate a `ClientGrpc` object, as follows:\n\n```typescript\n@Injectable()\nexport class AppService implements OnModuleInit {\n  @Client({\n    transport: Transport.GRPC,\n    options: {\n      package: 'hero',\n      protoPath: join(__dirname, 'hero/hero.proto'),\n    },\n  })\n  client: ClientGrpc;\n\n  private heroesService: HeroesService;\n\n  onModuleInit() {\n    this.heroesService = this.client.getService<HeroesService>('HeroesService');\n  }\n\n  getHero(): Observable<string> {\n    return this.heroesService.findOne({ id: 1 });\n  }\n}\n```\n\nFinally, for more complex scenarios, we can inject a dynamically configured client using the `ClientProxyFactory` class as described <a href=\"/microservices/basics#client\">here</a>.\n\nIn either case, we end up with a reference to our `HeroesService` proxy object, which exposes the same set of methods that are defined inside the `.proto` file. Now, when we access this proxy object (i.e., `heroesService`), the gRPC system automatically serializes requests, forwards them to the remote system, returns a response, and deserializes the response. Because gRPC shields us from these network communication details, `heroesService` looks and acts like a local provider.\n\nNote, all service methods are **lower camel cased** (in order to follow the natural convention of the language). So, for example, while our `.proto` file `HeroesService` definition contains the `FindOne()` function, the `heroesService` instance will provide the `findOne()` method.\n\n```typescript\ninterface HeroesService {\n  findOne(data: { id: number }): Observable<any>;\n}\n```\n\nA message handler is also able to return an `Observable`, in which case the result values will be emitted until the stream is completed.\n\n```typescript\n@@filename(heroes.controller)\n@Get()\ncall(): Observable<any> {\n  return this.heroesService.findOne({ id: 1 });\n}\n@@switch\n@Get()\ncall() {\n  return this.heroesService.findOne({ id: 1 });\n}\n```\n\nTo send gRPC metadata (along with the request), you can pass a second argument, as follows:\n\n```typescript\ncall(): Observable<any> {\n  const metadata = new Metadata();\n  metadata.add('Set-Cookie', 'yummy_cookie=choco');\n\n  return this.heroesService.findOne({ id: 1 }, metadata);\n}\n```\n\n> info **Hint** The `Metadata` class is imported from the `grpc` package.\n\nPlease note that this would require updating the `HeroesService` interface that we've defined a few steps earlier.\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/04-grpc).\n\n#### gRPC Streaming\n\ngRPC on its own supports long-term live connections, conventionally known as `streams`. Streams are useful for cases such as Chatting, Observations or Chunk-data transfers. Find more details in the official documentation [here](https://grpc.io/docs/guides/concepts/).\n\nNest supports GRPC stream handlers in two possible ways:\n\n- RxJS `Subject` + `Observable` handler: can be useful to write responses right inside of a Controller method or to be passed down to `Subject`/`Observable` consumer\n- Pure GRPC call stream handler: can be useful to be passed to some executor which will handle the rest of dispatch for the Node standard `Duplex` stream handler.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Streaming sample\n\nLet's define a new sample gRPC service called `HelloService`. The `hello.proto` file is structured using <a href=\"https://developers.google.com/protocol-buffers\">protocol buffers</a>. Here's what it looks like:\n\n```typescript\n// hello/hello.proto\nsyntax = \"proto3\";\n\npackage hello;\n\nservice HelloService {\n  rpc BidiHello(stream HelloRequest) returns (stream HelloResponse);\n  rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse);\n}\n\nmessage HelloRequest {\n  string greeting = 1;\n}\n\nmessage HelloResponse {\n  string reply = 1;\n}\n```\n\n> info **Hint** The `LotsOfGreetings` method can be simply implemented with the `@GrpcMethod` decorator (as in the examples above) since the returned stream can emit multiple values.\n\nBased on this `.proto` file, let's define the `HelloService` interface:\n\n```typescript\ninterface HelloService {\n  bidiHello(upstream: Observable<HelloRequest>): Observable<HelloResponse>;\n  lotsOfGreetings(\n    upstream: Observable<HelloRequest>,\n  ): Observable<HelloResponse>;\n}\n\ninterface HelloRequest {\n  greeting: string;\n}\n\ninterface HelloResponse {\n  reply: string;\n}\n```\n\n> info **Hint** The proto interface can be automatically generated by the [ts-proto](https://github.com/stephenh/ts-proto) package, learn more [here](https://github.com/stephenh/ts-proto/blob/main/NESTJS.markdown).\n\n#### Subject strategy\n\nThe `@GrpcStreamMethod()` decorator provides the function parameter as an RxJS `Observable`. Thus, we can receive and process multiple messages.\n\n```typescript\n@GrpcStreamMethod()\nbidiHello(messages: Observable<any>, metadata: Metadata, call: ServerDuplexStream<any, any>): Observable<any> {\n  const subject = new Subject();\n\n  const onNext = message => {\n    console.log(message);\n    subject.next({\n      reply: 'Hello, world!'\n    });\n  };\n  const onComplete = () => subject.complete();\n  messages.subscribe({\n    next: onNext,\n    complete: onComplete,\n  });\n\n\n  return subject.asObservable();\n}\n```\n\n> warning **Warning** For supporting full-duplex interaction with the `@GrpcStreamMethod()` decorator, the controller method must return an RxJS `Observable`.\n\n> info **Hint** The `Metadata` and `ServerUnaryCall` classes/interfaces are imported from the `grpc` package.\n\nAccording to the service definition (in the `.proto` file), the `BidiHello` method should stream requests to the service. To send multiple asynchronous messages to the stream from a client, we leverage an RxJS `ReplaySubject` class.\n\n```typescript\nconst helloService = this.client.getService<HelloService>('HelloService');\nconst helloRequest$ = new ReplaySubject<HelloRequest>();\n\nhelloRequest$.next({ greeting: 'Hello (1)!' });\nhelloRequest$.next({ greeting: 'Hello (2)!' });\nhelloRequest$.complete();\n\nreturn helloService.bidiHello(helloRequest$);\n```\n\nIn the example above, we wrote two messages to the stream (`next()` calls) and notified the service that we've completed sending the data (`complete()` call).\n\n#### Call stream handler\n\nWhen the method return value is defined as `stream`, the `@GrpcStreamCall()` decorator provides the function parameter as `grpc.ServerDuplexStream`, which supports standard methods like `.on('data', callback)`, `.write(message)` or `.cancel()`. Full documentation on available methods can be found [here](https://grpc.github.io/grpc/node/grpc-ClientDuplexStream.html).\n\nAlternatively, when the method return value is not a `stream`, the `@GrpcStreamCall()` decorator provides two function parameters, respectively `grpc.ServerReadableStream` (read more [here](https://grpc.github.io/grpc/node/grpc-ServerReadableStream.html)) and `callback`.\n\nLet's start with implementing the `BidiHello` which should support a full-duplex interaction.\n\n```typescript\n@GrpcStreamCall()\nbidiHello(requestStream: any) {\n  requestStream.on('data', message => {\n    console.log(message);\n    requestStream.write({\n      reply: 'Hello, world!'\n    });\n  });\n}\n```\n\n> info **Hint** This decorator does not require any specific return parameter to be provided. It is expected that the stream will be handled similar to any other standard stream type.\n\nIn the example above, we used the `write()` method to write objects to the response stream. The callback passed into the `.on()` method as a second parameter will be called every time our service receives a new chunk of data.\n\nLet's implement the `LotsOfGreetings` method.\n\n```typescript\n@GrpcStreamCall()\nlotsOfGreetings(requestStream: any, callback: (err: unknown, value: HelloResponse) => void) {\n  requestStream.on('data', message => {\n    console.log(message);\n  });\n  requestStream.on('end', () => callback(null, { reply: 'Hello, world!' }));\n}\n```\n\nHere we used the `callback` function to send the response once processing of the `requestStream` has been completed.\n\n#### gRPC Metadata\n\nMetadata is information about a particular RPC call in the form of a list of key-value pairs, where the keys are strings and the values are typically strings but can be binary data. Metadata is opaque to gRPC itself - it lets the client provide information associated with the call to the server and vice versa. Metadata may include authentication tokens, request identifiers and tags for monitoring purposes, and data information such as the number of records in a data set.\n\nTo read the metadata in `@GrpcMethod()` handler, use the second argument (metadata), which is of type `Metadata` (imported from the `grpc` package).\n\nTo send back metadata from the handler, use the `ServerUnaryCall#sendMetadata()` method (third handler argument).\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesService {\n  @GrpcMethod()\n  findOne(data: HeroById, metadata: Metadata, call: ServerUnaryCall<any>): Hero {\n    const serverMetadata = new Metadata();\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n\n    serverMetadata.add('Set-Cookie', 'yummy_cookie=choco');\n    call.sendMetadata(serverMetadata);\n\n    return items.find(({ id }) => id === data.id);\n  }\n}\n@@switch\n@Controller()\nexport class HeroesService {\n  @GrpcMethod()\n  findOne(data, metadata, call) {\n    const serverMetadata = new Metadata();\n    const items = [\n      { id: 1, name: 'John' },\n      { id: 2, name: 'Doe' },\n    ];\n\n    serverMetadata.add('Set-Cookie', 'yummy_cookie=choco');\n    call.sendMetadata(serverMetadata);\n\n    return items.find(({ id }) => id === data.id);\n  }\n}\n```\n\nLikewise, to read the metadata in handlers annotated with the `@GrpcStreamMethod()` handler ([subject strategy](microservices/grpc#subject-strategy)), use the second argument (metadata), which is of type `Metadata` (imported from the `grpc` package).\n\nTo send back metadata from the handler, use the `ServerDuplexStream#sendMetadata()` method (third handler argument).\n\nTo read metadata from within the [call stream handlers](microservices/grpc#call-stream-handler) (handlers annotated with `@GrpcStreamCall()` decorator), listen to the `metadata` event on the `requestStream` reference, as follows:\n\n```typescript\nrequestStream.on('metadata', (metadata: Metadata) => {\n  const meta = metadata.get('X-Meta');\n});\n```\n"
  },
  {
    "path": "content/microservices/guards.md",
    "content": "### Guards\n\nThere is no fundamental difference between microservices guards and [regular HTTP application guards](/guards).\nThe only difference is that instead of throwing `HttpException`, you should use `RpcException`.\n\n> info **Hint** The `RpcException` class is exposed from `@nestjs/microservices` package.\n\n#### Binding guards\n\nThe following example uses a method-scoped guard. Just as with HTTP based applications, you can also use controller-scoped guards (i.e., prefix the controller class with a `@UseGuards()` decorator).\n\n```typescript\n@@filename()\n@UseGuards(AuthGuard)\n@MessagePattern({ cmd: 'sum' })\naccumulate(data: number[]): number {\n  return (data || []).reduce((a, b) => a + b);\n}\n@@switch\n@UseGuards(AuthGuard)\n@MessagePattern({ cmd: 'sum' })\naccumulate(data) {\n  return (data || []).reduce((a, b) => a + b);\n}\n```\n"
  },
  {
    "path": "content/microservices/interceptors.md",
    "content": "### Interceptors\n\nThere is no difference between [regular interceptors](/interceptors) and microservices interceptors. The following example uses a manually instantiated method-scoped interceptor. Just as with HTTP based applications, you can also use controller-scoped interceptors (i.e., prefix the controller class with a `@UseInterceptors()` decorator).\n\n```typescript\n@@filename()\n@UseInterceptors(new TransformInterceptor())\n@MessagePattern({ cmd: 'sum' })\naccumulate(data: number[]): number {\n  return (data || []).reduce((a, b) => a + b);\n}\n@@switch\n@UseInterceptors(new TransformInterceptor())\n@MessagePattern({ cmd: 'sum' })\naccumulate(data) {\n  return (data || []).reduce((a, b) => a + b);\n}\n```\n"
  },
  {
    "path": "content/microservices/kafka.md",
    "content": "### Kafka\n\n[Kafka](https://kafka.apache.org/) is an open source, distributed streaming platform which has three key capabilities:\n\n- Publish and subscribe to streams of records, similar to a message queue or enterprise messaging system.\n- Store streams of records in a fault-tolerant durable way.\n- Process streams of records as they occur.\n\nThe Kafka project aims to provide a unified, high-throughput, low-latency platform for handling real-time data feeds. It integrates very well with Apache Storm and Spark for real-time streaming data analysis.\n\n#### Installation\n\nTo start building Kafka-based microservices, first install the required package:\n\n```bash\n$ npm i --save kafkajs\n```\n\n#### Overview\n\nLike other Nest microservice transport layer implementations, you select the Kafka transporter mechanism using the `transport` property of the options object passed to the `createMicroservice()` method, along with an optional `options` property, as shown below:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n  transport: Transport.KAFKA,\n  options: {\n    client: {\n      brokers: ['localhost:9092'],\n    }\n  }\n});\n@@switch\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.KAFKA,\n  options: {\n    client: {\n      brokers: ['localhost:9092'],\n    }\n  }\n});\n```\n\n> info **Hint** The `Transport` enum is imported from the `@nestjs/microservices` package.\n\n#### Options\n\nThe `options` property is specific to the chosen transporter. The <strong>Kafka</strong> transporter exposes the properties described below.\n\n<table>\n  <tr>\n    <td><code>client</code></td>\n    <td>Client configuration options (read more\n      <a\n        href=\"https://kafka.js.org/docs/configuration\"\n        rel=\"nofollow\"\n        target=\"blank\"\n        >here</a\n      >)</td>\n  </tr>\n  <tr>\n    <td><code>consumer</code></td>\n    <td>Consumer configuration options (read more\n      <a\n        href=\"https://kafka.js.org/docs/consuming#a-name-options-a-options\"\n        rel=\"nofollow\"\n        target=\"blank\"\n        >here</a\n      >)</td>\n  </tr>\n  <tr>\n    <td><code>run</code></td>\n    <td>Run configuration options (read more\n      <a\n        href=\"https://kafka.js.org/docs/consuming\"\n        rel=\"nofollow\"\n        target=\"blank\"\n        >here</a\n      >)</td>\n  </tr>\n  <tr>\n    <td><code>subscribe</code></td>\n    <td>Subscribe configuration options (read more\n      <a\n        href=\"https://kafka.js.org/docs/consuming#frombeginning\"\n        rel=\"nofollow\"\n        target=\"blank\"\n        >here</a\n      >)</td>\n  </tr>\n  <tr>\n    <td><code>producer</code></td>\n    <td>Producer configuration options (read more\n      <a\n        href=\"https://kafka.js.org/docs/producing#options\"\n        rel=\"nofollow\"\n        target=\"blank\"\n        >here</a\n      >)</td>\n  </tr>\n  <tr>\n    <td><code>send</code></td>\n    <td>Send configuration options (read more\n      <a\n        href=\"https://kafka.js.org/docs/producing#options\"\n        rel=\"nofollow\"\n        target=\"blank\"\n        >here</a\n      >)</td>\n  </tr>\n</table>\n\n#### Client\n\nThere is a small difference in Kafka compared to other microservice transporters. Instead of the `ClientProxy` class, we use the `ClientKafka` class.\n\nLike other microservice transporters, you have <a href=\"https://docs.nestjs.com/microservices/basics#client\">several options</a> for creating a `ClientKafka` instance.\n\nOne method for creating an instance is to use the `ClientsModule`. To create a client instance with the `ClientsModule`, import it and use the `register()` method to pass an options object with the same properties shown above in the `createMicroservice()` method, as well as a `name` property to be used as the injection token. Read more about `ClientsModule` <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n```typescript\n@Module({\n  imports: [\n    ClientsModule.register([\n      {\n        name: 'HERO_SERVICE',\n        transport: Transport.KAFKA,\n        options: {\n          client: {\n            clientId: 'hero',\n            brokers: ['localhost:9092'],\n          },\n          consumer: {\n            groupId: 'hero-consumer'\n          }\n        }\n      },\n    ]),\n  ]\n  ...\n})\n```\n\nOther options to create a client (either `ClientProxyFactory` or `@Client()`) can be used as well. You can read about them <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\nUse the `@Client()` decorator as follows:\n\n```typescript\n@Client({\n  transport: Transport.KAFKA,\n  options: {\n    client: {\n      clientId: 'hero',\n      brokers: ['localhost:9092'],\n    },\n    consumer: {\n      groupId: 'hero-consumer'\n    }\n  }\n})\nclient: ClientKafka;\n```\n\n#### Message pattern\n\nThe Kafka microservice message pattern utilizes two topics for the request and reply channels. The `ClientKafka#send()` method sends messages with a [return address](https://www.enterpriseintegrationpatterns.com/patterns/messaging/ReturnAddress.html) by associating a [correlation id](https://www.enterpriseintegrationpatterns.com/patterns/messaging/CorrelationIdentifier.html), reply topic, and reply partition with the request message. This requires the `ClientKafka` instance to be subscribed to the reply topic and assigned to at least one partition before sending a message.\n\nSubsequently, you need to have at least one reply topic partition for every Nest application running. For example, if you are running 4 Nest applications but the reply topic only has 3 partitions, then 1 of the Nest applications will error out when trying to send a message.\n\nWhen new `ClientKafka` instances are launched they join the consumer group and subscribe to their respective topics. This process triggers a rebalance of topic partitions assigned to consumers of the consumer group.\n\nNormally, topic partitions are assigned using the round robin partitioner, which assigns topic partitions to a collection of consumers sorted by consumer names which are randomly set on application launch. However, when a new consumer joins the consumer group, the new consumer can be positioned anywhere within the collection of consumers. This creates a condition where pre-existing consumers can be assigned different partitions when the pre-existing consumer is positioned after the new consumer. As a result, the consumers that are assigned different partitions will lose response messages of requests sent before the rebalance.\n\nTo prevent the `ClientKafka` consumers from losing response messages, a Nest-specific built-in custom partitioner is utilized. This custom partitioner assigns partitions to a collection of consumers sorted by high-resolution timestamps (`process.hrtime()`) that are set on application launch.\n\n#### Message response subscription\n\n> warning **Note** This section is only relevant if you use [request-response](/microservices/basics#request-response) message style (with the `@MessagePatern` decorator and the `ClientKafka#send` method). Subscribing to the response topic is not necessary for the [event-based](/microservices/basics#event-based) communication (`@EventPattern` decorator and `ClientKafka#emit` method).\n\nThe `ClientKafka` class provides the `subscribeToResponseOf()` method. The `subscribeToResponseOf()` method takes a request's topic name as an argument and adds the derived reply topic name to a collection of reply topics. This method is required when implementing the message pattern.\n\n```typescript\n@@filename(heroes.controller)\nonModuleInit() {\n  this.client.subscribeToResponseOf('hero.kill.dragon');\n}\n```\n\nIf the `ClientKafka` instance is created asynchronously, the `subscribeToResponseOf()` method must be called before calling the `connect()` method.\n\n```typescript\n@@filename(heroes.controller)\nasync onModuleInit() {\n  this.client.subscribeToResponseOf('hero.kill.dragon');\n  await this.client.connect();\n}\n```\n\n#### Incoming\n\nNest receives incoming Kafka messages as an object with `key`, `value`, and `headers` properties that have values of type `Buffer`. Nest then parses these values by transforming the buffers into strings. If the string is \"object like\", Nest attempts to parse the string as `JSON`. The `value` is then passed to its associated handler.\n\n#### Outgoing\n\nNest sends outgoing Kafka messages after a serialization process when publishing events or sending messages. This occurs on arguments passed to the `ClientKafka` `emit()` and `send()` methods or on values returned from a `@MessagePattern` method. This serialization \"stringifies\" objects that are not strings or buffers by using `JSON.stringify()` or the `toString()` prototype method.\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesController {\n  @MessagePattern('hero.kill.dragon')\n  killDragon(@Payload() message: KillDragonMessage): any {\n    const dragonId = message.dragonId;\n    const items = [\n      { id: 1, name: 'Mythical Sword' },\n      { id: 2, name: 'Key to Dungeon' },\n    ];\n    return items;\n  }\n}\n```\n\n> info **Hint** `@Payload()` is imported from the `@nestjs/microservices`.\n\nOutgoing messages can also be keyed by passing an object with the `key` and `value` properties. Keying messages is important for meeting the [co-partitioning requirement](https://docs.confluent.io/current/ksql/docs/developer-guide/partition-data.html#co-partitioning-requirements).\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesController {\n  @MessagePattern('hero.kill.dragon')\n  killDragon(@Payload() message: KillDragonMessage): any {\n    const realm = 'Nest';\n    const heroId = message.heroId;\n    const dragonId = message.dragonId;\n\n    const items = [\n      { id: 1, name: 'Mythical Sword' },\n      { id: 2, name: 'Key to Dungeon' },\n    ];\n\n    return {\n      headers: {\n        realm\n      },\n      key: heroId,\n      value: items\n    }\n  }\n}\n```\n\nAdditionally, messages passed in this format can also contain custom headers set in the `headers` hash property. Header hash property values must be either of type `string` or type `Buffer`.\n\n```typescript\n@@filename(heroes.controller)\n@Controller()\nexport class HeroesController {\n  @MessagePattern('hero.kill.dragon')\n  killDragon(@Payload() message: KillDragonMessage): any {\n    const realm = 'Nest';\n    const heroId = message.heroId;\n    const dragonId = message.dragonId;\n\n    const items = [\n      { id: 1, name: 'Mythical Sword' },\n      { id: 2, name: 'Key to Dungeon' },\n    ];\n\n    return {\n      headers: {\n        kafka_nestRealm: realm\n      },\n      key: heroId,\n      value: items\n    }\n  }\n}\n```\n\n#### Event-based\n\nWhile the request-response method is ideal for exchanging messages between services, it is less suitable when your message style is event-based (which in turn is ideal for Kafka) - when you just want to publish events **without waiting for a response**. In that case, you do not want the overhead required by request-response for maintaining two topics.\n\nCheck out these two sections to learn more about this: [Overview: Event-based](/microservices/basics#event-based) and [Overview: Publishing events](/microservices/basics#publishing-events).\n\n#### Context\n\nIn more sophisticated scenarios, you may want to access more information about the incoming request. When using the Kafka transporter, you can access the `KafkaContext` object.\n\n```typescript\n@@filename()\n@MessagePattern('hero.kill.dragon')\nkillDragon(@Payload() message: KillDragonMessage, @Ctx() context: KafkaContext) {\n  console.log(`Topic: ${context.getTopic()}`);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('hero.kill.dragon')\nkillDragon(message, context) {\n  console.log(`Topic: ${context.getTopic()}`);\n}\n```\n\n> info **Hint** `@Payload()`, `@Ctx()` and `KafkaContext` are imported from the `@nestjs/microservices` package.\n\nTo access the original Kafka `IncomingMessage` object, use the `getMessage()` method of the `KafkaContext` object, as follows:\n\n```typescript\n@@filename()\n@MessagePattern('hero.kill.dragon')\nkillDragon(@Payload() message: KillDragonMessage, @Ctx() context: KafkaContext) {\n  const originalMessage = context.getMessage();\n  const { headers, partition, timestamp } = originalMessage;\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('hero.kill.dragon')\nkillDragon(message, context) {\n  const originalMessage = context.getMessage();\n  const { headers, partition, timestamp } = originalMessage;\n}\n```\n\nWhere the `IncomingMessage` fulfills the following interface:\n\n```typescript\ninterface IncomingMessage {\n  topic: string;\n  partition: number;\n  timestamp: string;\n  size: number;\n  attributes: number;\n  offset: string;\n  key: any;\n  value: any;\n  headers: Record<string, any>;\n}\n```\n\n#### Naming conventions\n\nThe Kafka microservice components append a description of their respective role onto the `client.clientId` and `consumer.groupId` options to prevent collisions between Nest microservice client and server components. By default the `ClientKafka` components append `-client` and the `ServerKafka` components append `-server` to both of these options. Note how the provided values below are transformed in that way (as shown in the comments).\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.KAFKA,\n  options: {\n    client: {\n      clientId: 'hero', // hero-server\n      brokers: ['localhost:9092'],\n    },\n    consumer: {\n      groupId: 'hero-consumer' // hero-consumer-server\n    },\n  }\n});\n```\n\nAnd for the client:\n\n```typescript\n@@filename(heroes.controller)\n@Client({\n  transport: Transport.KAFKA,\n  options: {\n    client: {\n      clientId: 'hero', // hero-client\n      brokers: ['localhost:9092'],\n    },\n    consumer: {\n      groupId: 'hero-consumer' // hero-consumer-client\n    }\n  }\n})\nclient: ClientKafka;\n```\n\n> info **Hint** Kafka client and consumer naming conventions can be customized by extending `ClientKafka` and `KafkaServer` in your own custom provider and overriding the constructor.\n\nSince the Kafka microservice message pattern utilizes two topics for the request and reply channels, a reply pattern should be derived from the request topic. By default, the name of the reply topic is the composite of the request topic name with `.reply` appended.\n\n```typescript\n@@filename(heroes.controller)\nonModuleInit() {\n  this.client.subscribeToResponseOf('hero.get'); // hero.get.reply\n}\n```\n\n> info **Hint** Kafka reply topic naming conventions can be customized by extending `ClientKafka` in your own custom provider and overriding the `getResponsePatternName` method.\n"
  },
  {
    "path": "content/microservices/mqtt.md",
    "content": "### MQTT\n\n[MQTT](https://mqtt.org/) (Message Queuing Telemetry Transport) is an open source, lightweight messaging protocol, optimized for low latency. This protocol provides a scalable and cost-efficient way to connect devices using a **publish/subscribe** model. A communication system built on MQTT consists of the publishing server, a broker and one or more clients. It is designed for constrained devices and low-bandwidth, high-latency or unreliable networks.\n\n#### Installation\n\nTo start building MQTT-based microservices, first install the required package:\n\n```bash\n$ npm i --save mqtt\n```\n\n#### Overview\n\nTo use the MQTT transporter, pass the following options object to the `createMicroservice()` method:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n  transport: Transport.MQTT,\n  options: {\n    url: 'mqtt://localhost:1883',\n  },\n});\n@@switch\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.MQTT,\n  options: {\n    url: 'mqtt://localhost:1883',\n  },\n});\n```\n\n> info **Hint** The `Transport` enum is imported from the `@nestjs/microservices` package.\n\n#### Options\n\nThe `options` object is specific to the chosen transporter. The <strong>MQTT</strong> transporter exposes the properties described [here](https://github.com/mqttjs/MQTT.js/#mqttclientstreambuilder-options).\n\n#### Client\n\nLike other microservice transporters, you have <a href=\"https://docs.nestjs.com/microservices/basics#client\">several options</a> for creating a MQTT `ClientProxy` instance.\n\nOne method for creating an instance is to use use the `ClientsModule`. To create a client instance with the `ClientsModule`, import it and use the `register()` method to pass an options object with the same properties shown above in the `createMicroservice()` method, as well as a `name` property to be used as the injection token. Read more about `ClientsModule` <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n```typescript\n@Module({\n  imports: [\n    ClientsModule.register([\n      {\n        name: 'MATH_SERVICE',\n        transport: Transport.MQTT,\n        options: {\n          url: 'mqtt://localhost:1883',\n        }\n      },\n    ]),\n  ]\n  ...\n})\n```\n\nOther options to create a client (either `ClientProxyFactory` or `@Client()`) can be used as well. You can read about them <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n#### Context\n\nIn more sophisticated scenarios, you may want to access more information about the incoming request. When using the MQTT transporter, you can access the `MqttContext` object.\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: MqttContext) {\n  console.log(`Topic: ${context.getTopic()}`);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(`Topic: ${context.getTopic()}`);\n}\n```\n\n> info **Hint** `@Payload()`, `@Ctx()` and `MqttContext` are imported from the `@nestjs/microservices` package.\n\nTo access the original mqtt [packet](https://github.com/mqttjs/mqtt-packet), use the `getPacket()` method of the `MqttContext` object, as follows:\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: MqttContext) {\n  console.log(context.getPacket());\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(context.getPacket());\n}\n```\n\n#### Wildcards\n\nA subscription may be to an explicit topic, or it may include wildcards. Two wildcards are available, `+` and `#`. `+` is a single-level wildcard, while `#` is a multi-level wildcard which covers many topic levels.\n\n```typescript\n@@filename()\n@MessagePattern('sensors/+/temperature/+')\ngetTemperature(@Ctx() context: MqttContext) {\n  console.log(`Topic: ${context.getTopic()}`);\n}\n@@switch\n@Bind(Ctx())\n@MessagePattern('sensors/+/temperature/+')\ngetTemperature(context) {\n  console.log(`Topic: ${context.getTopic()}`);\n}\n```\n\n#### Record builders\n\nTo configure message options (adjust the QoS level, set the Retain or DUP flags, or add additional properties to the payload), you can use the `MqttRecordBuilder` class. For example, to set `QoS` to `2` use the `setQoS` method, as follows:\n\n```typescript\nconst userProperties = { 'x-version': '1.0.0' };\nconst record = new MqttRecordBuilder(':cat:')\n  .setProperties({ userProperties })\n  .setQoS(1)\n  .build();\nclient.send('replace-emoji', record).subscribe(...);\n```\n\n> info **Hint** `MqttRecordBuilder` class is exported from the `@nestjs/microservices` package.\n\nAnd you can read these options on the server-side as well, by accessing the `MqttContext`.\n\n```typescript\n@@filename()\n@MessagePattern('replace-emoji')\nreplaceEmoji(@Payload() data: string, @Ctx() context: MqttContext): string {\n  const { properties: { userProperties } } = context.getPacket();\n  return userProperties['x-version'] === '1.0.0' ? '🐱' : '🐈';\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('replace-emoji')\nreplaceEmoji(data, context) {\n  const { properties: { userProperties } } = context.getPacket();\n  return userProperties['x-version'] === '1.0.0' ? '🐱' : '🐈';\n}\n```\n\nIn some cases you might want to configure user properties for multiple requests, you can pass these options to the `ClientProxyFactory`.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { ClientProxyFactory, Transport } from '@nestjs/microservices';\n\n@Module({\n  providers: [\n    {\n      provide: 'API_v1',\n      useFactory: () =>\n        ClientProxyFactory.create({\n          transport: Transport.MQTT,\n          options: {\n            url: 'mqtt://localhost:1833',\n            userProperties: { 'x-version': '1.0.0' },\n          },\n        }),\n    },\n  ],\n})\nexport class ApiModule {}\n```\n"
  },
  {
    "path": "content/microservices/nats.md",
    "content": "### NATS\n\n[NATS](https://nats.io) is a simple, secure and high performance open source messaging system for cloud native applications, IoT messaging, and microservices architectures. The NATS server is written in the Go programming language, but client libraries to interact with the server are available for dozens of major programming languages. NATS supports both **At Most Once** and **At Least Once** delivery. It can run anywhere, from large servers and cloud instances, through edge gateways and even Internet of Things devices.\n\n#### Installation\n\nTo start building NATS-based microservices, first install the required package:\n\n```bash\n$ npm i --save nats\n```\n\n#### Overview\n\nTo use the NATS transporter, pass the following options object to the `createMicroservice()` method:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n  transport: Transport.NATS,\n  options: {\n    servers: ['nats://localhost:4222'],\n  },\n});\n@@switch\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.NATS,\n  options: {\n    servers: ['nats://localhost:4222'],\n  },\n});\n```\n\n> info **Hint** The `Transport` enum is imported from the `@nestjs/microservices` package.\n\n#### Options\n\nThe `options` object is specific to the chosen transporter. The <strong>NATS</strong> transporter exposes the properties described [here](https://github.com/nats-io/node-nats#connect-options).\nAdditionally, there is a `queue` property which allows you to specify the name of the queue that your server should subscribe to (leave `undefined` to ignore this setting). Read more about NATS queue groups <a href=\"https://docs.nestjs.com/microservices/nats#queue-groups\">below</a>.\n\n#### Client\n\nLike other microservice transporters, you have <a href=\"https://docs.nestjs.com/microservices/basics#client\">several options</a> for creating a NATS `ClientProxy` instance.\n\nOne method for creating an instance is to use the `ClientsModule`. To create a client instance with the `ClientsModule`, import it and use the `register()` method to pass an options object with the same properties shown above in the `createMicroservice()` method, as well as a `name` property to be used as the injection token. Read more about `ClientsModule` <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n```typescript\n@Module({\n  imports: [\n    ClientsModule.register([\n      {\n        name: 'MATH_SERVICE',\n        transport: Transport.NATS,\n        options: {\n          servers: ['nats://localhost:4222'],\n        }\n      },\n    ]),\n  ]\n  ...\n})\n```\n\nOther options to create a client (either `ClientProxyFactory` or `@Client()`) can be used as well. You can read about them <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n#### Request-response\n\nFor the **request-response** message style ([read more](https://docs.nestjs.com/microservices/basics#request-response)), the NATS transporter does not use the NATS built-in [Request-Reply](https://docs.nats.io/nats-concepts/reqreply) mechanism. Instead, a \"request\" is published on a given subject using the `publish()` method with a unique reply subject name, and responders listen on that subject and send responses to the reply subject. Reply subjects are directed back to the requestor dynamically, regardless of location of either party.\n\n#### Event-based\n\nFor the **event-based** message style ([read more](https://docs.nestjs.com/microservices/basics#event-based)), the NATS transporter uses NATS built-in [Publish-Subscribe](https://docs.nats.io/nats-concepts/pubsub) mechanism. A publisher sends a message on a subject and any active subscriber listening on that subject receives the message. Subscribers can also register interest in wildcard subjects that work a bit like a regular expression. This one-to-many pattern is sometimes called fan-out.\n\n#### Queue groups\n\nNATS provides a built-in load balancing feature called [distributed queues](https://docs.nats.io/nats-concepts/queue). To create a queue subscription, use the `queue` property as follows:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.NATS,\n  options: {\n    servers: ['nats://localhost:4222'],\n    queue: 'cats_queue',\n  },\n});\n```\n\n#### Context\n\nIn more sophisticated scenarios, you may want to access more information about the incoming request. When using the NATS transporter, you can access the `NatsContext` object.\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: NatsContext) {\n  console.log(`Subject: ${context.getSubject()}`);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(`Subject: ${context.getSubject()}`);\n}\n```\n\n> info **Hint** `@Payload()`, `@Ctx()` and `NatsContext` are imported from the `@nestjs/microservices` package.\n\n#### Wildcards\n\nA subscription may be to an explicit subject, or it may include wildcards.\n\n```typescript\n@@filename()\n@MessagePattern('time.us.*')\ngetDate(@Payload() data: number[], @Ctx() context: NatsContext) {\n  console.log(`Subject: ${context.getSubject()}`); // e.g. \"time.us.east\"\n  return new Date().toLocaleTimeString(...);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('time.us.*')\ngetDate(data, context) {\n  console.log(`Subject: ${context.getSubject()}`); // e.g. \"time.us.east\"\n  return new Date().toLocaleTimeString(...);\n}\n```\n\n#### Record builders\n\nTo configure message options, you can use the `NatsRecordBuilder` class (note: this is doable for event-based flows as well). For example, to add `x-version` header, use the `setHeaders` method, as follows:\n\n```typescript\nimport * as nats from 'nats';\n\n// somewhere in your code\nconst headers = nats.headers();\nheaders.set('x-version', '1.0.0');\n\nconst record = new NatsRecordBuilder(':cat:').setHeaders(headers).build();\nthis.client.send('replace-emoji', record).subscribe(...);\n```\n\n> info **Hint** `NatsRecordBuilder` class is exported from the `@nestjs/microservices` package.\n\nAnd you can read these headers on the server-side as well, by accessing the `NatsContext`, as follows:\n\n```typescript\n@@filename()\n@MessagePattern('replace-emoji')\nreplaceEmoji(@Payload() data: string, @Ctx() context: NatsContext): string {\n  const headers = context.getHeaders();\n  return headers['x-version'] === '1.0.0' ? '🐱' : '🐈';\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('replace-emoji')\nreplaceEmoji(data, context) {\n  const headers = context.getHeaders();\n  return headers['x-version'] === '1.0.0' ? '🐱' : '🐈';\n}\n```\n\nIn some cases you might want to configure headers for multiple requests, you can pass these as options to the `ClientProxyFactory`:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { ClientProxyFactory, Transport } from '@nestjs/microservices';\n\n@Module({\n  providers: [\n    {\n      provide: 'API_v1',\n      useFactory: () =>\n        ClientProxyFactory.create({\n          transport: Transport.NATS,\n          options: {\n            servers: ['nats://localhost:4222'],\n            headers: { 'x-version': '1.0.0' },\n          },\n        }),\n    },\n  ],\n})\nexport class ApiModule {}\n```\n"
  },
  {
    "path": "content/microservices/pipes.md",
    "content": "### Pipes\n\nThere is no fundamental difference between [regular pipes](/pipes) and microservices pipes. The only difference is that instead of throwing `HttpException`, you should use `RpcException`.\n\n> info **Hint** The `RpcException` class is exposed from `@nestjs/microservices` package.\n\n#### Binding pipes\n\nThe following example uses a manually instantiated method-scoped pipe. Just as with HTTP based applications, you can also use controller-scoped pipes (i.e., prefix the controller class with a `@UsePipes()` decorator).\n\n```typescript\n@@filename()\n@UsePipes(new ValidationPipe())\n@MessagePattern({ cmd: 'sum' })\naccumulate(data: number[]): number {\n  return (data || []).reduce((a, b) => a + b);\n}\n@@switch\n@UsePipes(new ValidationPipe())\n@MessagePattern({ cmd: 'sum' })\naccumulate(data) {\n  return (data || []).reduce((a, b) => a + b);\n}\n```\n"
  },
  {
    "path": "content/microservices/rabbitmq.md",
    "content": "### RabbitMQ\n\n[RabbitMQ](https://www.rabbitmq.com/)는 다양한 메시징 프로토콜을 지원하는 가벼운 오픈소스 메시지 브로커이며, 대규모 또는 고가용성에 대한 요구사항을 충족시키기 위해 분산 또는 연합 구성으로 배포할 수 있습니다. 추가로, 세계적으로 작은 스타트업이나 대기업 등 어느곳에서든 보편적으로 사용하는 메시지 브로커입니다.\n\n#### 설치\n\nRabbitMQ 기반의 마이크로서비스를 구축하기 위해서는 우선 필요한 패키지들을 설치해야 합니다:\n\n```bash\n$ npm i --save amqplib amqp-connection-manager\n```\n\n#### 개요\n\nRabbitMQ 전송매체를 사용하려면 `createMicroservice()` 메서드에 다음의 옵션 객체를 넘겨야 합니다:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n  transport: Transport.RMQ,\n  options: {\n    urls: ['amqp://localhost:5672'],\n    queue: 'cats_queue',\n    queueOptions: {\n      durable: false\n    },\n  },\n});\n@@switch\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.RMQ,\n  options: {\n    urls: ['amqp://localhost:5672'],\n    queue: 'cats_queue',\n    queueOptions: {\n      durable: false\n    },\n  },\n});\n```\n\n> info **힌트** `Transport` enum은 `@nestjs/microservices` 패키지에서 import합니다.\n\n#### 옵션\n\n`options`의 프로퍼티는 선택한 전송매체에 따라 다른 값을 가집니다. <strong>RabbitMQ</strong> 전송매체에 대한 프로퍼티들은 아래와 같습니다.\n\n<table>\n  <tr>\n    <td><code>urls</code></td>\n    <td>연결할 URL들</td>\n  </tr>\n  <tr>\n    <td><code>queue</code></td>\n    <td>현재 서버가 귀 기울이고 있을 큐 이름</td>\n  </tr>\n  <tr>\n    <td><code>prefetchCount</code></td>\n    <td>채널에서 미리 불러올 횟수</td>\n    <td></td>\n  </tr>\n  <tr>\n    <td><code>isGlobalPrefetchCount</code></td>\n    <td>prefetch를 채널별로 실행할지 여부</td>\n  </tr>\n  <tr>\n    <td><code>noAck</code></td>\n    <td><code>false</code>일 때, 승인을 수동으로 보내게 됩니다</td>\n  </tr>\n  <tr>\n    <td><code>queueOptions</code></td>\n    <td>큐에 대한 추가적인 옵션 (자세한 내용은 <a href=\"https://www.squaremobius.net/amqp.node/channel_api.html#channel_assertQueue\" rel=\"nofollow\" target=\"_blank\">여기</a>를 참조하세요)</td>\n  </tr>\n  <tr>\n    <td><code>socketOptions</code></td>\n    <td>소켓에 대한 추가적인 옵션 (자세한 내용은 <a href=\"https://www.squaremobius.net/amqp.node/channel_api.html#socket-options\" rel=\"nofollow\" target=\"_blank\">여기</a>를 참조하세요)</td>\n  </tr>\n  <tr>\n    <td><code>headers</code></td>\n    <td>모든 메시지에 붙일 헤더 정보</td>\n  </tr>\n</table>\n\n#### 클라이언트\n\n다른 마이크로서비스 전송매체를 다룰 때처럼, RabbitMQ `ClientProxy` 인스턴스를 만들기 위해 <a href=\"https://docs.nestjs.com/microservices/basics#client\">몇가지 옵션</a>이 필요합니다.\n\n인스턴스를 만드는 방법 중 하나는 `ClientsModule`을 사용하는 것입니다. `ClientsModule`로 클라이언트 인스턴스를 만들기 위해서는, import하고 위의 `createMicroservice()` 메서드에 넘겼던 내용 그대로 `register()` 메서드에 옵션 객체를 넘깁니다. 여기에 추가로 `name` 프로퍼티에 주입 토큰을 기입합니다. `ClientsModule`에 대한 자세한 내용은 <a href=\"https://docs.nestjs.com/microservices/basics#client\">여기</a>를 확인해 주세요.\n\n```typescript\n@Module({\n  imports: [\n    ClientsModule.register([\n      {\n        name: 'MATH_SERVICE',\n        transport: Transport.RMQ,\n        options: {\n          urls: ['amqp://localhost:5672'],\n          queue: 'cats_queue',\n          queueOptions: {\n            durable: false\n          },\n        },\n      },\n    ]),\n  ]\n  ...\n})\n```\n\n클라이언트를 생성하기 위한 다른 옵션들(`ClientProxyFactory`나 `@Client()`) 또한 사용해도 됩니다. 이에 대한 내용은 <a href=\"https://docs.nestjs.com/microservices/basics#client\">여기</a>에서 설명합니다.\n\n#### 컨텍스트\n\n더 복잡한 시나리오에서는 들어오는 요청에 대해 더 자세한 정보가 필요할 것입니다. RabbitMQ 전송매체를 사용하면 `RmqContext` 객체에 접근할 수 있습니다.\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {\n  console.log(`Pattern: ${context.getPattern()}`);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(`Pattern: ${context.getPattern()}`);\n}\n```\n\n> info **힌트** `@Payload()`와 `@Ctx()`, `RmqContext`는 `@nestjs/microservices` 패키지에서 import합니다.\n\n`properties`와 `fields`, `content`를 가지는 본래의 RabbitMQ 메시지에 접근하고 싶다면 아래와 같이 `RmqContext` 객체의 `getMessage()` 메서드를 사용하면 됩니다:\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {\n  console.log(context.getMessage());\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(context.getMessage());\n}\n```\n\nRabbitMQ [채널]을 참조하고 싶다면 아래와 같이 `RmqContext` 객체의 `getChannerlRef` 메서드를 사용하면 됩니다:\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {\n  console.log(context.getChannelRef());\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(context.getChannelRef());\n}\n```\n\n#### 메시지 승인\n\n메시지를 유실되는 일을 방지하기 위해 RabbitMQ에서는 [메시지 승인](https://www.rabbitmq.com/confirms.html)을 지원합니다. 승인이란 소비자가 RabbitMQ에게 특정 메시지를 정상적으로 수신하고 처리했으니 마음대로 지워도 된다고 알리는 것입니다. 소비자가 승인을 보내지 않고 없어지면(채널이 닫히거나, 연결이 끊기거나, TCP 연결이 사라지는 등), RabbitMQ는 메시지가 제대로 처리되지 않았다고 이해하여 해당 메시지를 다시 큐에 담습니다.\n\n수동 승인 모드를 활성화 하려면 `noAck` 프로퍼티를 `false`로 설정합니다:\n\n```typescript\noptions: {\n  urls: ['amqp://localhost:5672'],\n  queue: 'cats_queue',\n  noAck: false,\n  queueOptions: {\n    durable: false\n  },\n},\n```\n\n소비자가 승인을 수동으로 보내도록 전환 되었다면, 수신한 메시지를 처리하는 곳에서 적절한 승인을 보내어 작업이 완료되었음을 알립니다.\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {\n  const channel = context.getChannelRef();\n  const originalMsg = context.getMessage();\n\n  channel.ack(originalMsg);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  const channel = context.getChannelRef();\n  const originalMsg = context.getMessage();\n\n  channel.ack(originalMsg);\n}\n```\n\n#### 레코드 빌더\n\n메시지에 대한 옵션을 설정하려면 `RmqRecordBuilder` 클래스(참고: 이 클래스는 이벤트 기반 흐름에서도 사용할 수 있습니다)를 사용합니다. 예를 들어 `headers`와 `priority` 프로퍼티를 설정하려면, 다음과 같이 `setOptions` 메서드를 사용합니다.\n\n```typescript\nconst message = ':cat:';\nconst record = new RmqRecordBuilder(message)\n  .setOptions({\n    headers: {\n      ['x-version']: '1.0.0',\n    },\n    priority: 3,\n  })\n  .build();\n\nthis.client.send('replace-emoji', record).subscribe(...);\n```\n\n> info **힌트** `RmqRecordBuilder` 클래스는 `@nestjs/microservices` 패키지에서 import합니다.\n\n이제 다음과 같이 서버 사이드에서도 `RmqContext`를 통해 이 값들을 확인할 수 있습니다:\n\n```typescript\n@@filename()\n@MessagePattern('replace-emoji')\nreplaceEmoji(@Payload() data: string, @Ctx() context: RmqContext): string {\n  const { properties: { headers } } = context.getMessage();\n  return headers['x-version'] === '1.0.0' ? '🐱' : '🐈';\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('replace-emoji')\nreplaceEmoji(data, context) {\n  const { properties: { headers } } = context.getMessage();\n  return headers['x-version'] === '1.0.0' ? '🐱' : '🐈';\n}\n```\n"
  },
  {
    "path": "content/microservices/redis.md",
    "content": "### Redis\n\nThe [Redis](https://redis.io/) transporter implements the publish/subscribe messaging paradigm and leverages the [Pub/Sub](https://redis.io/topics/pubsub) feature of Redis. Published messages are categorized in channels, without knowing what subscribers (if any) will eventually receive the message. Each microservice can subscribe to any number of channels. In addition, more than one channel can be subscribed to at a time. Messages exchanged through channels are **fire-and-forget**, which means that if a message is published and there are no subscribers interested in it, the message is removed and cannot be recovered. Thus, you don't have a guarantee that either messages or events will be handled by at least one service. A single message can be subscribed to (and received) by multiple subscribers.\n\n<figure><img src=\"/assets/Redis_1.png\" /></figure>\n\n#### Installation\n\nTo start building Redis-based microservices, first install the required package (note as of now the supported Redis version is ^3, not the latest ^4):\n\n```bash\n$ npm i --save redis@^3\n```\n\n#### Overview\n\nTo use the Redis transporter, pass the following options object to the `createMicroservice()` method:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {\n  transport: Transport.REDIS,\n  options: {\n    url: 'redis://localhost:6379',\n  },\n});\n@@switch\nconst app = await NestFactory.createMicroservice(AppModule, {\n  transport: Transport.REDIS,\n  options: {\n    url: 'redis://localhost:6379',\n  },\n});\n```\n\n> info **Hint** The `Transport` enum is imported from the `@nestjs/microservices` package.\n\n#### Options\n\nThe `options` property is specific to the chosen transporter. The <strong>Redis</strong> transporter exposes the properties described below.\n\n<table>\n  <tr>\n    <td><code>url</code></td>\n    <td>Connection url</td>\n  </tr>\n  <tr>\n    <td><code>retryAttempts</code></td>\n    <td>Number of times to retry message (default: <code>0</code>)</td>\n  </tr>\n  <tr>\n    <td><code>retryDelay</code></td>\n    <td>Delay between message retry attempts (ms) (default: <code>0</code>)</td>\n  </tr>\n</table>\n\nAll the properties supported by the official [redis](https://www.npmjs.com/package/redis#options-object-properties) client are also supported by this transporter.\n\n#### Client\n\nLike other microservice transporters, you have <a href=\"https://docs.nestjs.com/microservices/basics#client\">several options</a> for creating a Redis `ClientProxy` instance.\n\nOne method for creating an instance is to use the `ClientsModule`. To create a client instance with the `ClientsModule`, import it and use the `register()` method to pass an options object with the same properties shown above in the `createMicroservice()` method, as well as a `name` property to be used as the injection token. Read more about `ClientsModule` <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n```typescript\n@Module({\n  imports: [\n    ClientsModule.register([\n      {\n        name: 'MATH_SERVICE',\n        transport: Transport.REDIS,\n        options: {\n          url: 'redis://localhost:6379',\n        }\n      },\n    ]),\n  ]\n  ...\n})\n```\n\nOther options to create a client (either `ClientProxyFactory` or `@Client()`) can be used as well. You can read about them <a href=\"https://docs.nestjs.com/microservices/basics#client\">here</a>.\n\n#### Context\n\nIn more sophisticated scenarios, you may want to access more information about the incoming request. When using the Redis transporter, you can access the `RedisContext` object.\n\n```typescript\n@@filename()\n@MessagePattern('notifications')\ngetNotifications(@Payload() data: number[], @Ctx() context: RedisContext) {\n  console.log(`Channel: ${context.getChannel()}`);\n}\n@@switch\n@Bind(Payload(), Ctx())\n@MessagePattern('notifications')\ngetNotifications(data, context) {\n  console.log(`Channel: ${context.getChannel()}`);\n}\n```\n\n> info **Hint** `@Payload()`, `@Ctx()` and `RedisContext` are imported from the `@nestjs/microservices` package.\n"
  },
  {
    "path": "content/middlewares.md",
    "content": "### Middleware\n\n미들웨어는 라우트 핸들러보다 **먼저** 호출되는 함수입니다. 미들웨어 함수는 [request](https://expressjs.com/en/4x/api.html#req) 및 [response](https://expressjs.com/en/4x/api.html#res) 객체와 애플리케이션의 요청-응답 사이클 안에 있는 `next()` 미들웨어 함수에 접근할 수 있습니다. **next** 미들웨어 함수는 일반적으로 `next` 라는 변수명으로 표시됩니다.\n\n<figure><img src=\"/assets/Middlewares_1.png\" /></figure>\n\nNest 미들웨어는 기본적으로 [express](https://expressjs.com/en/guide/using-middleware.html) 미들웨어와 동일합니다. 공식 Express 문서에서는 미들웨어의 기능을 다음와 같이 설명합니다:\n\n<blockquote class=\"external\">\n  미들웨어 함수는 다음 작업들을 수행할 수 있습니다:\n  <ul>\n    <li>모든 코드를 실행.</li>\n    <li>요청 및 응답 객체를 변경.</li>\n    <li>요청-응답 사이클을 종료.</li>\n    <li>스택 내 다음 미들웨어 함수를 호출합니다.</li>\n    <li>만약 현재 미들웨어 함수가 요청-응답 사이클을 종료하지 않는 경우, <code>next()</code>를 호출하여 다음 미들웨어 함수에 제어 권한을 전달해야합니다. 그렇지 않으면 해당 요청은 정지된 채로 방치됩니다.</li>\n  </ul>\n</blockquote>\n\n함수 또는 `@Injectable()` 데코레이터가 있는 클래스에서 커스텀 Nest 미들웨어를 구현합니다. 클래스는 `NestMiddleware` 인터페이스를 구현해야 하며 함수는 특별한 요구 사항이 없습니다. 클래스 메소드를 이용한 간단한 미들웨어 기능 구현부터 시작하겠습니다.\n\n```typescript\n@@filename(logger.middleware)\nimport { Injectable, NestMiddleware } from '@nestjs/common';\nimport { Request, Response, NextFunction } from 'express';\n\n@Injectable()\nexport class LoggerMiddleware implements NestMiddleware {\n  use(req: Request, res: Response, next: NextFunction) {\n    console.log('Request...');\n    next();\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class LoggerMiddleware {\n  use(req, res, next) {\n    console.log('Request...');\n    next();\n  }\n}\n```\n\n#### Dependency injection\n\nNest middleware fully supports Dependency Injection. Just as with providers and controllers, they are able to **inject dependencies** that are available within the same module. As usual, this is done through the `constructor`.\n\n#### Applying middleware\n\nThere is no place for middleware in the `@Module()` decorator. Instead, we set them up using the `configure()` method of the module class. Modules that include middleware have to implement the `NestModule` interface. Let's set up the `LoggerMiddleware` at the `AppModule` level.\n\n```typescript\n@@filename(app.module)\nimport { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';\nimport { LoggerMiddleware } from './common/middleware/logger.middleware';\nimport { CatsModule } from './cats/cats.module';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes('cats');\n  }\n}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { LoggerMiddleware } from './common/middleware/logger.middleware';\nimport { CatsModule } from './cats/cats.module';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule {\n  configure(consumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes('cats');\n  }\n}\n```\n\nIn the above example we have set up the `LoggerMiddleware` for the `/cats` route handlers that were previously defined inside the `CatsController`. We may also further restrict a middleware to a particular request method by passing an object containing the route `path` and request `method` to the `forRoutes()` method when configuring the middleware. In the example below, notice that we import the `RequestMethod` enum to reference the desired request method type.\n\n```typescript\n@@filename(app.module)\nimport { Module, NestModule, RequestMethod, MiddlewareConsumer } from '@nestjs/common';\nimport { LoggerMiddleware } from './common/middleware/logger.middleware';\nimport { CatsModule } from './cats/cats.module';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes({ path: 'cats', method: RequestMethod.GET });\n  }\n}\n@@switch\nimport { Module, RequestMethod } from '@nestjs/common';\nimport { LoggerMiddleware } from './common/middleware/logger.middleware';\nimport { CatsModule } from './cats/cats.module';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule {\n  configure(consumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes({ path: 'cats', method: RequestMethod.GET });\n  }\n}\n```\n\n> info **Hint** The `configure()` method can be made asynchronous using `async/await` (e.g., you can `await` completion of an asynchronous operation inside the `configure()` method body).\n\n#### Route wildcards\n\nPattern based routes are supported as well. For instance, the asterisk is used as a **wildcard**, and will match any combination of characters:\n\n```typescript\nforRoutes({ path: 'ab*cd', method: RequestMethod.ALL });\n```\n\nThe `'ab*cd'` route path will match `abcd`, `ab_cd`, `abecd`, and so on. The characters `?`, `+`, `*`, and `()` may be used in a route path, and are subsets of their regular expression counterparts. The hyphen ( `-`) and the dot (`.`) are interpreted literally by string-based paths.\n\n> warning **Warning** The `fastify` package uses the latest version of the `path-to-regexp` package, which no longer supports wildcard asterisks `*`. Instead, you must use parameters (e.g., `(.*)`, `:splat*`).\n\n#### Middleware consumer\n\nThe `MiddlewareConsumer` is a helper class. It provides several built-in methods to manage middleware. All of them can be simply **chained** in the [fluent style](https://en.wikipedia.org/wiki/Fluent_interface). The `forRoutes()` method can take a single string, multiple strings, a `RouteInfo` object, a controller class and even multiple controller classes. In most cases you'll probably just pass a list of **controllers** separated by commas. Below is an example with a single controller:\n\n```typescript\n@@filename(app.module)\nimport { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';\nimport { LoggerMiddleware } from './common/middleware/logger.middleware';\nimport { CatsModule } from './cats/cats.module';\nimport { CatsController } from './cats/cats.controller';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule implements NestModule {\n  configure(consumer: MiddlewareConsumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes(CatsController);\n  }\n}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { LoggerMiddleware } from './common/middleware/logger.middleware';\nimport { CatsModule } from './cats/cats.module';\nimport { CatsController } from './cats/cats.controller';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule {\n  configure(consumer) {\n    consumer\n      .apply(LoggerMiddleware)\n      .forRoutes(CatsController);\n  }\n}\n```\n\n> info **Hint** The `apply()` method may either take a single middleware, or multiple arguments to specify <a href=\"/middleware#multiple-middleware\">multiple middlewares</a>.\n\n#### Excluding routes\n\nAt times we want to **exclude** certain routes from having the middleware applied. We can easily exclude certain routes with the `exclude()` method. This method can take a single string, multiple strings, or a `RouteInfo` object identifying routes to be excluded, as shown below:\n\n```typescript\nconsumer\n  .apply(LoggerMiddleware)\n  .exclude(\n    { path: 'cats', method: RequestMethod.GET },\n    { path: 'cats', method: RequestMethod.POST },\n    'cats/(.*)',\n  )\n  .forRoutes(CatsController);\n```\n\n> info **Hint** The `exclude()` method supports wildcard parameters using the [path-to-regexp](https://github.com/pillarjs/path-to-regexp#parameters) package.\n\nWith the example above, `LoggerMiddleware` will be bound to all routes defined inside `CatsController` **except** the three passed to the `exclude()` method.\n\n#### Functional middleware\n\nThe `LoggerMiddleware` class we've been using is quite simple. It has no members, no additional methods, and no dependencies. Why can't we just define it in a simple function instead of a class? In fact, we can. This type of middleware is called **functional middleware**. Let's transform the logger middleware from class-based into functional middleware to illustrate the difference:\n\n```typescript\n@@filename(logger.middleware)\nimport { Request, Response, NextFunction } from 'express';\n\nexport function logger(req: Request, res: Response, next: NextFunction) {\n  console.log(`Request...`);\n  next();\n};\n@@switch\nexport function logger(req, res, next) {\n  console.log(`Request...`);\n  next();\n};\n```\n\nAnd use it within the `AppModule`:\n\n```typescript\n@@filename(app.module)\nconsumer\n  .apply(logger)\n  .forRoutes(CatsController);\n```\n\n> info **Hint** Consider using the simpler **functional middleware** alternative any time your middleware doesn't need any dependencies.\n\n#### Multiple middleware\n\nAs mentioned above, in order to bind multiple middleware that are executed sequentially, simply provide a comma separated list inside the `apply()` method:\n\n```typescript\nconsumer.apply(cors(), helmet(), logger).forRoutes(CatsController);\n```\n\n#### Global middleware\n\nIf we want to bind middleware to every registered route at once, we can use the `use()` method that is supplied by the `INestApplication` instance:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.create(AppModule);\napp.use(logger);\nawait app.listen(3000);\n```\n\n> info **Hint** Accessing the DI container in a global middleware is not possible. You can use a [functional middleware](middleware#functional-middleware) instead when using `app.use()`. Alternatively, you can use a class middleware and consume it with `.forRoutes('*')` within the `AppModule` (or any other module).\n"
  },
  {
    "path": "content/migration.md",
    "content": "### Migration guide\n\nThis article provides a set of guidelines for migrating from Nest version 7 to version 8.\nTo learn more about the new features we've added in the v8, check out this [link](https://github.com/nestjs/nest/pull/6349).\n\n#### HTTP module\n\nThe `HttpModule` exported from the `@nestjs/common` package has been deprecated and will be removed in the next major release.\nInstead, please use the `@nestjs/axios` package (otherwise, there are no API differences).\n\n#### gRPC strategy\n\nThe original Node gRPC library (`grpc`) has been deprecated and will no longer receive feature updates.\nWith Nest v8, you should use the `@grpc/grpc-js` library instead.\n\n#### NATS strategy\n\nNATS has released a new major version (2.0) which has many changes and it is not API compatible with `nats@1.x.x`.\nIf you interact with a Nest microservice (that uses NATS as a transfer layer), from a service written in a different framework, please, see their [migration document](https://github.com/nats-io/nats.js/blob/master/migration.md) to learn what's changed in v2. Otherwise, you should not see any major differences when communicating between Nest microservices.\n\nTo upgrade, make sure to install the latest version of the `nats` package (`npm i nats@latest`). Also, update your [NATS configuration](https://github.com/nats-io/nats.js/blob/master/migration.md#changed-configuration-properties). Example:\n\n```typescript\n// Before\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(\n  AppModule,\n  {\n    transport: Transport.NATS,\n    options: {\n      url: 'nats://localhost:4222',\n    },\n  },\n);\n\n// Now\nconst app = await NestFactory.createMicroservice<MicroserviceOptions>(\n  AppModule,\n  {\n    transport: Transport.NATS,\n    options: {\n      servers: ['nats://localhost:4222'],\n    },\n  },\n);\n```\n\n#### `@All()` decorator\n\nRoutes annotated with the `@All()` decorator will now map to the `router.all()` method instead of the `router.use()`.\n\n#### Async listen/start methods\n\n`listenAsync()` and `startAllMicroservicesAsync()` methods have been deprecated.\nInstead, simply use the `listen()` and `startAllMicroservices()` methods (they are `async` either way).\n\n#### Socket.io\n\nThe `@nestjs/platform-socket.io` package was upgraded to use the `socket.io@4.x.x` version (Nest v7 was based on the `socket.io` v2).\nTo learn more, check out these articles: [Socket.io 3 Release](https://socket.io/blog/socket-io-3-release/) and [Socket.io 4 Release](https://socket.io/blog/socket-io-4-release/).\n\n#### Logger breaking changes\n\nFor better extensibility, we separated out the `Logger` and `ConsoleLogger` classes ([PR](https://github.com/nestjs/nest/pull/6221), learn more in the [Logging](/techniques/logger) chapter). If your application uses a custom logger class that extends the built-in `Logger`, you should update it to extend the `ConsoleLogger` now.\n\nBefore:\n\n```typescript\nexport class MyLogger extends Logger {}\n```\n\nNow:\n\n```typescript\nexport class MyLogger extends ConsoleLogger {}\n```\n\n#### `@nestjs/config` package\n\nThere was a minor breaking change in the `registerAs` function (typings), you can see what has changed in [this PR](https://github.com/nestjs/config/pull/173).\n\n#### `@nestjs/graphql` package\n\nThere might be some small differences in how your auto-generated schema file looks like (changed types order). Also, if you use the schema-first approach, the automatically generated type definitions will change as there was a new `Nullable<T>` type introduced in the latest release.\n\nAlso, all `HttpException` errors thrown from your resolvers will be now automatically mapped to the corresponding `ApolloError` instances, unless you set the `autoTransformHttpErrors` configuration property (in the options object you pass into the `GraphQLModule#forRoot()` method) to `false`.\n\n#### `@nestjs/terminus` package\n\n`HttpHealthIndicator` requires `@nestjs/axios` to be installed as well as `HttpModule` to be imported. Also, the deprecated `TerminusModule.forRootAsync` has been removed. To migrate, check out the `@nestjs/terminus` v7.x.x [upgrade guide](https://docs.nestjs.com/v7/migration-guide#terminus).\n\n#### RxJS\n\nMake sure to upgrade to the latest version of the `rxjs` package (v7).\n"
  },
  {
    "path": "content/modules.md",
    "content": "### Modules\n\nA module is a class annotated with a `@Module()` decorator. The `@Module()` decorator provides metadata that **Nest** makes use of to organize the application structure.\n\n<figure><img src=\"/assets/Modules_1.png\" /></figure>\n\nEach application has at least one module, a **root module**. The root module is the starting point Nest uses to build the **application graph** - the internal data structure Nest uses to resolve module and provider relationships and dependencies. While very small applications may theoretically have just the root module, this is not the typical case. We want to emphasize that modules are **strongly** recommended as an effective way to organize your components. Thus, for most applications, the resulting architecture will employ multiple modules, each encapsulating a closely related set of **capabilities**.\n\nThe `@Module()` decorator takes a single object whose properties describe the module:\n\n| | |\n|-|-|\n| `providers`   | the providers that will be instantiated by the Nest injector and that may be shared at least across this module |\n| `controllers` | the set of controllers defined in this module which have to be instantiated  |\n| `imports`     | the list of imported modules that export the providers which are required in this module |\n| `exports`     | the subset of `providers` that are provided by this module and should be available in other modules which import this module. You can use either the provider itself or just its token (`provide` value) |\n\nThe module **encapsulates** providers by default. This means that it's impossible to inject providers that are neither directly part of the current module nor exported from the imported modules. Thus, you may consider the exported providers from a module as the module's public interface, or API.\n\n#### Feature modules\n\nThe `CatsController` and `CatsService` belong to the same application domain. As they are closely related, it makes sense to move them into a feature module. A feature module simply organizes code relevant for a specific feature, keeping code organized and establishing clear boundaries. This helps us manage complexity and develop with [SOLID](https://en.wikipedia.org/wiki/SOLID) principles, especially as the size of the application and/or team grow.\n\nTo demonstrate this, we'll create the `CatsModule`.\n\n```typescript\n@@filename(cats/cats.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n})\nexport class CatsModule {}\n```\n\n> info **Hint** To create a module using the CLI, simply execute the `$ nest g module cats` command.\n\nAbove, we defined the `CatsModule` in the `cats.module.ts` file, and moved everything related to this module into the `cats` directory. The last thing we need to do is import this module into the root module (the `AppModule`, defined in the `app.module.ts` file).\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { CatsModule } from './cats/cats.module';\n\n@Module({\n  imports: [CatsModule],\n})\nexport class AppModule {}\n```\n\nHere is how our directory structure looks now:\n\n<div class=\"file-tree\">\n  <div class=\"item\">src</div>\n  <div class=\"children\">\n    <div class=\"item\">cats</div>\n    <div class=\"children\">\n      <div class=\"item\">dto</div>\n      <div class=\"children\">\n        <div class=\"item\">create-cat.dto.ts</div>\n      </div>\n      <div class=\"item\">interfaces</div>\n      <div class=\"children\">\n        <div class=\"item\">cat.interface.ts</div>\n      </div>\n      <div class=\"item\">cats.controller.ts</div>\n      <div class=\"item\">cats.module.ts</div>\n      <div class=\"item\">cats.service.ts</div>\n    </div>\n    <div class=\"item\">app.module.ts</div>\n    <div class=\"item\">main.ts</div>\n  </div>\n</div>\n\n#### Shared modules\n\nIn Nest, modules are **singletons** by default, and thus you can share the same instance of any provider between multiple modules effortlessly.\n\n<figure><img src=\"/assets/Shared_Module_1.png\" /></figure>\n\nEvery module is automatically a **shared module**. Once created it can be reused by any module. Let's imagine that we want to share an instance of the `CatsService` between several other modules. In order to do that, we first need to **export** the `CatsService` provider by adding it to the module's `exports` array, as shown below:\n\n```typescript\n@@filename(cats.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n  exports: [CatsService]\n})\nexport class CatsModule {}\n```\n\nNow any module that imports the `CatsModule` has access to the `CatsService` and will share the same instance with all other modules that import it as well.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Module re-exporting\n\nAs seen above, Modules can export their internal providers. In addition, they can re-export modules that they import. In the example below, the `CommonModule` is both imported into **and** exported from the `CoreModule`, making it available for other modules which import this one.\n\n```typescript\n@Module({\n  imports: [CommonModule],\n  exports: [CommonModule],\n})\nexport class CoreModule {}\n```\n\n#### Dependency injection\n\nA module class can **inject** providers as well (e.g., for configuration purposes):\n\n```typescript\n@@filename(cats.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n})\nexport class CatsModule {\n  constructor(private catsService: CatsService) {}\n}\n@@switch\nimport { Module, Dependencies } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n})\n@Dependencies(CatsService)\nexport class CatsModule {\n  constructor(catsService) {\n    this.catsService = catsService;\n  }\n}\n```\n\nHowever, module classes themselves cannot be injected as providers due to [circular dependency](/fundamentals/circular-dependency) .\n\n#### Global modules\n\nIf you have to import the same set of modules everywhere, it can get tedious. Unlike in Nest, [Angular](https://angular.io) `providers` are registered in the global scope. Once defined, they're available everywhere. Nest, however, encapsulates providers inside the module scope. You aren't able to use a module's providers elsewhere without first importing the encapsulating module.\n\nWhen you want to provide a set of providers which should be available everywhere out-of-the-box (e.g., helpers, database connections, etc.), make the module **global** with the `@Global()` decorator.\n\n```typescript\nimport { Module, Global } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\n\n@Global()\n@Module({\n  controllers: [CatsController],\n  providers: [CatsService],\n  exports: [CatsService],\n})\nexport class CatsModule {}\n```\n\nThe `@Global()` decorator makes the module global-scoped. Global modules should be registered **only once**, generally by the root or core module. In the above example, the `CatsService` provider will be ubiquitous, and modules that wish to inject the service will not need to import the `CatsModule` in their imports array.\n\n> info **Hint** Making everything global is not a good design decision. Global modules are available to reduce the amount of necessary boilerplate. The `imports` array is generally the preferred way to make the module's API available to consumers.\n\n#### Dynamic modules\n\nThe Nest module system includes a powerful feature called **dynamic modules**. This feature enables you to easily create customizable modules that can register and configure providers dynamically. Dynamic modules are covered extensively [here](/fundamentals/dynamic-modules). In this chapter, we'll give a brief overview to complete the introduction to modules.\n\nFollowing is an example of a dynamic module definition for a `DatabaseModule`:\n\n```typescript\n@@filename()\nimport { Module, DynamicModule } from '@nestjs/common';\nimport { createDatabaseProviders } from './database.providers';\nimport { Connection } from './connection.provider';\n\n@Module({\n  providers: [Connection],\n})\nexport class DatabaseModule {\n  static forRoot(entities = [], options?): DynamicModule {\n    const providers = createDatabaseProviders(options, entities);\n    return {\n      module: DatabaseModule,\n      providers: providers,\n      exports: providers,\n    };\n  }\n}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { createDatabaseProviders } from './database.providers';\nimport { Connection } from './connection.provider';\n\n@Module({\n  providers: [Connection],\n})\nexport class DatabaseModule {\n  static forRoot(entities = [], options?) {\n    const providers = createDatabaseProviders(options, entities);\n    return {\n      module: DatabaseModule,\n      providers: providers,\n      exports: providers,\n    };\n  }\n}\n```\n\n> info **Hint** The `forRoot()` method may return a dynamic module either synchronously or asynchronously (i.e., via a `Promise`).\n\nThis module defines the `Connection` provider by default (in the `@Module()` decorator metadata), but additionally - depending on the `entities` and `options` objects passed into the `forRoot()` method - exposes a collection of providers, for example, repositories. Note that the properties returned by the dynamic module **extend** (rather than override) the base module metadata defined in the `@Module()` decorator. That's how both the statically declared `Connection` provider **and** the dynamically generated repository providers are exported from the module.\n\nIf you want to register a dynamic module in the global scope, set the `global` property to `true`.\n\n```typescript\n{\n  global: true,\n  module: DatabaseModule,\n  providers: providers,\n  exports: providers,\n}\n```\n\n> warning **Warning** As mentioned above, making everything global **is not a good design decision**.\n\nThe `DatabaseModule` can be imported and configured in the following manner:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { DatabaseModule } from './database/database.module';\nimport { User } from './users/entities/user.entity';\n\n@Module({\n  imports: [DatabaseModule.forRoot([User])],\n})\nexport class AppModule {}\n```\n\nIf you want to in turn re-export a dynamic module, you can omit the `forRoot()` method call in the exports array:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { DatabaseModule } from './database/database.module';\nimport { User } from './users/entities/user.entity';\n\n@Module({\n  imports: [DatabaseModule.forRoot([User])],\n  exports: [DatabaseModule],\n})\nexport class AppModule {}\n```\n\nThe [Dynamic modules](/fundamentals/dynamic-modules) chapter covers this topic in greater detail, and includes a [working example](https://github.com/nestjs/nest/tree/master/sample/25-dynamic-modules).\n"
  },
  {
    "path": "content/openapi/cli-plugin.md",
    "content": "### CLI Plugin\n\nTypeScript's metadata reflection system has several limitations which make it impossible to, for instance, determine what properties a class consists of or recognize whether a given property is optional or required. However, some of these constraints can be addressed at compilation time. Nest provides a plugin that enhances the TypeScript compilation process to reduce the amount of boilerplate code required.\n\n> info **Hint** This plugin is **opt-in**. If you prefer, you can declare all decorators manually, or only specific decorators where you need them.\n\n#### Overview\n\nThe Swagger plugin will automatically:\n\n- annotate all DTO properties with `@ApiProperty` unless `@ApiHideProperty` is used\n- set the `required` property depending on the question mark (e.g. `name?: string` will set `required: false`)\n- set the `type` or `enum` property depending on the type (supports arrays as well)\n- set the `default` property based on the assigned default value\n- set several validation rules based on `class-validator` decorators (if `classValidatorShim` set to `true`)\n- add a response decorator to every endpoint with a proper status and `type` (response model)\n- generate descriptions for properties and endpoints based on comments (if `introspectComments` set to `true`)\n- generate example values for properties based on comments (if `introspectComments` set to `true`)\n\nPlease, note that your filenames **must have** one of the following suffixes: `['.dto.ts', '.entity.ts']` (e.g., `create-user.dto.ts`) in order to be analysed by the plugin.\n\nIf you are using a different suffix, you can adjust the plugin's behavior by specifying the `dtoFileNameSuffix` option (see below).\n\nPreviously, if you wanted to provide an interactive experience with the Swagger UI,\nyou had to duplicate a lot of code to let the package know how your models/components should be declared in the specification. For example, you could define a simple `CreateUserDto` class as follows:\n\n```typescript\nexport class CreateUserDto {\n  @ApiProperty()\n  email: string;\n\n  @ApiProperty()\n  password: string;\n\n  @ApiProperty({ enum: RoleEnum, default: [], isArray: true })\n  roles: RoleEnum[] = [];\n\n  @ApiProperty({ required: false, default: true })\n  isEnabled?: boolean = true;\n}\n```\n\nWhile not a significant issue with medium-sized projects, it becomes verbose & hard to maintain once you have a large set of classes.\n\nBy enabling the Swagger plugin, the above class definition can be declared simply:\n\n```typescript\nexport class CreateUserDto {\n  email: string;\n  password: string;\n  roles: RoleEnum[] = [];\n  isEnabled?: boolean = true;\n}\n```\n\nThe plugin adds appropriate decorators on the fly based on the **Abstract Syntax Tree**. Thus you won't have to struggle with `@ApiProperty` decorators scattered throughout the code.\n\n> info **Hint** The plugin will automatically generate any missing swagger properties, but if you need to override them, you simply set them explicitly via `@ApiProperty()`.\n\n#### Comments introspection\n\nWith the comments introspection feature enabled, CLI plugin will generate descriptions and example values for properties based on comments.\n\nFor example, given an example `roles` property:\n\n```typescript\n/**\n * A list of user's roles\n * @example ['admin']\n */\n@ApiProperty({\n  description: `A list of user's roles`,\n  example: ['admin'],\n})\nroles: RoleEnum[] = [];\n```\n\nYou must duplicate both description and example values. With `introspectComments` enabled, the CLI plugin can extract these comments and automatically provide descriptions (and examples, if defined) for properties. Now, the above property can be declared simply as follows:\n\n```typescript\n/**\n * A list of user's roles\n * @example ['admin']\n */\nroles: RoleEnum[] = [];\n```\n\nThere are `dtoKeyOfComment` and `controllerKeyOfComment` plugin options that you can use to customize how the plugin will set the value for `ApiProperty` and `ApiOperation` decorators respectively. Take a look at the following example:\n\n```typescript\nexport class SomeController {\n  /**\n   * Create some resource\n   */\n  @Post()\n  create() {}\n}\n```\n\nBy default, these options are set to `\"description\"`. This means the plugin will assign `\"Create some resource\"` to `description` key on the `ApiOperation` operator. Like so:\n\n```ts\n@ApiOperation({ description: \"Create some resource\" })\n```\n\n> info **Hint** For models, the same logic applies but to `ApiProperty` decorator instead. \n\n#### Using the CLI plugin\n\nTo enable the plugin, open `nest-cli.json` (if you use [Nest CLI](/cli/overview)) and add the following `plugins` configuration:\n\n```javascript\n{\n  \"collection\": \"@nestjs/schematics\",\n  \"sourceRoot\": \"src\",\n  \"compilerOptions\": {\n    \"plugins\": [\"@nestjs/swagger\"]\n  }\n}\n```\n\nYou can use the `options` property to customize the behavior of the plugin.\n\n```javascript\n\"plugins\": [\n  {\n    \"name\": \"@nestjs/swagger\",\n    \"options\": {\n      \"classValidatorShim\": false,\n      \"introspectComments\": true\n    }\n  }\n]\n```\n\nThe `options` property has to fulfill the following interface:\n\n```typescript\nexport interface PluginOptions {\n  dtoFileNameSuffix?: string[];\n  controllerFileNameSuffix?: string[];\n  classValidatorShim?: boolean;\n  dtoKeyOfComment?: string;\n  controllerKeyOfComment?: string;\n  introspectComments?: boolean;\n}\n```\n\n<table>\n  <tr>\n    <th>Option</th>\n    <th>Default</th>\n    <th>Description</th>\n  </tr>\n  <tr>\n    <td><code>dtoFileNameSuffix</code></td>\n    <td><code>['.dto.ts', '.entity.ts']</code></td>\n    <td>DTO (Data Transfer Object) files suffix</td>\n  </tr>\n  <tr>\n    <td><code>controllerFileNameSuffix</code></td>\n    <td><code>.controller.ts</code></td>\n    <td>Controller files suffix</td>\n  </tr>\n  <tr>\n    <td><code>classValidatorShim</code></td>\n    <td><code>true</code></td>\n    <td>If set to true, the module will reuse <code>class-validator</code> validation decorators (e.g. <code>@Max(10)</code> will add <code>max: 10</code> to schema definition) </td>\n  </tr>\n  <tr>\n    <td><code>dtoKeyOfComment</code></td>\n    <td><code>'description'</code></td>\n    <td>The property key to set the comment text to on <code>ApiProperty</code>.</td>\n  </tr>\n  <tr>\n    <td><code>controllerKeyOfComment</code></td>\n    <td><code>'description'</code></td>\n    <td>The property key to set the comment text to on <code>ApiOperation</code>.</td>\n  </tr>\n  <tr>\n  <td><code>introspectComments</code></td>\n    <td><code>false</code></td>\n    <td>If set to true, plugin will generate descriptions and example values for properties based on comments</td>\n  </tr>\n</table>\n\nIf you don't use the CLI but instead have a custom `webpack` configuration, you can use this plugin in combination with `ts-loader`:\n\n```javascript\ngetCustomTransformers: (program: any) => ({\n  before: [require('@nestjs/swagger/plugin').before({}, program)]\n}),\n```\n\n#### Integration with `ts-jest` (e2e tests)\n\nTo run e2e tests, `ts-jest` compiles your source code files on the fly, in memory. This means, it doesn't use Nest CLI compiler and does not apply any plugins or perform AST transformations.\n\nTo enable the plugin, create the following file in your e2e tests directory:\n\n```javascript\nconst transformer = require('@nestjs/swagger/plugin');\n\nmodule.exports.name = 'nestjs-swagger-transformer';\n// you should change the version number anytime you change the configuration below - otherwise, jest will not detect changes\nmodule.exports.version = 1;\n\nmodule.exports.factory = (cs) => {\n  return transformer.before(\n    {\n      // @nestjs/swagger/plugin options (can be empty)\n    },\n    cs.program, // \"cs.tsCompiler.program\" for older versions of Jest (<= v27)\n  );\n};\n```\n\nWith this in place, import AST transformer within your `jest` configuration file. By default (in the starter application), e2e tests configuration file is located under the `test` folder and is named `jest-e2e.json`.\n\n```json\n{\n  ... // other configuration\n  \"globals\": {\n    \"ts-jest\": {\n      \"astTransformers\": {\n        \"before\": [\"<path to the file created above>\"],\n      }\n    }\n  }\n}\n```\n\n#### Troubleshooting `jest` (e2e tests)\n\nIn case `jest` does not seem to pick up your configuration changes, it's possible that Jest has already **cached** the build result. To apply the new configuration, you need to clear Jest's cache directory.\n\nTo clear the cache directory, run the following command in your NestJS project folder:\n\n```bash\n$ npx jest --clearCache\n```\n\nIn case the automatic cache clearance fails, you can still manually remove the cache folder with the following commands:\n\n```bash\n# Find jest cache directory (usually /tmp/jest_rs)\n# by running the following command in your NestJS project root\n$ npx jest --showConfig | grep cache\n# ex result:\n#   \"cache\": true,\n#   \"cacheDirectory\": \"/tmp/jest_rs\"\n\n# Remove or empty the Jest cache directory\n$ rm -rf  <cacheDirectory value>\n# ex:\n# rm -rf /tmp/jest_rs\n```\n"
  },
  {
    "path": "content/openapi/decorators.md",
    "content": "### Decorators\n\n모든 OpenAPI 의 decorator 들은 다른 주요 decorator 들과 구별하기 위해, `Api` 라는 접두어를 앞에 붙입니다. 하단의 항목은 사용할 수 있는 전체 decorator 들을 적용 가능한 위치에 따라 정리한 표입니다.\n\n|                          |                     |\n| ------------------------ | ------------------- |\n| `@ApiOperation()`        | Method              |\n| `@ApiResponse()`         | Method / Controller |\n| `@ApiProduces()`         | Method / Controller |\n| `@ApiConsumes()`         | Method / Controller |\n| `@ApiBearerAuth()`       | Method / Controller |\n| `@ApiOAuth2()`           | Method / Controller |\n| `@ApiBasicAuth()`        | Method / Controller |\n| `@ApiSecurity()`         | Method / Controller |\n| `@ApiExtraModels()`      | Method / Controller |\n| `@ApiBody()`             | Method              |\n| `@ApiParam()`            | Method              |\n| `@ApiQuery()`            | Method              |\n| `@ApiHeader()`           | Method / Controller |\n| `@ApiExcludeEndpoint()`  | Method              |\n| `@ApiTags()`             | Method / Controller |\n| `@ApiProperty()`         | Model               |\n| `@ApiPropertyOptional()` | Model               |\n| `@ApiHideProperty()`     | Model               |\n| `@ApiExtension()`        | Method              |\n"
  },
  {
    "path": "content/openapi/introduction.md",
    "content": "### Introduction\n\nThe [OpenAPI](https://swagger.io/specification/) specification is a language-agnostic definition format used to describe RESTful APIs. Nest provides a dedicated [module](https://github.com/nestjs/swagger) which allows generating such a specification by leveraging decorators.\n\n#### Installation\n\nTo begin using it, we first install the required dependencies.\n\n```bash\n$ npm install --save @nestjs/swagger swagger-ui-express\n```\n\nIf you use fastify, install `fastify-swagger` instead of `swagger-ui-express`:\n\n```bash\n$ npm install --save @nestjs/swagger fastify-swagger\n```\n\n#### Bootstrap\n\nOnce the installation process is complete, open the `main.ts` file and initialize Swagger using the `SwaggerModule` class:\n\n```typescript\n@@filename(main)\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  const config = new DocumentBuilder()\n    .setTitle('Cats example')\n    .setDescription('The cats API description')\n    .setVersion('1.0')\n    .addTag('cats')\n    .build();\n  const document = SwaggerModule.createDocument(app, config);\n  SwaggerModule.setup('api', app, document);\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\n> info **Hint** `document` (returned by the `SwaggerModule#createDocument()` method) is a serializable object conforming to [OpenAPI Document](https://swagger.io/specification/#openapi-document). Instead of hosting it via HTTP, you could also save it as a JSON/YAML file, and consume it in different ways.\n\nThe `DocumentBuilder` helps to structure a base document that conforms to the OpenAPI Specification. It provides several methods that allow setting such properties as title, description, version, etc. In order to create a full document (with all HTTP routes defined) we use the `createDocument()` method of the `SwaggerModule` class. This method takes two arguments, an application instance and a Swagger options object. Alternatively, we can provide a third argument, which should be of type `SwaggerDocumentOptions`. More on this in the [Document options section](/openapi/introduction#document-options).\n\nOnce we create a document, we can call the `setup()` method. It accepts:\n\n1. The path to mount the Swagger UI\n2. An application instance\n3. The document object instantiated above\n4. Optional configuration parameter (read more [here](/openapi/introduction#document-options))\n\nNow you can run the following command to start the HTTP server:\n\n```bash\n$ npm run start\n```\n\nWhile the application is running, open your browser and navigate to `http://localhost:3000/api`. You should see the Swagger UI.\n\n<figure><img src=\"/assets/swagger1.png\" /></figure>\n\nThe `SwaggerModule` automatically reflects all of your endpoints. Note that the Swagger UI is created using either `swagger-ui-express` or `fastify-swagger`, depending on the platform.\n\n> info **Hint** To generate and download a Swagger JSON file, navigate to `http://localhost:3000/api-json` (`swagger-ui-express`) or `http://localhost:3000/api/json` (`fastify-swagger`) in your browser (assuming that your Swagger documentation is available under `http://localhost:3000/api`).\n\n> warning **Warning** When using `fastify-swagger` and `helmet`, there may be a problem with [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP), to solve this collision, configure the CSP as shown below:\n>\n> ```typescript\n> app.register(helmet, {\n>   contentSecurityPolicy: {\n>     directives: {\n>       defaultSrc: [`'self'`],\n>       styleSrc: [`'self'`, `'unsafe-inline'`],\n>       imgSrc: [`'self'`, 'data:', 'validator.swagger.io'],\n>       scriptSrc: [`'self'`, `https: 'unsafe-inline'`],\n>     },\n>   },\n> });\n>\n> // If you are not going to use CSP at all, you can use this:\n> app.register(helmet, {\n>   contentSecurityPolicy: false,\n> });\n> ```\n\n#### Document options\n\nWhen creating a document, it is possible to provide some extra options to fine tune the library's behavior. These options should be of type `SwaggerDocumentOptions`, which can be the following:\n\n```TypeScript\nexport interface SwaggerDocumentOptions {\n  /**\n   * List of modules to include in the specification\n   */\n  include?: Function[];\n\n  /**\n   * Additional, extra models that should be inspected and included in the specification\n   */\n  extraModels?: Function[];\n\n  /**\n   * If `true`, swagger will ignore the global prefix set through `setGlobalPrefix()` method\n   */\n  ignoreGlobalPrefix?: boolean;\n\n  /**\n   * If `true`, swagger will also load routes from the modules imported by `include` modules\n   */\n  deepScanRoutes?: boolean;\n\n  /**\n   * Custom operationIdFactory that will be used to generate the `operationId`\n   * based on the `controllerKey` and `methodKey`\n   * @default () => controllerKey_methodKey\n   */\n  operationIdFactory?: (controllerKey: string, methodKey: string) => string;\n}\n```\n\nFor example, if you want to make sure that the library generates operation names like `createUser` instead of `UserController_createUser`, you can set the following:\n\n```TypeScript\nconst options: SwaggerDocumentOptions =  {\n  operationIdFactory: (\n    controllerKey: string,\n    methodKey: string\n  ) => methodKey\n};\nconst document = SwaggerModule.createDocument(app, config, options);\n```\n\n#### Setup options\n\nYou can configure Swagger UI by passing the options object which fulfills the `ExpressSwaggerCustomOptions` (if you use express) interface as a fourth argument of the `SwaggerModule#setup` method.\n\n```TypeScript\nexport interface ExpressSwaggerCustomOptions {\n  explorer?: boolean;\n  swaggerOptions?: Record<string, any>;\n  customCss?: string;\n  customCssUrl?: string;\n  customJs?: string;\n  customfavIcon?: string;\n  swaggerUrl?: string;\n  customSiteTitle?: string;\n  validatorUrl?: string;\n  url?: string;\n  urls?: Record<'url' | 'name', string>[];\n}\n```\n\nIf you use fastify, you can configure the user interface by passing the `FastifySwaggerCustomOptions` object.\n\n```Typescript\nexport interface FastifySwaggerCustomOptions {\n  uiConfig?: Record<string, any>;\n}\n```\n\nFor example, if you want to make sure that the authentication token persists after refreshing the page, or change the page title (that shows up in the browser), you can use the following settings:\n\n```TypeScript\nconst customOptions: SwaggerCustomOptions = {\n  swaggerOptions: {\n    persistAuthorization: true,\n  },\n  customSiteTitle: 'My API Docs',\n};\nSwaggerModule.setup('docs', app, document, customOptions);\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/11-swagger).\n"
  },
  {
    "path": "content/openapi/mapped-types.md",
    "content": "### Mapped types\n\nAs you build out features like **CRUD** (Create/Read/Update/Delete) it's often useful to construct variants on a base entity type. Nest provides several utility functions that perform type transformations to make this task more convenient.\n\n#### Partial\n\nWhen building input validation types (also called DTOs), it's often useful to build **create** and **update** variations on the same type. For example, the **create** variant may require all fields, while the **update** variant may make all fields optional.\n\nNest provides the `PartialType()` utility function to make this task easier and minimize boilerplate.\n\nThe `PartialType()` function returns a type (class) with all the properties of the input type set to optional. For example, suppose we have a **create** type as follows:\n\n```typescript\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class CreateCatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\nBy default, all of these fields are required. To create a type with the same fields, but with each one optional, use `PartialType()` passing the class reference (`CreateCatDto`) as an argument:\n\n```typescript\nexport class UpdateCatDto extends PartialType(CreateCatDto) {}\n```\n\n> info **Hint** The `PartialType()` function is imported from the `@nestjs/swagger` package.\n\n#### Pick\n\nThe `PickType()` function constructs a new type (class) by picking a set of properties from an input type. For example, suppose we start with a type like:\n\n```typescript\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class CreateCatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\nWe can pick a set of properties from this class using the `PickType()` utility function:\n\n```typescript\nexport class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}\n```\n\n> info **Hint** The `PickType()` function is imported from the `@nestjs/swagger` package.\n\n#### Omit\n\nThe `OmitType()` function constructs a type by picking all properties from an input type and then removing a particular set of keys. For example, suppose we start with a type like:\n\n```typescript\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class CreateCatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\nWe can generate a derived type that has every property **except** `name` as shown below. In this construct, the second argument to `OmitType` is an array of property names.\n\n```typescript\nexport class UpdateCatDto extends OmitType(CreateCatDto, ['name'] as const) {}\n```\n\n> info **Hint** The `OmitType()` function is imported from the `@nestjs/swagger` package.\n\n#### Intersection\n\nThe `IntersectionType()` function combines two types into one new type (class). For example, suppose we start with two types like:\n\n```typescript\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class CreateCatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  breed: string;\n}\n\nexport class AdditionalCatInfo {\n  @ApiProperty()\n  color: string;\n}\n```\n\nWe can generate a new type that combines all properties in both types.\n\n```typescript\nexport class UpdateCatDto extends IntersectionType(\n  CreateCatDto,\n  AdditionalCatInfo,\n) {}\n```\n\n> info **Hint** The `IntersectionType()` function is imported from the `@nestjs/swagger` package.\n\n#### Composition\n\nThe type mapping utility functions are composable. For example, the following will produce a type (class) that has all of the properties of the `CreateCatDto` type except for `name`, and those properties will be set to optional:\n\n```typescript\nexport class UpdateCatDto extends PartialType(\n  OmitType(CreateCatDto, ['name'] as const),\n) {}\n```\n"
  },
  {
    "path": "content/openapi/migration-guide.md",
    "content": "### 마이그레이션 가이드\n\n`@nestjs/swagger@3.*` 를 사용하고 있다면, 버전 4.0 에서는 하단의 중요한 변화들이 있다는 점을 유념해야 합니다.\n\n#### 중요한 변화들\n\n다음의 decorator 들은 기능 혹은 이름이 변경되었습니다.\n\n- `@ApiModelProperty` 는 `@ApiProperty` 로 이름이 변경되었습니다.\n- `@ApiModelPropertyOptional` 은 `@ApiPropertyOptional` 로 이름이 변경되었습니다.\n- `@ApiResponseModelProperty` 는 `@ApiResponseProperty` 로 이름이 변경되었습니다.\n- `@ApiImplicitQuery` 는 `@ApiQuery` 로 이름이 변경되었습니다.\n- `@ApiImplicitParam` 은 `@ApiParam` 로 이름이 변경되었습니다.\n- `@ApiImplicitBody` 는 `@ApiBody` 로 이름이 변경되었습니다.\n- `@ApiImplicitHeader` 는 `@ApiHeader` 로 이름이 변경되었습니다.\n- `@ApiOperation({{ '{' }} title: 'test' {{ '}' }})` 은 `@ApiOperation({{ '{' }} summary: 'test' {{ '}' }})` 로 이름이 변경되었습니다.\n- `@ApiUseTags` 는 `@ApiTags` 이름이 변경되었습니다.\n\n`DocumentBuilder` 의 중요한 변화들 (변경된 method signature들):\n\n- `addTag`\n- `addBearerAuth`\n- `addOAuth2`\n- `setContactEmail` 은 `setContact` 로 이름이 변경되었습니다.\n- `setHost` 는 삭제되었습니다.\n- `setSchemes` 는 삭제되었습니다. (`addServer` 를 사용하십시오. 예를 들어, `addServer('http://')`와 같이 사용할 수 있습니다.)\n\n#### 새로운 method들\n\n다음의 method 들은 추가되었습니다.\n\n- `addServer`\n- `addApiKey`\n- `addBasicAuth`\n- `addSecurity`\n- `addSecurityRequirements`\n\n<app-banner-shop></app-banner-shop>\n"
  },
  {
    "path": "content/openapi/operations.md",
    "content": "### Operations\n\nIn OpenAPI terms, paths are endpoints (resources), such as `/users` or `/reports/summary`, that your API exposes, and operations are the HTTP methods used to manipulate these paths, such as `GET`, `POST` or `DELETE`.\n\n#### Tags\n\nTo attach a controller to a specific tag, use the `@ApiTags(...tags)` decorator.\n\n```typescript\n@ApiTags('cats')\n@Controller('cats')\nexport class CatsController {}\n```\n\n#### Headers\n\nTo define custom headers that are expected as part of the request, use `@ApiHeader()`.\n\n```typescript\n@ApiHeader({\n  name: 'X-MyHeader',\n  description: 'Custom header',\n})\n@Controller('cats')\nexport class CatsController {}\n```\n\n#### Responses\n\nTo define a custom HTTP response, use the `@ApiResponse()` decorator.\n\n```typescript\n@Post()\n@ApiResponse({ status: 201, description: 'The record has been successfully created.'})\n@ApiResponse({ status: 403, description: 'Forbidden.'})\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\nNest provides a set of short-hand **API response** decorators that inherit from the `@ApiResponse` decorator:\n\n- `@ApiOkResponse()`\n- `@ApiCreatedResponse()`\n- `@ApiAcceptedResponse()`\n- `@ApiNoContentResponse()`\n- `@ApiMovedPermanentlyResponse()`\n- `@ApiBadRequestResponse()`\n- `@ApiUnauthorizedResponse()`\n- `@ApiNotFoundResponse()`\n- `@ApiForbiddenResponse()`\n- `@ApiMethodNotAllowedResponse()`\n- `@ApiNotAcceptableResponse()`\n- `@ApiRequestTimeoutResponse()`\n- `@ApiConflictResponse()`\n- `@ApiTooManyRequestsResponse()`\n- `@ApiGoneResponse()`\n- `@ApiPayloadTooLargeResponse()`\n- `@ApiUnsupportedMediaTypeResponse()`\n- `@ApiUnprocessableEntityResponse()`\n- `@ApiInternalServerErrorResponse()`\n- `@ApiNotImplementedResponse()`\n- `@ApiBadGatewayResponse()`\n- `@ApiServiceUnavailableResponse()`\n- `@ApiGatewayTimeoutResponse()`\n- `@ApiDefaultResponse()`\n\n```typescript\n@Post()\n@ApiCreatedResponse({ description: 'The record has been successfully created.'})\n@ApiForbiddenResponse({ description: 'Forbidden.'})\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\nTo specify a return model for a request, we must create a class and annotate all properties with the `@ApiProperty()` decorator.\n\n```typescript\nexport class Cat {\n  @ApiProperty()\n  id: number;\n\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\nThen the `Cat` model can be used in combination with the `type` property of the response decorator.\n\n```typescript\n@ApiTags('cats')\n@Controller('cats')\nexport class CatsController {\n  @Post()\n  @ApiCreatedResponse({\n    description: 'The record has been successfully created.',\n    type: Cat,\n  })\n  async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {\n    return this.catsService.create(createCatDto);\n  }\n}\n```\n\nLet's open the browser and verify the generated `Cat` model:\n\n<figure><img src=\"/assets/swagger-response-type.png\" /></figure>\n\n#### File upload\n\nYou can enable file upload for a specific method with the `@ApiBody` decorator together with `@ApiConsumes()`. Here's a full example using the [File Upload](/techniques/file-upload) technique:\n\n```typescript\n@UseInterceptors(FileInterceptor('file'))\n@ApiConsumes('multipart/form-data')\n@ApiBody({\n  description: 'List of cats',\n  type: FileUploadDto,\n})\nuploadFile(@UploadedFile() file) {}\n```\n\nWhere `FileUploadDto` is defined as follows:\n\n```typescript\nclass FileUploadDto {\n  @ApiProperty({ type: 'string', format: 'binary' })\n  file: any;\n}\n```\n\nTo handle multiple files uploading, you can define `FilesUploadDto` as follows:\n\n```typescript\nclass FilesUploadDto {\n  @ApiProperty({ type: 'array', items: { type: 'string', format: 'binary' } })\n  files: any[];\n}\n```\n\n#### Extensions\n\nTo add an Extension to a request use the `@ApiExtension()` decorator. The extension name must be prefixed with `x-`.\n\n```typescript\n@ApiExtension('x-foo', { hello: 'world' })\n```\n\n#### Advanced: Generic `ApiResponse`\n\nWith the ability to provide [Raw Definitions](/openapi/types-and-parameters#raw-definitions), we can define Generic schema for Swagger UI. Assume we have the following DTO:\n\n```ts\nexport class PaginatedDto<TData> {\n  @ApiProperty()\n  total: number;\n\n  @ApiProperty()\n  limit: number;\n\n  @ApiProperty()\n  offset: number;\n\n  results: TData[];\n}\n```\n\nWe skip decorating `results` as we will be providing a raw definition for it later. Now, let's define another DTO and name it, for example, `CatDto`, as follows:\n\n```ts\nexport class CatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\nWith this in place, we can define a `PaginatedDto<CatDto>` response, as follows:\n\n```ts\n@ApiOkResponse({\n  schema: {\n    allOf: [\n      { $ref: getSchemaPath(PaginatedDto) },\n      {\n        properties: {\n          results: {\n            type: 'array',\n            items: { $ref: getSchemaPath(CatDto) },\n          },\n        },\n      },\n    ],\n  },\n})\nasync findAll(): Promise<PaginatedDto<CatDto>> {}\n```\n\nIn this example, we specify that the response will have allOf `PaginatedDto` and the `results` property will be of type `Array<CatDto>`.\n\n- `getSchemaPath()` function that returns the OpenAPI Schema path from within the OpenAPI Spec File for a given model.\n- `allOf` is a concept that OAS 3 provides to cover various Inheritance related use-cases.\n\nLastly, since `PaginatedDto` is not directly referenced by any controller, the `SwaggerModule` will not be able to generate a corresponding model definition just yet. In this case, we must add it as an [Extra Model](/openapi/types-and-parameters#extra-models). For example, we can use the `@ApiExtraModels()` decorator on the controller level, as follows:\n\n```ts\n@Controller('cats')\n@ApiExtraModels(PaginatedDto)\nexport class CatsController {}\n```\n\nIf you run Swagger now, the generated `swagger.json` for this specific endpoint should have the following response defined:\n\n```json\n\"responses\": {\n  \"200\": {\n    \"description\": \"\",\n    \"content\": {\n      \"application/json\": {\n        \"schema\": {\n          \"allOf\": [\n            {\n              \"$ref\": \"#/components/schemas/PaginatedDto\"\n            },\n            {\n              \"properties\": {\n                \"results\": {\n                  \"$ref\": \"#/components/schemas/CatDto\"\n                }\n              }\n            }\n          ]\n        }\n      }\n    }\n  }\n}\n```\n\nTo make it reusable, we can create a custom decorator for `PaginatedDto`, as follows:\n\n```ts\nexport const ApiPaginatedResponse = <TModel extends Type<any>>(\n  model: TModel,\n) => {\n  return applyDecorators(\n    ApiOkResponse({\n      schema: {\n        allOf: [\n          { $ref: getSchemaPath(PaginatedDto) },\n          {\n            properties: {\n              results: {\n                type: 'array',\n                items: { $ref: getSchemaPath(model) },\n              },\n            },\n          },\n        ],\n      },\n    }),\n  );\n};\n```\n\n> info **Hint** `Type<any>` interface and `applyDecorators` function are imported from the `@nestjs/common` package.\n\nWith this in place, we can use the custom `@ApiPaginatedResponse()` decorator on our endpoint:\n\n```ts\n@ApiPaginatedResponse(CatDto)\nasync findAll(): Promise<PaginatedDto<CatDto>> {}\n```\n\nFor client generation tools, this approach poses an ambiguity in how the `PaginatedResponse<TModel>` is being generated for the client. The following snippet is an example of a client generator result for the above `GET /` endpoint.\n\n```typescript\n// Angular\nfindAll(): Observable<{ total: number, limit: number, offset: number, results: CatDto[] }>\n```\n\nAs you can see, the **Return Type** here is ambiguous. To workaround this issue, you can add a `title` property to the `schema` for `ApiPaginatedResponse`:\n\n```typescript\nexport const ApiPaginatedResponse = <TModel extends Type<any>>(model: TModel) => {\n  return applyDecorators(\n    ApiOkResponse({\n      schema: {\n        title: `PaginatedResponseOf${model.name}`\n        allOf: [\n          // ...\n        ],\n      },\n    }),\n  );\n};\n```\n\nNow the result of the client generator tool will become:\n\n```ts\n// Angular\nfindAll(): Observable<PaginatedResponseOfCatDto>\n```\n"
  },
  {
    "path": "content/openapi/other-features.md",
    "content": "### Other features\n\nThis page lists all the other available features that you may find useful.\n\n#### Global prefix\n\nTo ignore a global prefix for routes set through `setGlobalPrefix()`, use `ignoreGlobalPrefix`:\n\n```typescript\nconst document = SwaggerModule.createDocument(app, options, {\n  ignoreGlobalPrefix: true,\n});\n```\n\n#### Multiple specifications\n\nThe `SwaggerModule` provides a way to support multiple specifications. In other words, you can serve different documentation, with different UIs, on different endpoints.\n\nTo support multiple specifications, your application must be written with a modular approach. The `createDocument()` method takes a 3rd argument, `extraOptions`, which is an object with a property named `include`. The `include` property takes a value which is an array of modules.\n\nYou can setup multiple specifications support as shown below:\n\n```typescript\nimport { NestFactory } from '@nestjs/core';\nimport { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';\nimport { AppModule } from './app.module';\nimport { CatsModule } from './cats/cats.module';\nimport { DogsModule } from './dogs/dogs.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n\n  /**\n   * createDocument(application, configurationOptions, extraOptions);\n   *\n   * createDocument method takes an optional 3rd argument \"extraOptions\"\n   * which is an object with \"include\" property where you can pass an Array\n   * of Modules that you want to include in that Swagger Specification\n   * E.g: CatsModule and DogsModule will have two separate Swagger Specifications which\n   * will be exposed on two different SwaggerUI with two different endpoints.\n   */\n\n  const options = new DocumentBuilder()\n    .setTitle('Cats example')\n    .setDescription('The cats API description')\n    .setVersion('1.0')\n    .addTag('cats')\n    .build();\n\n  const catDocument = SwaggerModule.createDocument(app, options, {\n    include: [CatsModule],\n  });\n  SwaggerModule.setup('api/cats', app, catDocument);\n\n  const secondOptions = new DocumentBuilder()\n    .setTitle('Dogs example')\n    .setDescription('The dogs API description')\n    .setVersion('1.0')\n    .addTag('dogs')\n    .build();\n\n  const dogDocument = SwaggerModule.createDocument(app, secondOptions, {\n    include: [DogsModule],\n  });\n  SwaggerModule.setup('api/dogs', app, dogDocument);\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nNow you can start your server with the following command:\n\n```bash\n$ npm run start\n```\n\nNavigate to `http://localhost:3000/api/cats` to see the Swagger UI for cats:\n\n<figure><img src=\"/assets/swagger-cats.png\" /></figure>\n\nIn turn, `http://localhost:3000/api/dogs` will expose the Swagger UI for dogs:\n\n<figure><img src=\"/assets/swagger-dogs.png\" /></figure>\n"
  },
  {
    "path": "content/openapi/security.md",
    "content": "### 보안\n\n특정 작업에 사용할 보안 메커니즘을 정의하려면 `@ApiSecurity()` 데코레이터를 사용하십시오.\n\n```typescript\n@ApiSecurity('basic')\n@Controller('cats')\nexport class CatsController {}\n```\n\n어플리케이션을 실행하기 전에 `DocumentBuilder`를 사용하여 기본 문서에 보안 정의를 추가해야 합니다.\n\n```typescript\nconst options = new DocumentBuilder().addSecurity('basic', {\n  type: 'http',\n  scheme: 'basic',\n});\n```\n\n주로 사용되는 인증 방식 중 일부는 빌트인(예: `basic` 및 `bearer`)이므로 위와 같이 보안 메커니즘을 직접 정의할 필요가 없습니다.\n\n#### Basic 인증\n\nBasic 인증을 사용하려면 `@ApiBasicAuth()`를 사용하십시오.\n\n```typescript\n@ApiBasicAuth()\n@Controller('cats')\nexport class CatsController {}\n```\n\n어플리케이션을 실행하기 전에 `DocumentBuilder`를 사용하여 기본 문서에 보안 정의를 추가해야 합니다.\n\n```typescript\nconst options = new DocumentBuilder().addBasicAuth();\n```\n\n#### Bearer 인증\n\nBearer 인증을 사용하려면, `@ApiBearerAuth()`를 사용하십시오.\n\n```typescript\n@ApiBearerAuth()\n@Controller('cats')\nexport class CatsController {}\n```\n\n어플리케이션을 실행하기 전에 `DocumentBuilder`를 사용하여 기본 문서에 보안 정의를 추가해야 합니다.\n\n```typescript\nconst options = new DocumentBuilder().addBearerAuth();\n```\n\n#### OAuth2 인증\n\nOAuth2를 사용하려면, `@ApiOAuth2()`를 사용하십시오.\n\n```typescript\n@ApiOAuth2(['pets:write'])\n@Controller('cats')\nexport class CatsController {}\n```\n\n어플리케이션을 실행하기 전에 `DocumentBuilder`를 사용하여 기본 문서에 보안 정의를 추가해야 합니다.\n\n```typescript\nconst options = new DocumentBuilder().addOAuth2();\n```\n\n#### Cookie 인증\n\nCookie 인증을 사용하려면, `@ApiCookieAuth()`를 사용하십시오.\n\n```typescript\n@ApiCookieAuth()\n@Controller('cats')\nexport class CatsController {}\n```\n\n어플리케이션을 실행하기 전에 `DocumentBuilder`를 사용하여 기본 문서에 보안 정의를 추가해야 합니다.\n\n```typescript\nconst options = new DocumentBuilder().addCookieAuth('optional-session-id');\n```\n"
  },
  {
    "path": "content/openapi/types-and-parameters.md",
    "content": "### Types and parameters\n\nThe `SwaggerModule` searches for all `@Body()`, `@Query()`, and `@Param()` decorators in route handlers to generate the API document. It also creates corresponding model definitions by taking advantage of reflection. Consider the following code:\n\n```typescript\n@Post()\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n> info **Hint** To explicitly set the body definition use the `@ApiBody()` decorator (imported from the `@nestjs/swagger` package).\n\nBased on the `CreateCatDto`, the following model definition Swagger UI will be created:\n\n<figure><img src=\"/assets/swagger-dto.png\" /></figure>\n\nAs you can see, the definition is empty although the class has a few declared properties. In order to make the class properties visible to the `SwaggerModule`, we have to either annotate them with the `@ApiProperty()` decorator or use the CLI plugin (read more in the **Plugin** section) which will do it automatically:\n\n```typescript\nimport { ApiProperty } from '@nestjs/swagger';\n\nexport class CreateCatDto {\n  @ApiProperty()\n  name: string;\n\n  @ApiProperty()\n  age: number;\n\n  @ApiProperty()\n  breed: string;\n}\n```\n\n> info **Hint** Instead of manually annotating each property, consider using the Swagger plugin (see [Plugin](/openapi/cli-plugin) section) which will automatically provide this for you.\n\nLet's open the browser and verify the generated `CreateCatDto` model:\n\n<figure><img src=\"/assets/swagger-dto2.png\" /></figure>\n\nIn addition, the `@ApiProperty()` decorator allows setting various [Schema Object](https://swagger.io/specification/#schemaObject) properties:\n\n```typescript\n@ApiProperty({\n  description: 'The age of a cat',\n  minimum: 1,\n  default: 1,\n})\nage: number;\n```\n\n> info **Hint** Instead of explicitly typing the `{{\"@ApiProperty({ required: false })\"}}` you can use the `@ApiPropertyOptional()` short-hand decorator.\n\nIn order to explicitly set the type of the property, use the `type` key:\n\n```typescript\n@ApiProperty({\n  type: Number,\n})\nage: number;\n```\n\n#### Arrays\n\nWhen the property is an array, we must manually indicate the array type as shown below:\n\n```typescript\n@ApiProperty({ type: [String] })\nnames: string[];\n```\n\n> info **Hint** Consider using the Swagger plugin (see [Plugin](/openapi/cli-plugin) section) which will automatically detect arrays.\n\nEither include the type as the first element of an array (as shown above) or set the `isArray` property to `true`.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Circular dependencies\n\nWhen you have circular dependencies between classes, use a lazy function to provide the `SwaggerModule` with type information:\n\n```typescript\n@ApiProperty({ type: () => Node })\nnode: Node;\n```\n\n> info **Hint** Consider using the Swagger plugin (see [Plugin](/openapi/cli-plugin) section) which will automatically detect circular dependencies.\n\n#### Generics and interfaces\n\nSince TypeScript does not store metadata about generics or interfaces, when you use them in your DTOs, `SwaggerModule` may not be able to properly generate model definitions at runtime. For instance, the following code won't be correctly inspected by the Swagger module:\n\n```typescript\ncreateBulk(@Body() usersDto: CreateUserDto[])\n```\n\nIn order to overcome this limitation, you can set the type explicitly:\n\n```typescript\n@ApiBody({ type: [CreateUserDto] })\ncreateBulk(@Body() usersDto: CreateUserDto[])\n```\n\n#### Enums\n\nTo identify an `enum`, we must manually set the `enum` property on the `@ApiProperty` with an array of values.\n\n```typescript\n@ApiProperty({ enum: ['Admin', 'Moderator', 'User']})\nrole: UserRole;\n```\n\nAlternatively, define an actual TypeScript enum as follows:\n\n```typescript\nexport enum UserRole {\n  Admin = 'Admin',\n  Moderator = 'Moderator',\n  User = 'User',\n}\n```\n\nYou can then use the enum directly with the `@Query()` parameter decorator in combination with the `@ApiQuery()` decorator.\n\n```typescript\n@ApiQuery({ name: 'role', enum: UserRole })\nasync filterByRole(@Query('role') role: UserRole = UserRole.User) {}\n```\n\n<figure><img src=\"/assets/enum_query.gif\" /></figure>\n\nWith `isArray` set to **true**, the `enum` can be selected as a **multi-select**:\n\n<figure><img src=\"/assets/enum_query_array.gif\" /></figure>\n\n#### Enums schema\n\nBy default, the `enum` property will add a raw definition of [Enum](https://swagger.io/docs/specification/data-models/enums/) on the `parameter`.\n\n```yaml\n- breed:\n    type: 'string'\n    enum:\n      - Persian\n      - Tabby\n      - Siamese\n```\n\nThe above specification works fine for most cases. However, if you are utilizing a tool that takes the specification as **input** and generates **client-side** code, you might run into a problem with the generated code containing duplicated `enums`. Consider the following code snippet:\n\n```typescript\n// generated client-side code\nexport class CatDetail {\n  breed: CatDetailEnum;\n}\n\nexport class CatInformation {\n  breed: CatInformationEnum;\n}\n\nexport enum CatDetailEnum {\n  Persian = 'Persian',\n  Tabby = 'Tabby',\n  Siamese = 'Siamese',\n}\n\nexport enum CatInformationEnum {\n  Persian = 'Persian',\n  Tabby = 'Tabby',\n  Siamese = 'Siamese',\n}\n```\n\n> info **Hint** The above snippet is generated using a tool called [NSwag](https://github.com/RicoSuter/NSwag).\n\nYou can see that now you have two `enums` that are exactly the same.\nTo address this issue, you can pass an `enumName` along with the `enum` property in your decorator.\n\n```typescript\nexport class CatDetail {\n  @ApiProperty({ enum: CatBreed, enumName: 'CatBreed' })\n  breed: CatBreed;\n}\n```\n\nThe `enumName` property enables `@nestjs/swagger` to turn `CatBreed` into its own `schema` which in turns makes `CatBreed` enum reusable. The specification will look like the following:\n\n```yaml\nCatDetail:\n  type: 'object'\n  properties:\n    ...\n    - breed:\n        schema:\n          $ref: '#/components/schemas/CatBreed'\nCatBreed:\n  type: string\n  enum:\n    - Persian\n    - Tabby\n    - Siamese\n```\n\n> info **Hint** Any **decorator** that takes `enum` as a property will also take `enumName`.\n\n#### Raw definitions\n\nIn some specific scenarios (e.g., deeply nested arrays, matrices), you may want to describe your type by hand.\n\n```typescript\n@ApiProperty({\n  type: 'array',\n  items: {\n    type: 'array',\n    items: {\n      type: 'number',\n    },\n  },\n})\ncoords: number[][];\n```\n\nLikewise, in order to define your input/output content manually in controller classes, use the `schema` property:\n\n```typescript\n@ApiBody({\n  schema: {\n    type: 'array',\n    items: {\n      type: 'array',\n      items: {\n        type: 'number',\n      },\n    },\n  },\n})\nasync create(@Body() coords: number[][]) {}\n```\n\n#### Extra models\n\nTo define additional models that are not directly referenced in your controllers but should be inspected by the Swagger module, use the `@ApiExtraModels()` decorator:\n\n```typescript\n@ApiExtraModels(ExtraModel)\nexport class CreateCatDto {}\n```\n\n> info **Hint** You only need to use `@ApiExtraModels()` once for a specific model class.\n\nAlternatively, you can pass an options object with the `extraModels` property specified to the `SwaggerModule#createDocument()` method, as follows:\n\n```typescript\nconst document = SwaggerModule.createDocument(app, options, {\n  extraModels: [ExtraModel],\n});\n```\n\nTo get a reference (`$ref`) to your model, use the `getSchemaPath(ExtraModel)` function:\n\n```typescript\n'application/vnd.api+json': {\n   schema: { $ref: getSchemaPath(ExtraModel) },\n},\n```\n\n#### oneOf, anyOf, allOf\n\nTo combine schemas, you can use the `oneOf`, `anyOf` or `allOf` keywords ([read more](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/)).\n\n```typescript\n@ApiProperty({\n  oneOf: [\n    { $ref: getSchemaPath(Cat) },\n    { $ref: getSchemaPath(Dog) },\n  ],\n})\npet: Cat | Dog;\n```\n\nIf you want to define a polymorphic array (i.e., an array whose members span multiple schemas), you should use a raw definition (see above) to define your type by hand.\n\n```typescript\ntype Pet = Cat | Dog;\n\n@ApiProperty({\n  type: 'array',\n  items: {\n    oneOf: [\n      { $ref: getSchemaPath(Cat) },\n      { $ref: getSchemaPath(Dog) },\n    ],\n  },\n})\npets: Pet[];\n```\n\n> info **Hint** The `getSchemaPath()` function is imported from `@nestjs/swagger`.\n\nBoth `Cat` and `Dog` must be defined as extra models using the `@ApiExtraModels()` decorator (at the class-level).\n"
  },
  {
    "path": "content/pipes.md",
    "content": "### Pipes\n\nA pipe is a class annotated with the `@Injectable()` decorator. Pipes should implement the `PipeTransform` interface.\n\n<figure>\n  <img src=\"/assets/Pipe_1.png\" />\n</figure>\n\nPipes have two typical use cases:\n\n- **transformation**: transform input data to the desired form (e.g., from string to integer)\n- **validation**: evaluate input data and if valid, simply pass it through unchanged; otherwise, throw an exception when the data is incorrect\n\nIn both cases, pipes operate on the `arguments` being processed by a <a href=\"controllers#route-parameters\">controller route handler</a>. Nest interposes a pipe just before a method is invoked, and the pipe receives the arguments destined for the method and operates on them. Any transformation or validation operation takes place at that time, after which the route handler is invoked with any (potentially) transformed arguments.\n\nNest comes with a number of built-in pipes that you can use out-of-the-box. You can also build your own custom pipes. In this chapter, we'll introduce the built-in pipes and show how to bind them to route handlers. We'll then examine several custom-built pipes to show how you can build one from scratch.\n\n> info **Hint** Pipes run inside the exceptions zone. This means that when a Pipe throws an exception it is handled by the exceptions layer (global exceptions filter and any [exceptions filters](/exception-filters) that are applied to the current context). Given the above, it should be clear that when an exception is thrown in a Pipe, no controller method is subsequently executed. This gives you a best-practice technique for validating data coming into the application from external sources at the system boundary.\n\n#### Built-in pipes\n\nNest comes with eight pipes available out-of-the-box:\n\n- `ValidationPipe`\n- `ParseIntPipe`\n- `ParseFloatPipe`\n- `ParseBoolPipe`\n- `ParseArrayPipe`\n- `ParseUUIDPipe`\n- `ParseEnumPipe`\n- `DefaultValuePipe`\n\nThey're exported from the `@nestjs/common` package.\n\nLet's take a quick look at using `ParseIntPipe`. This is an example of the **transformation** use case, where the pipe ensures that a method handler parameter is converted to a JavaScript integer (or throws an exception if the conversion fails). Later in this chapter, we'll show a simple custom implementation for a `ParseIntPipe`. The example techniques below also apply to the other built-in transformation pipes (`ParseBoolPipe`, `ParseFloatPipe`, `ParseEnumPipe`, `ParseArrayPipe` and `ParseUUIDPipe`, which we'll refer to as the `Parse*` pipes in this chapter).\n\n#### Binding pipes\n\nTo use a pipe, we need to bind an instance of the pipe class to the appropriate context. In our `ParseIntPipe` example, we want to associate the pipe with a particular route handler method, and make sure it runs before the method is called. We do so with the following construct, which we'll refer to as binding the pipe at the method parameter level:\n\n```typescript\n@Get(':id')\nasync findOne(@Param('id', ParseIntPipe) id: number) {\n  return this.catsService.findOne(id);\n}\n```\n\nThis ensures that one of the following two conditions is true: either the parameter we receive in the `findOne()` method is a number (as expected in our call to `this.catsService.findOne()`), or an exception is thrown before the route handler is called.\n\nFor example, assume the route is called like:\n\n```bash\nGET localhost:3000/abc\n```\n\nNest will throw an exception like this:\n\n```json\n{\n  \"statusCode\": 400,\n  \"message\": \"Validation failed (numeric string is expected)\",\n  \"error\": \"Bad Request\"\n}\n```\n\nThe exception will prevent the body of the `findOne()` method from executing.\n\nIn the example above, we pass a class (`ParseIntPipe`), not an instance, leaving responsibility for instantiation to the framework and enabling dependency injection. As with pipes and guards, we can instead pass an in-place instance. Passing an in-place instance is useful if we want to customize the built-in pipe's behavior by passing options:\n\n```typescript\n@Get(':id')\nasync findOne(\n  @Param('id', new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE }))\n  id: number,\n) {\n  return this.catsService.findOne(id);\n}\n```\n\nBinding the other transformation pipes (all of the **Parse\\*** pipes) works similarly. These pipes all work in the context of validating route parameters, query string parameters and request body values.\n\nFor example with a query string parameter:\n\n```typescript\n@Get()\nasync findOne(@Query('id', ParseIntPipe) id: number) {\n  return this.catsService.findOne(id);\n}\n```\n\nHere's an example of using the `ParseUUIDPipe` to parse a string parameter and validate if it is a UUID.\n\n```typescript\n@@filename()\n@Get(':uuid')\nasync findOne(@Param('uuid', new ParseUUIDPipe()) uuid: string) {\n  return this.catsService.findOne(uuid);\n}\n@@switch\n@Get(':uuid')\n@Bind(Param('uuid', new ParseUUIDPipe()))\nasync findOne(uuid) {\n  return this.catsService.findOne(uuid);\n}\n```\n\n> info **Hint** When using `ParseUUIDPipe()` you are parsing UUID in version 3, 4 or 5, if you only require a specific version of UUID you can pass a version in the pipe options.\n\nAbove we've seen examples of binding the various `Parse*` family of built-in pipes. Binding validation pipes is a little bit different; we'll discuss that in the following section.\n\n> info **Hint** Also, see [Validation techniques](/techniques/validation) for extensive examples of validation pipes.\n\n#### Custom pipes\n\nAs mentioned, you can build your own custom pipes. While Nest provides a robust built-in `ParseIntPipe` and `ValidationPipe`, let's build simple custom versions of each from scratch to see how custom pipes are constructed.\n\nWe start with a simple `ValidationPipe`. Initially, we'll have it simply take an input value and immediately return the same value, behaving like an identity function.\n\n```typescript\n@@filename(validation.pipe)\nimport { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';\n\n@Injectable()\nexport class ValidationPipe implements PipeTransform {\n  transform(value: any, metadata: ArgumentMetadata) {\n    return value;\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ValidationPipe {\n  transform(value, metadata) {\n    return value;\n  }\n}\n```\n\n> info **Hint** `PipeTransform<T, R>` is a generic interface that must be implemented by any pipe. The generic interface uses `T` to indicate the type of the input `value`, and `R` to indicate the return type of the `transform()` method.\n\nEvery pipe must implement the `transform()` method to fulfill the `PipeTransform` interface contract. This method has two parameters:\n\n- `value`\n- `metadata`\n\nThe `value` parameter is the currently processed method argument (before it is received by the route handling method), and `metadata` is the currently processed method argument's metadata. The metadata object has these properties:\n\n```typescript\nexport interface ArgumentMetadata {\n  type: 'body' | 'query' | 'param' | 'custom';\n  metatype?: Type<unknown>;\n  data?: string;\n}\n```\n\nThese properties describe the currently processed argument.\n\n<table>\n  <tr>\n    <td>\n      <code>type</code>\n    </td>\n    <td>Indicates whether the argument is a body\n      <code>@Body()</code>, query\n      <code>@Query()</code>, param\n      <code>@Param()</code>, or a custom parameter (read more\n      <a routerLink=\"/custom-decorators\">here</a>).</td>\n  </tr>\n  <tr>\n    <td>\n      <code>metatype</code>\n    </td>\n    <td>\n      Provides the metatype of the argument, for example,\n      <code>String</code>. Note: the value is\n      <code>undefined</code> if you either omit a type declaration in the route handler method signature, or use vanilla JavaScript.\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>data</code>\n    </td>\n    <td>The string passed to the decorator, for example\n      <code>@Body('string')</code>. It's\n      <code>undefined</code> if you leave the decorator parenthesis empty.</td>\n  </tr>\n</table>\n\n> warning **Warning** TypeScript interfaces disappear during transpilation. Thus, if a method parameter's type is declared as an interface instead of a class, the `metatype` value will be `Object`.\n\n#### Schema based validation\n\nLet's make our validation pipe a little more useful. Take a closer look at the `create()` method of the `CatsController`, where we probably would like to ensure that the post body object is valid before attempting to run our service method.\n\n```typescript\n@@filename()\n@Post()\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\nasync create(@Body() createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\nLet's focus in on the `createCatDto` body parameter. Its type is `CreateCatDto`:\n\n```typescript\n@@filename(create-cat.dto)\nexport class CreateCatDto {\n  name: string;\n  age: number;\n  breed: string;\n}\n```\n\nWe want to ensure that any incoming request to the create method contains a valid body. So we have to validate the three members of the `createCatDto` object. We could do this inside the route handler method, but doing so is not ideal as it would break the **single responsibility rule** (SRP).\n\nAnother approach could be to create a **validator class** and delegate the task there. This has the disadvantage that we would have to remember to call this validator at the beginning of each method.\n\nHow about creating validation middleware? This could work, but unfortunately it's not possible to create **generic middleware** which can be used across all contexts across the whole application. This is because middleware is unaware of the **execution context**, including the handler that will be called and any of its parameters.\n\nThis is, of course, exactly the use case for which pipes are designed. So let's go ahead and refine our validation pipe.\n\n<app-banner-courses></app-banner-courses>\n\n#### Object schema validation\n\nThere are several approaches available for doing object validation in a clean, [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) way. One common approach is to use **schema-based** validation. Let's go ahead and try that approach.\n\nThe [Joi](https://github.com/sideway/joi) library allows you to create schemas in a straightforward way, with a readable API. Let's build a validation pipe that makes use of Joi-based schemas.\n\nStart by installing the required package:\n\n```bash\n$ npm install --save joi\n$ npm install --save-dev @types/joi\n```\n\nIn the code sample below, we create a simple class that takes a schema as a `constructor` argument. We then apply the `schema.validate()` method, which validates our incoming argument against the provided schema.\n\nAs noted earlier, a **validation pipe** either returns the value unchanged, or throws an exception.\n\nIn the next section, you'll see how we supply the appropriate schema for a given controller method using the `@UsePipes()` decorator. Doing so makes our validation pipe re-usable across contexts, just as we set out to do.\n\n```typescript\n@@filename()\nimport { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';\nimport { ObjectSchema } from 'joi';\n\n@Injectable()\nexport class JoiValidationPipe implements PipeTransform {\n  constructor(private schema: ObjectSchema) {}\n\n  transform(value: any, metadata: ArgumentMetadata) {\n    const { error } = this.schema.validate(value);\n    if (error) {\n      throw new BadRequestException('Validation failed');\n    }\n    return value;\n  }\n}\n@@switch\nimport { Injectable, BadRequestException } from '@nestjs/common';\n\n@Injectable()\nexport class JoiValidationPipe {\n  constructor(schema) {\n    this.schema = schema;\n  }\n\n  transform(value, metadata) {\n    const { error } = this.schema.validate(value);\n    if (error) {\n      throw new BadRequestException('Validation failed');\n    }\n    return value;\n  }\n}\n```\n\n#### Binding validation pipes\n\nEarlier, we saw how to bind transformation pipes (like `ParseIntPipe` and the rest of the `Parse*` pipes).\n\nBinding validation pipes is also very straightforward.\n\nIn this case, we want to bind the pipe at the method call level. In our current example, we need to do the following to use the `JoiValidationPipe`:\n\n1. Create an instance of the `JoiValidationPipe`\n2. Pass the context-specific Joi schema in the class constructor of the pipe\n3. Bind the pipe to the method\n\nWe do that using the `@UsePipes()` decorator as shown below:\n\n```typescript\n@@filename()\n@Post()\n@UsePipes(new JoiValidationPipe(createCatSchema))\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@Bind(Body())\n@UsePipes(new JoiValidationPipe(createCatSchema))\nasync create(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n> info **Hint** The `@UsePipes()` decorator is imported from the `@nestjs/common` package.\n\n#### Class validator\n\n> warning **Warning** The techniques in this section require TypeScript, and are not available if your app is written using vanilla JavaScript.\n\nLet's look at an alternate implementation for our validation technique.\n\nNest works well with the [class-validator](https://github.com/typestack/class-validator) library. This powerful library allows you to use decorator-based validation. Decorator-based validation is extremely powerful, especially when combined with Nest's **Pipe** capabilities since we have access to the `metatype` of the processed property. Before we start, we need to install the required packages:\n\n```bash\n$ npm i --save class-validator class-transformer\n```\n\nOnce these are installed, we can add a few decorators to the `CreateCatDto` class. Here we see a significant advantage of this technique: the `CreateCatDto` class remains the single source of truth for our Post body object (rather than having to create a separate validation class).\n\n```typescript\n@@filename(create-cat.dto)\nimport { IsString, IsInt } from 'class-validator';\n\nexport class CreateCatDto {\n  @IsString()\n  name: string;\n\n  @IsInt()\n  age: number;\n\n  @IsString()\n  breed: string;\n}\n```\n\n> info **Hint** Read more about the class-validator decorators [here](https://github.com/typestack/class-validator#usage).\n\nNow we can create a `ValidationPipe` class that uses these annotations.\n\n```typescript\n@@filename(validation.pipe)\nimport { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';\nimport { validate } from 'class-validator';\nimport { plainToClass } from 'class-transformer';\n\n@Injectable()\nexport class ValidationPipe implements PipeTransform<any> {\n  async transform(value: any, { metatype }: ArgumentMetadata) {\n    if (!metatype || !this.toValidate(metatype)) {\n      return value;\n    }\n    const object = plainToClass(metatype, value);\n    const errors = await validate(object);\n    if (errors.length > 0) {\n      throw new BadRequestException('Validation failed');\n    }\n    return value;\n  }\n\n  private toValidate(metatype: Function): boolean {\n    const types: Function[] = [String, Boolean, Number, Array, Object];\n    return !types.includes(metatype);\n  }\n}\n```\n\n> warning **Notice** Above, we have used the [class-transformer](https://github.com/typestack/class-transformer) library. It's made by the same author as the **class-validator** library, and as a result, they play very well together.\n\nLet's go through this code. First, note that the `transform()` method is marked as `async`. This is possible because Nest supports both synchronous and **asynchronous** pipes. We make this method `async` because some of the class-validator validations [can be async](https://github.com/typestack/class-validator#custom-validation-classes) (utilize Promises).\n\nNext note that we are using destructuring to extract the metatype field (extracting just this member from an `ArgumentMetadata`) into our `metatype` parameter. This is just shorthand for getting the full `ArgumentMetadata` and then having an additional statement to assign the metatype variable.\n\nNext, note the helper function `toValidate()`. It's responsible for bypassing the validation step when the current argument being processed is a native JavaScript type (these can't have validation decorators attached, so there's no reason to run them through the validation step).\n\nNext, we use the class-transformer function `plainToClass()` to transform our plain JavaScript argument object into a typed object so that we can apply validation. The reason we must do this is that the incoming post body object, when deserialized from the network request, does **not have any type information** (this is the way the underlying platform, such as Express, works). Class-validator needs to use the validation decorators we defined for our DTO earlier, so we need to perform this transformation to treat the incoming body as an appropriately decorated object, not just a plain vanilla object.\n\nFinally, as noted earlier, since this is a **validation pipe** it either returns the value unchanged, or throws an exception.\n\nThe last step is to bind the `ValidationPipe`. Pipes can be parameter-scoped, method-scoped, controller-scoped, or global-scoped. Earlier, with our Joi-based validation pipe, we saw an example of binding the pipe at the method level.\nIn the example below, we'll bind the pipe instance to the route handler `@Body()` decorator so that our pipe is called to validate the post body.\n\n```typescript\n@@filename(cats.controller)\n@Post()\nasync create(\n  @Body(new ValidationPipe()) createCatDto: CreateCatDto,\n) {\n  this.catsService.create(createCatDto);\n}\n```\n\nParameter-scoped pipes are useful when the validation logic concerns only one specified parameter.\n\n#### Global scoped pipes\n\nSince the `ValidationPipe` was created to be as generic as possible, we can realize it's full utility by setting it up as a **global-scoped** pipe so that it is applied to every route handler across the entire application.\n\n```typescript\n@@filename(main)\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> warning **Notice** In the case of <a href=\"faq/hybrid-application\">hybrid apps</a> the `useGlobalPipes()` method doesn't set up pipes for gateways and micro services. For \"standard\" (non-hybrid) microservice apps, `useGlobalPipes()` does mount pipes globally.\n\nGlobal pipes are used across the whole application, for every controller and every route handler.\n\nNote that in terms of dependency injection, global pipes registered from outside of any module (with `useGlobalPipes()` as in the example above) cannot inject dependencies since the binding has been done outside the context of any module. In order to solve this issue, you can set up a global pipe **directly from any module** using the following construction:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { APP_PIPE } from '@nestjs/core';\n\n@Module({\n  providers: [\n    {\n      provide: APP_PIPE,\n      useClass: ValidationPipe,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n> info **Hint** When using this approach to perform dependency injection for the pipe, note that regardless of the module where this construction is employed, the pipe is, in fact, global. Where should this be done? Choose the module where the pipe (`ValidationPipe` in the example above) is defined. Also, `useClass` is not the only way of dealing with custom provider registration. Learn more [here](/fundamentals/custom-providers).\n\n#### The built-in ValidationPipe\n\nAs a reminder, you don't have to build a generic validation pipe on your own since the `ValidationPipe` is provided by Nest out-of-the-box. The built-in `ValidationPipe` offers more options than the sample we built in this chapter, which has been kept basic for the sake of illustrating the mechanics of a custom-built pipe. You can find full details, along with lots of examples [here](/techniques/validation).\n\n#### Transformation use case\n\nValidation isn't the only use case for custom pipes. At the beginning of this chapter, we mentioned that a pipe can also **transform** the input data to the desired format. This is possible because the value returned from the `transform` function completely overrides the previous value of the argument.\n\nWhen is this useful? Consider that sometimes the data passed from the client needs to undergo some change - for example converting a string to an integer - before it can be properly handled by the route handler method. Furthermore, some required data fields may be missing, and we would like to apply default values. **Transformation pipes** can perform these functions by interposing a processing function between the client request and the request handler.\n\nHere's a simple `ParseIntPipe` which is responsible for parsing a string into an integer value. (As noted above, Nest has a built-in `ParseIntPipe` that is more sophisticated; we include this as a simple example of a custom transformation pipe).\n\n```typescript\n@@filename(parse-int.pipe)\nimport { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';\n\n@Injectable()\nexport class ParseIntPipe implements PipeTransform<string, number> {\n  transform(value: string, metadata: ArgumentMetadata): number {\n    const val = parseInt(value, 10);\n    if (isNaN(val)) {\n      throw new BadRequestException('Validation failed');\n    }\n    return val;\n  }\n}\n@@switch\nimport { Injectable, BadRequestException } from '@nestjs/common';\n\n@Injectable()\nexport class ParseIntPipe {\n  transform(value, metadata) {\n    const val = parseInt(value, 10);\n    if (isNaN(val)) {\n      throw new BadRequestException('Validation failed');\n    }\n    return val;\n  }\n}\n```\n\nWe can then bind this pipe to the selected param as shown below:\n\n```typescript\n@@filename()\n@Get(':id')\nasync findOne(@Param('id', new ParseIntPipe()) id) {\n  return this.catsService.findOne(id);\n}\n@@switch\n@Get(':id')\n@Bind(Param('id', new ParseIntPipe()))\nasync findOne(id) {\n  return this.catsService.findOne(id);\n}\n```\n\nAnother useful transformation case would be to select an **existing user** entity from the database using an id supplied in the request:\n\n```typescript\n@@filename()\n@Get(':id')\nfindOne(@Param('id', UserByIdPipe) userEntity: UserEntity) {\n  return userEntity;\n}\n@@switch\n@Get(':id')\n@Bind(Param('id', UserByIdPipe))\nfindOne(userEntity) {\n  return userEntity;\n}\n```\n\nWe leave the implementation of this pipe to the reader, but note that like all other transformation pipes, it receives an input value (an `id`) and returns an output value (a `UserEntity` object). This can make your code more declarative and [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) by abstracting boilerplate code out of your handler and into a common pipe.\n\n#### Providing defaults\n\n`Parse*` pipes expect a parameter's value to be defined. They throw an exception upon receiving `null` or `undefined` values. To allow an endpoint to handle missing querystring parameter values, we have to provide a default value to be injected before the `Parse*` pipes operate on these values. The `DefaultValuePipe` serves that purpose. Simply instantiate a `DefaultValuePipe` in the `@Query()` decorator before the relevant `Parse*` pipe, as shown below:\n\n```typescript\n@@filename()\n@Get()\nasync findAll(\n  @Query('activeOnly', new DefaultValuePipe(false), ParseBoolPipe) activeOnly: boolean,\n  @Query('page', new DefaultValuePipe(0), ParseIntPipe) page: number,\n) {\n  return this.catsService.findAll({ activeOnly, page });\n}\n```\n"
  },
  {
    "path": "content/recipes/cqrs.md",
    "content": "### CQRS\n\nThe flow of simple [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) (Create, Read, Update and Delete) applications can be described using the following steps:\n\n1. The **controllers** layer handles HTTP requests and delegates tasks to the services layer.\n2. The **services layer** is where most of the business logic lives.\n3. Services use **repositories / DAOs** to change / persist entities.\n4. Entities act as containers for the values, with setters and getters.\n\nIn most cases, for small and medium-sized applications, this pattern is sufficient. However, when our requirements become more complex, the **CQRS** model may be more appropriate and scalable. To facilitate that model, Nest provides a lightweight [CQRS module](https://github.com/nestjs/cqrs). This chapter describes how to use it.\n\n#### Installation\n\nFirst install the required package:\n\n```bash\n$ npm install --save @nestjs/cqrs\n```\n\n#### Commands\n\nIn this model, each action is called a **Command**. When a command is dispatched, the application reacts to it. Commands can be dispatched from the services layer, or directly from controllers/gateways. Commands are consumed by **Command Handlers**.\n\n```typescript\n@@filename(heroes-game.service)\n@Injectable()\nexport class HeroesGameService {\n  constructor(private commandBus: CommandBus) {}\n\n  async killDragon(heroId: string, killDragonDto: KillDragonDto) {\n    return this.commandBus.execute(\n      new KillDragonCommand(heroId, killDragonDto.dragonId)\n    );\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(CommandBus)\nexport class HeroesGameService {\n  constructor(commandBus) {\n    this.commandBus = commandBus;\n  }\n\n  async killDragon(heroId, killDragonDto) {\n    return this.commandBus.execute(\n      new KillDragonCommand(heroId, killDragonDto.dragonId)\n    );\n  }\n}\n```\n\nHere's a sample service that dispatches `KillDragonCommand`. Let's see how the command looks:\n\n```typescript\n@@filename(kill-dragon.command)\nexport class KillDragonCommand {\n  constructor(\n    public readonly heroId: string,\n    public readonly dragonId: string,\n  ) {}\n}\n@@switch\nexport class KillDragonCommand {\n  constructor(heroId, dragonId) {\n    this.heroId = heroId;\n    this.dragonId = dragonId;\n  }\n}\n```\n\nThe `CommandBus` is a **stream** of commands. It delegates commands to the equivalent handlers. Each command must have a corresponding **Command Handler**:\n\n```typescript\n@@filename(kill-dragon.handler)\n@CommandHandler(KillDragonCommand)\nexport class KillDragonHandler implements ICommandHandler<KillDragonCommand> {\n  constructor(private repository: HeroRepository) {}\n\n  async execute(command: KillDragonCommand) {\n    const { heroId, dragonId } = command;\n    const hero = this.repository.findOneById(+heroId);\n\n    hero.killEnemy(dragonId);\n    await this.repository.persist(hero);\n  }\n}\n@@switch\n@CommandHandler(KillDragonCommand)\n@Dependencies(HeroRepository)\nexport class KillDragonHandler {\n  constructor(repository) {\n    this.repository = repository;\n  }\n\n  async execute(command) {\n    const { heroId, dragonId } = command;\n    const hero = this.repository.findOneById(+heroId);\n\n    hero.killEnemy(dragonId);\n    await this.repository.persist(hero);\n  }\n}\n```\n\nWith this approach, every application state change is driven by the occurrence of a **Command**. The logic is encapsulated in handlers. With this approach, we can simply add behavior like logging or persisting commands in the database (e.g., for diagnostics purposes).\n\n#### Events\n\nCommand handlers neatly encapsulate logic. While beneficial, the application structure is still not flexible enough, not **reactive**. To remedy this, we also introduce **events**.\n\n```typescript\n@@filename(hero-killed-dragon.event)\nexport class HeroKilledDragonEvent {\n  constructor(\n    public readonly heroId: string,\n    public readonly dragonId: string,\n  ) {}\n}\n@@switch\nexport class HeroKilledDragonEvent {\n  constructor(heroId, dragonId) {\n    this.heroId = heroId;\n    this.dragonId = dragonId;\n  }\n}\n```\n\nEvents are asynchronous. They are dispatched either by **models** or directly using `EventBus`. In order to dispatch events, models have to extend the `AggregateRoot` class.\n\n```typescript\n@@filename(hero.model)\nexport class Hero extends AggregateRoot {\n  constructor(private id: string) {\n    super();\n  }\n\n  killEnemy(enemyId: string) {\n    // logic\n    this.apply(new HeroKilledDragonEvent(this.id, enemyId));\n  }\n}\n@@switch\nexport class Hero extends AggregateRoot {\n  constructor(id) {\n    super();\n    this.id = id;\n  }\n\n  killEnemy(enemyId) {\n    // logic\n    this.apply(new HeroKilledDragonEvent(this.id, enemyId));\n  }\n}\n```\n\nThe `apply()` method does not dispatch events yet because there's no relationship between the model and the `EventPublisher` class. How do we associate the model and the publisher? By using a publisher `mergeObjectContext()` method inside our command handler.\n\n```typescript\n@@filename(kill-dragon.handler)\n@CommandHandler(KillDragonCommand)\nexport class KillDragonHandler implements ICommandHandler<KillDragonCommand> {\n  constructor(\n    private repository: HeroRepository,\n    private publisher: EventPublisher,\n  ) {}\n\n  async execute(command: KillDragonCommand) {\n    const { heroId, dragonId } = command;\n    const hero = this.publisher.mergeObjectContext(\n      await this.repository.findOneById(+heroId),\n    );\n    hero.killEnemy(dragonId);\n    hero.commit();\n  }\n}\n@@switch\n@CommandHandler(KillDragonCommand)\n@Dependencies(HeroRepository, EventPublisher)\nexport class KillDragonHandler {\n  constructor(repository, publisher) {\n    this.repository = repository;\n    this.publisher = publisher;\n  }\n\n  async execute(command) {\n    const { heroId, dragonId } = command;\n    const hero = this.publisher.mergeObjectContext(\n      await this.repository.findOneById(+heroId),\n    );\n    hero.killEnemy(dragonId);\n    hero.commit();\n  }\n}\n```\n\nNow everything works as expected. Notice that we need to `commit()` events since they're not being dispatched immediately. Obviously, an object doesn't have to exist up front. We can easily merge type context as well:\n\n```typescript\nconst HeroModel = this.publisher.mergeClassContext(Hero);\nnew HeroModel('id');\n```\n\nNow the model has the ability to publish events. Additionally, we can emit events manually using `EventBus`:\n\n```typescript\nthis.eventBus.publish(new HeroKilledDragonEvent());\n```\n\n> info **Hint** The `EventBus` is an injectable class.\n\nEach event can have multiple **Event Handlers**.\n\n```typescript\n@@filename(hero-killed-dragon.handler)\n@EventsHandler(HeroKilledDragonEvent)\nexport class HeroKilledDragonHandler implements IEventHandler<HeroKilledDragonEvent> {\n  constructor(private repository: HeroRepository) {}\n\n  handle(event: HeroKilledDragonEvent) {\n    // logic\n  }\n}\n```\n\nNow we can move the **write logic** into the event handlers.\n\n#### Sagas\n\nThis type of **Event-Driven Architecture** improves application **reactiveness and scalability**. Now, when we have events, we can simply react to them in various ways. **Sagas** are the final building block from an architectural point of view.\n\nSagas are an extremely powerful feature. A single saga may listen for 1..\\* events. Using the [RxJS](https://github.com/ReactiveX/rxjs) library, it can combine, merge, filter or apply other `RxJS` operators on the event stream. Each saga returns an Observable which contains a command. This command is dispatched **asynchronously**.\n\n```typescript\n@@filename(heroes-game.saga)\n@Injectable()\nexport class HeroesGameSagas {\n  @Saga()\n  dragonKilled = (events$: Observable<any>): Observable<ICommand> => {\n    return events$.pipe(\n      ofType(HeroKilledDragonEvent),\n      map((event) => new DropAncientItemCommand(event.heroId, fakeItemID)),\n    );\n  }\n}\n@@switch\n@Injectable()\nexport class HeroesGameSagas {\n  @Saga()\n  dragonKilled = (events$) => {\n    return events$.pipe(\n      ofType(HeroKilledDragonEvent),\n      map((event) => new DropAncientItemCommand(event.heroId, fakeItemID)),\n    );\n  }\n}\n```\n\n> info **Hint** The `ofType` operator is exported from the `@nestjs/cqrs` package.\n\nWe declared a rule - when any hero kills the dragon, the ancient item should be dropped. With this in place, `DropAncientItemCommand` will be dispatched and processed by the appropriate handler.\n\n#### Queries\n\nThe `CqrsModule` can also be used for handling queries. The `QueryBus` follows the same pattern as the `CommandsBus`. Query handlers should implement the `IQueryHandler` interface and be marked with the `@QueryHandler()` decorator.\n\n#### Setup\n\nFinally, let's look at how to set up the whole CQRS mechanism.\n\n```typescript\n@@filename(heroes-game.module)\nexport const CommandHandlers = [KillDragonHandler, DropAncientItemHandler];\nexport const EventHandlers =  [HeroKilledDragonHandler, HeroFoundItemHandler];\n\n@Module({\n  imports: [CqrsModule],\n  controllers: [HeroesGameController],\n  providers: [\n    HeroesGameService,\n    HeroesGameSagas,\n    ...CommandHandlers,\n    ...EventHandlers,\n    HeroRepository,\n  ]\n})\nexport class HeroesGameModule {}\n```\n\n#### Summary\n\n`CommandBus`, `QueryBus` and `EventBus` are **Observables**. This means that you can easily subscribe to the whole stream and enrich your application with **Event Sourcing**.\n\n#### Example\n\nA working example is available [here](https://github.com/kamilmysliwiec/nest-cqrs-example).\n"
  },
  {
    "path": "content/recipes/crud-generator.md",
    "content": "### CRUD generator\n\nThroughout the life span of a project, when we build new features, we often need to add new resources to our application. These resources typically require multiple, repetitive operations that we have to repeat each time we define a new resource.\n\n#### Introduction\n\nLet's imagine a real-world scenario, where we need to expose CRUD endpoints for 2 entities, let's say **User** and **Product** entities.\nFollowing the best practices, for each entity we would have to perform several operations, as follows:\n\n- Generate a module (`nest g mo`) to keep code organized and establish clear boundaries (grouping related components)\n- Generate a controller (`nest g co`) to define CRUD routes (or queries/mutations for GraphQL applications)\n- Generate a service (`nest g s`) to implement & isolate business logic\n- Generate an entity class/interface to represent the resource data shape\n- Generate Data Transfer Objects (or inputs for GraphQL applications) to define how the data will be sent over the network\n\nThat's a lot of steps!\n\nTo help speed up this repetitive process, [Nest CLI](/cli/overview) provides a generator (schematic) that automatically generates all the boilerplate code to help us avoid doing all of this, and make the developer experience much simpler.\n\n> info **Note** The schematic supports generating **HTTP** controllers, **Microservice** controllers, **GraphQL** resolvers (both code first and schema first), and **WebSocket** Gateways.\n\n#### Generating a new resource\n\nTo create a new resource, simply run the following command in the root directory of your project:\n\n```shell\n$ nest g resource\n```\n\n`nest g resource` command not only generates all the NestJS building blocks (module, service, controller classes) but also an entity class, DTO classes as well as the testing (`.spec`) files.\n\nBelow you can see the generated controller file (for REST API):\n\n```typescript\n@Controller('users')\nexport class UsersController {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Post()\n  create(@Body() createUserDto: CreateUserDto) {\n    return this.usersService.create(createUserDto);\n  }\n\n  @Get()\n  findAll() {\n    return this.usersService.findAll();\n  }\n\n  @Get(':id')\n  findOne(@Param('id') id: string) {\n    return this.usersService.findOne(+id);\n  }\n\n  @Patch(':id')\n  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {\n    return this.usersService.update(+id, updateUserDto);\n  }\n\n  @Delete(':id')\n  remove(@Param('id') id: string) {\n    return this.usersService.remove(+id);\n  }\n}\n```\n\nAlso, it automatically creates placeholders for all the CRUD endpoints (routes for REST APIs, queries and mutations for GraphQL, message subscribes for both Microservices and WebSocket Gateways) - all without having to lift a finger.\n\n> warning **Note** Generated service classes are **not** tied to any specific **ORM (or data source)**. This makes the generator generic enough to meet the needs of any project. By default, all methods will contain placeholders, allowing you to populate it with the data sources specific to your project.\n\nLikewise, if you want to generate resolvers for a GraphQL application, simply select the `GraphQL (code first)` (or `GraphQL (schema first)`) as your transport layer.\n\nIn this case, NestJS will generate a resolver class instead of a REST API controller:\n\n```shell\n$ nest g resource users\n\n> ? What transport layer do you use? GraphQL (code first)\n> ? Would you like to generate CRUD entry points? Yes\n> CREATE src/users/users.module.ts (224 bytes)\n> CREATE src/users/users.resolver.spec.ts (525 bytes)\n> CREATE src/users/users.resolver.ts (1109 bytes)\n> CREATE src/users/users.service.spec.ts (453 bytes)\n> CREATE src/users/users.service.ts (625 bytes)\n> CREATE src/users/dto/create-user.input.ts (195 bytes)\n> CREATE src/users/dto/update-user.input.ts (281 bytes)\n> CREATE src/users/entities/user.entity.ts (187 bytes)\n> UPDATE src/app.module.ts (312 bytes)\n```\n\n> info **Hint** To avoid generating test files, you can pass the `--no-spec` flag, as follows: `nest g resource users --no-spec`\n\nWe can see below, that not only were all boilerplate mutations and queries created, but everything is all tied together. We're utilizing the `UsersService`, `User` Entity, and our DTO's.\n\n```typescript\nimport { Resolver, Query, Mutation, Args, Int } from '@nestjs/graphql';\nimport { UsersService } from './users.service';\nimport { User } from './entities/user.entity';\nimport { CreateUserInput } from './dto/create-user.input';\nimport { UpdateUserInput } from './dto/update-user.input';\n\n@Resolver(() => User)\nexport class UsersResolver {\n  constructor(private readonly usersService: UsersService) {}\n\n  @Mutation(() => User)\n  createUser(@Args('createUserInput') createUserInput: CreateUserInput) {\n    return this.usersService.create(createUserInput);\n  }\n\n  @Query(() => [User], { name: 'users' })\n  findAll() {\n    return this.usersService.findAll();\n  }\n\n  @Query(() => User, { name: 'user' })\n  findOne(@Args('id', { type: () => Int }) id: number) {\n    return this.usersService.findOne(id);\n  }\n\n  @Mutation(() => User)\n  updateUser(@Args('updateUserInput') updateUserInput: UpdateUserInput) {\n    return this.usersService.update(updateUserInput.id, updateUserInput);\n  }\n\n  @Mutation(() => User)\n  removeUser(@Args('id', { type: () => Int }) id: number) {\n    return this.usersService.remove(id);\n  }\n}\n```\n"
  },
  {
    "path": "content/recipes/documentation.md",
    "content": "### 문서화\n\n**Compodoc**은 Angular 애플리케이션을 위한 문서화 도구입니다. Nest와 Angular는 유사한 프로젝트 코드 구조를 공유하므로 **Compodoc**은 Nest 애플리케이션에서도 작동합니다.\n\n#### 설정\n\n기존 Nest 프로젝트 내에서 Compodoc을 설정하는 것은 매우 간단합니다. OS 터미널에서 다음 명령을 사용하여 dev-dependency를 추가합니다.\n\n```bash\n$ npm i -D @compodoc/compodoc\n```\n\n#### 생성\n\n다음 명령을 사용하여 프로젝트 문서를 생성합니다('npx' 지원을 위해서는 npm 6 필요합니다). 더 많은 옵션은 [공식 문서](https://compodoc.app/guides/usage.html)를 참조하세요.\n\n```bash\n$ npx @compodoc/compodoc -p tsconfig.json -s\n```\n\n브라우저를 열고 [http://localhost:8080](http://localhost:8080)으로 이동합니다. 다음과 같은 초기 Nest CLI 프로젝트가 표시됩니다:\n\n<figure><img src=\"/assets/documentation-compodoc-1.jpg\" /></figure>\n<figure><img src=\"/assets/documentation-compodoc-2.jpg\" /></figure>\n\n#### 기여\n\nCompodoc 프로젝트는 [여기](https://github.com/compodoc/compodoc)에서 참여하고 기여할 수 있습니다.\n"
  },
  {
    "path": "content/recipes/hot-reload.md",
    "content": "### Hot Reload\n\nThe highest impact on your application's bootstrapping process is **TypeScript compilation**. Fortunately, with [webpack](https://github.com/webpack/webpack) HMR (Hot-Module Replacement), we don't need to recompile the entire project each time a change occurs. This significantly decreases the amount of time necessary to instantiate your application, and makes iterative development a lot easier.\n\n> warning **Warning** Note that `webpack` won't automatically copy your assets (e.g. `graphql` files) to the `dist` folder. Similarly, `webpack` is not compatible with glob static paths (e.g., the `entities` property in `TypeOrmModule`).\n\n### With CLI\n\nIf you are using the [Nest CLI](https://docs.nestjs.com/cli/overview), the configuration process is pretty straightforward. The CLI wraps `webpack`, which allows use of the `HotModuleReplacementPlugin`.\n\n#### Installation\n\nFirst install the required packages:\n\n```bash\n$ npm i --save-dev webpack-node-externals run-script-webpack-plugin webpack\n```\n\n> info **Hint** If you use **Yarn Berry** (not classic Yarn), install the `webpack-pnp-externals` package instead of the `webpack-node-externals`.\n\n#### Configuration\n\nOnce the installation is complete, create a `webpack-hmr.config.js` file in the root directory of your application.\n\n```typescript\nconst nodeExternals = require('webpack-node-externals');\nconst { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');\n\nmodule.exports = function (options, webpack) {\n  return {\n    ...options,\n    entry: ['webpack/hot/poll?100', options.entry],\n    externals: [\n      nodeExternals({\n        allowlist: ['webpack/hot/poll?100'],\n      }),\n    ],\n    plugins: [\n      ...options.plugins,\n      new webpack.HotModuleReplacementPlugin(),\n      new webpack.WatchIgnorePlugin({\n        paths: [/\\.js$/, /\\.d\\.ts$/],\n      }),\n      new RunScriptWebpackPlugin({ name: options.output.filename }),\n    ],\n  };\n};\n```\n\n> info **Hint** With **Yarn Berry** (not classic Yarn), instead of using the `nodeExternals` in the `externals` configuration property, use the `WebpackPnpExternals` from `webpack-pnp-externals` package: `WebpackPnpExternals({{ '{' }} exclude: ['webpack/hot/poll?100'] {{ '}' }})`.\n\nThis function takes the original object containing the default webpack configuration as a first argument, and the reference to the underlying `webpack` package used by the Nest CLI as the second one. Also, it returns a modified webpack configuration with the `HotModuleReplacementPlugin`, `WatchIgnorePlugin`, and `RunScriptWebpackPlugin` plugins.\n\n#### Hot-Module Replacement\n\nTo enable **HMR**, open the application entry file (`main.ts`) and add the following webpack-related instructions:\n\n```typescript\ndeclare const module: any;\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n\n  if (module.hot) {\n    module.hot.accept();\n    module.hot.dispose(() => app.close());\n  }\n}\nbootstrap();\n```\n\nTo simplify the execution process, add a script to your `package.json` file.\n\n```json\n\"start:dev\": \"nest build --webpack --webpackPath webpack-hmr.config.js --watch\"\n```\n\nNow simply open your command line and run the following command:\n\n```bash\n$ npm run start:dev\n```\n\n### Without CLI\n\nIf you are not using the [Nest CLI](https://docs.nestjs.com/cli/overview), the configuration will be slightly more complex (will require more manual steps).\n\n#### Installation\n\nFirst install the required packages:\n\n```bash\n$ npm i --save-dev webpack webpack-cli webpack-node-externals ts-loader run-script-webpack-plugin\n```\n\n> info **Hint** If you use **Yarn Berry** (not classic Yarn), install the `webpack-pnp-externals` package instead of the `webpack-node-externals`.\n\n#### Configuration\n\nOnce the installation is complete, create a `webpack.config.js` file in the root directory of your application.\n\n```typescript\nconst webpack = require('webpack');\nconst path = require('path');\nconst nodeExternals = require('webpack-node-externals');\nconst { RunScriptWebpackPlugin } = require('run-script-webpack-plugin');\n\nmodule.exports = {\n  entry: ['webpack/hot/poll?100', './src/main.ts'],\n  target: 'node',\n  externals: [\n    nodeExternals({\n      allowlist: ['webpack/hot/poll?100'],\n    }),\n  ],\n  module: {\n    rules: [\n      {\n        test: /.tsx?$/,\n        use: 'ts-loader',\n        exclude: /node_modules/,\n      },\n    ],\n  },\n  mode: 'development',\n  resolve: {\n    extensions: ['.tsx', '.ts', '.js'],\n  },\n  plugins: [\n    new webpack.HotModuleReplacementPlugin(),\n    new RunScriptWebpackPlugin({ name: 'server.js' }),\n  ],\n  output: {\n    path: path.join(__dirname, 'dist'),\n    filename: 'server.js',\n  },\n};\n```\n\n> info **Hint** With **Yarn Berry** (not classic Yarn), instead of using the `nodeExternals` in the `externals` configuration property, use the `WebpackPnpExternals` from `webpack-pnp-externals` package: `WebpackPnpExternals({{ '{' }} exclude: ['webpack/hot/poll?100'] {{ '}' }})`.\n\nThis configuration tells webpack a few essential things about your application: location of the entry file, which directory should be used to hold **compiled** files, and what kind of loader we want to use to compile source files. Generally, you should be able to use this file as-is, even if you don't fully understand all of the options.\n\n#### Hot-Module Replacement\n\nTo enable **HMR**, open the application entry file (`main.ts`) and add the following webpack-related instructions:\n\n```typescript\ndeclare const module: any;\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  await app.listen(3000);\n\n  if (module.hot) {\n    module.hot.accept();\n    module.hot.dispose(() => app.close());\n  }\n}\nbootstrap();\n```\n\nTo simplify the execution process, add a script to your `package.json` file.\n\n```json\n\"start:dev\": \"webpack --config webpack.config.js --watch\"\n```\n\nNow simply open your command line and run the following command:\n\n```bash\n$ npm run start:dev\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/08-webpack).\n\n#### TypeORM\n\nIf you're using `@nestjs/typeorm`, you'll need to add `keepConnectionAlive: true` to your TypeORM configuration.\n"
  },
  {
    "path": "content/recipes/mikroorm.md",
    "content": "### MikroORM\n\nThis recipe is here to help users getting started with MikroORM in Nest. MikroORM is the TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. It is a great alternative to TypeORM and migration from TypeORM should be fairly easy. The complete documentation on MikroORM can be found [here](https://mikro-orm.io/docs).\n\n> info **info** `@mikro-orm/nestjs` is a third party package and is not managed by the NestJS core team. Please, report any issues found with the library in the [appropriate repository](https://github.com/mikro-orm/nestjs).\n\n#### Installation\n\nEasiest way to integrate MikroORM to Nest is via [`@mikro-orm/nestjs` module](https://github.com/mikro-orm/nestjs).\nSimply install it next to Nest, MikroORM and underlying driver:\n\n```bash\n$ npm i @mikro-orm/core @mikro-orm/nestjs @mikro-orm/mysql # for mysql/mariadb\n```\n\nMikroORM also supports `postgres`, `sqlite`, and `mongo`. See the [official docs](https://mikro-orm.io/docs/usage-with-sql/) for all drivers.\n\nOnce the installation process is completed, we can import the `MikroOrmModule` into the root `AppModule`.\n\n```typescript\n@Module({\n  imports: [\n    MikroOrmModule.forRoot({\n      entities: ['./dist/entities'],\n      entitiesTs: ['./src/entities'],\n      dbName: 'my-db-name.sqlite3',\n      type: 'sqlite',\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\nThe `forRoot()` method accepts the same configuration object as `init()` from the MikroORM package. Check [this page](https://mikro-orm.io/docs/configuration) for the complete configuration documentation.\n\nAlternatively we can [configure the CLI](https://mikro-orm.io/docs/installation#setting-up-the-commandline-tool) by creating a configuration file `mikro-orm.config.ts` and then call the `forRoot()` without any arguments. This won't work when you use a build tools that use tree shaking.\n\n```typescript\n@Module({\n  imports: [\n    MikroOrmModule.forRoot(),\n  ],\n  ...\n})\nexport class AppModule {}\n```\n\nAfterward, the `EntityManager` will be available to inject across entire project (without importing any module elsewhere).\n\n```ts\nimport { MikroORM } from '@mikro-orm/core';\n// Import EntityManager from your driver package or `@mikro-orm/knex`\nimport { EntityManager } from '@mikro-orm/mysql';\n\n@Injectable()\nexport class MyService {\n  constructor(\n    private readonly orm: MikroORM,\n    private readonly em: EntityManager,\n  ) {}\n}\n```\n\n> info **info** Notice that the `EntityManager` is imported from the `@mikro-orm/driver` package, where driver is `mysql`, `sqlite`, `postgres` or what driver you are using. In case you have `@mikro-orm/knex` installed as a dependency, you can also import the `EntityManager` from there.\n\n#### Repositories\n\nMikroORM supports the repository design pattern. For every entity we can create a repository. Read the complete documentation on repositories [here](https://mikro-orm.io/docs/repositories). To define which repositories should be registered in the current scope you can use the `forFeature()` method. For example, in this way:\n\n> info **info** You should **not** register your base entities via `forFeature()`, as there are no\n> repositories for those. On the other hand, base entities need to be part of the list in `forRoot()` (or in the ORM config in general).\n\n```typescript\n// photo.module.ts\n@Module({\n  imports: [MikroOrmModule.forFeature([Photo])],\n  providers: [PhotoService],\n  controllers: [PhotoController],\n})\nexport class PhotoModule {}\n```\n\nand import it into the root `AppModule`:\n\n```typescript\n// app.module.ts\n@Module({\n  imports: [MikroOrmModule.forRoot(...), PhotoModule],\n})\nexport class AppModule {}\n```\n\nIn this way we can inject the `PhotoRepository` to the `PhotoService` using the `@InjectRepository()` decorator:\n\n```typescript\n@Injectable()\nexport class PhotoService {\n  constructor(\n    @InjectRepository(Photo)\n    private readonly photoRepository: EntityRepository<Photo>,\n  ) {}\n}\n```\n\n#### Using custom repositories\n\nWhen using custom repositories, we can get around the need for `@InjectRepository()`\ndecorator by naming our repositories the same way as `getRepositoryToken()` method do:\n\n```ts\nexport const getRepositoryToken = <T>(entity: EntityName<T>) =>\n  `${Utils.className(entity)}Repository`;\n```\n\nIn other words, as long as we name the repository same was as the entity is called,\nappending `Repository` suffix, the repository will be registered automatically in\nthe Nest DI container.\n\n```ts\n// `**./author.entity.ts**`\n@Entity()\nexport class Author {\n  // to allow inference in `em.getRepository()`\n  [EntityRepositoryType]?: AuthorRepository;\n}\n\n// `**./author.repository.ts**`\n@Repository(Author)\nexport class AuthorRepository extends EntityRepository<Author> {\n  // your custom methods...\n}\n```\n\nAs the custom repository name is the same as what `getRepositoryToken()` would\nreturn, we do not need the `@InjectRepository()` decorator anymore:\n\n```ts\n@Injectable()\nexport class MyService {\n  constructor(private readonly repo: AuthorRepository) {}\n}\n```\n\n#### Load entities automatically\n\n> info **info** `autoLoadEntities` option was added in v4.1.0\n\nManually adding entities to the entities array of the connection options can be\ntedious. In addition, referencing entities from the root module breaks application\ndomain boundaries and causes leaking implementation details to other parts of the\napplication. To solve this issue, static glob paths can be used.\n\nNote, however, that glob paths are not supported by webpack, so if you are building\nyour application within a monorepo, you won't be able to use them. To address this\nissue, an alternative solution is provided. To automatically load entities, set the\n`autoLoadEntities` property of the configuration object (passed into the `forRoot()`\nmethod) to `true`, as shown below:\n\n```ts\n@Module({\n  imports: [\n    MikroOrmModule.forRoot({\n      ...\n      autoLoadEntities: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nWith that option specified, every entity registered through the `forFeature()`\nmethod will be automatically added to the entities array of the configuration\nobject.\n\n> info **info** Note that entities that aren't registered through the `forFeature()` method, but\n> are only referenced from the entity (via a relationship), won't be included by\n> way of the `autoLoadEntities` setting.\n\n> info **info** Using `autoLoadEntities` also has no effect on the MikroORM CLI - for that we\n> still need CLI config with the full list of entities. On the other hand, we can\n> use globs there, as the CLI won't go thru webpack.\n\n#### Request scoped handlers in queues\n\n> info **info** `@UseRequestContext()` decorator was added in v4.1.0\n\nAs mentioned in the [docs](https://mikro-orm.io/docs/identity-map), we need a clean state for each request. That is handled automatically thanks to the `RequestContext` helper registered via middleware.\n\nBut middlewares are executed only for regular HTTP request handles, what if we need\na request scoped method outside of that? One example of that is queue handlers or\nscheduled tasks.\n\nWe can use the `@UseRequestContext()` decorator. It requires you to first inject the\n`MikroORM` instance to current context, it will be then used to create the context\nfor you. Under the hood, the decorator will register new request context for your\nmethod and execute it inside the context.\n\n```ts\n@Injectable()\nexport class MyService {\n  constructor(private readonly orm: MikroORM) {}\n\n  @UseRequestContext()\n  async doSomething() {\n    // this will be executed in a separate context\n  }\n}\n```\n\n#### Using `AsyncLocalStorage` for request context\n\nBy default, the `domain` api is used in the `RequestContext` helper. Since `@mikro-orm/core@4.0.3`,\nyou can use the new `AsyncLocalStorage` too, if you are on up to date node version:\n\n```typescript\n// create new (global) storage instance\nconst storage = new AsyncLocalStorage<EntityManager>();\n\n@Module({\n  imports: [\n    MikroOrmModule.forRoot({\n      // ...\n      registerRequestContext: false, // disable automatatic middleware\n      context: () => storage.getStore(), // use our AsyncLocalStorage instance\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n\n// register the request context middleware\nconst app = await NestFactory.create(AppModule, { ... });\nconst orm = app.get(MikroORM);\n\napp.use((req, res, next) => {\n  storage.run(orm.em.fork(true, true), next);\n});\n```\n\n#### Testing\n\nThe `@mikro-orm/nestjs` package exposes `getRepositoryToken()` function that returns prepared token based on a given entity to allow mocking the repository.\n\n```typescript\n@Module({\n  providers: [\n    PhotoService,\n    {\n      provide: getRepositoryToken(Photo),\n      useValue: mockedRepository,\n    },\n  ],\n})\nexport class PhotoModule {}\n```\n\n#### Example\n\nA real world example of NestJS with MikroORM can be found [here](https://github.com/mikro-orm/nestjs-realworld-example-app)\n"
  },
  {
    "path": "content/recipes/mongodb.md",
    "content": "### MongoDB (Mongoose)\n\n> **Warning** In this article, you'll learn how to create a `DatabaseModule` based on the **Mongoose** package from scratch using custom components. As a consequence, this solution contains a lot of overhead that you can omit using ready to use and available out-of-the-box dedicated `@nestjs/mongoose` package. To learn more, see [here](/techniques/mongodb).\n\n[Mongoose](https://mongoosejs.com) is the most popular [MongoDB](https://www.mongodb.org/) object modeling tool.\n\n#### Getting started\n\nTo start the adventure with this library we have to install all required dependencies:\n\n```typescript\n$ npm install --save mongoose\n```\n\nThe first step we need to do is to establish the connection with our database using `connect()` function. The `connect()` function returns a `Promise`, and therefore we have to create an [async provider](/fundamentals/async-components).\n\n```typescript\n@@filename(database.providers)\nimport * as mongoose from 'mongoose';\n\nexport const databaseProviders = [\n  {\n    provide: 'DATABASE_CONNECTION',\n    useFactory: (): Promise<typeof mongoose> =>\n      mongoose.connect('mongodb://localhost/nest'),\n  },\n];\n@@switch\nimport * as mongoose from 'mongoose';\n\nexport const databaseProviders = [\n  {\n    provide: 'DATABASE_CONNECTION',\n    useFactory: () => mongoose.connect('mongodb://localhost/nest'),\n  },\n];\n```\n\n> info **Hint** Following best practices, we declared the custom provider in the separated file which has a `*.providers.ts` suffix.\n\nThen, we need to export these providers to make them **accessible** for the rest part of the application.\n\n```typescript\n@@filename(database.module)\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n  providers: [...databaseProviders],\n  exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\nNow we can inject the `Connection` object using `@Inject()` decorator. Each class that would depend on the `Connection` async provider will wait until a `Promise` is resolved.\n\n#### Model injection\n\nWith Mongoose, everything is derived from a [Schema](https://mongoosejs.com/docs/guide.html). Let's define the `CatSchema`:\n\n```typescript\n@@filename(schemas/cat.schema)\nimport * as mongoose from 'mongoose';\n\nexport const CatSchema = new mongoose.Schema({\n  name: String,\n  age: Number,\n  breed: String,\n});\n```\n\nThe `CatsSchema` belongs to the `cats` directory. This directory represents the `CatsModule`.\n\nNow it's time to create a **Model** provider:\n\n```typescript\n@@filename(cats.providers)\nimport { Connection } from 'mongoose';\nimport { CatSchema } from './schemas/cat.schema';\n\nexport const catsProviders = [\n  {\n    provide: 'CAT_MODEL',\n    useFactory: (connection: Connection) => connection.model('Cat', CatSchema),\n    inject: ['DATABASE_CONNECTION'],\n  },\n];\n@@switch\nimport { CatSchema } from './schemas/cat.schema';\n\nexport const catsProviders = [\n  {\n    provide: 'CAT_MODEL',\n    useFactory: (connection) => connection.model('Cat', CatSchema),\n    inject: ['DATABASE_CONNECTION'],\n  },\n];\n```\n\n> warning **Warning** In the real-world applications you should avoid **magic strings**. Both `CAT_MODEL` and `DATABASE_CONNECTION` should be kept in the separated `constants.ts` file.\n\nNow we can inject the `CAT_MODEL` to the `CatsService` using the `@Inject()` decorator:\n\n```typescript\n@@filename(cats.service)\nimport { Model } from 'mongoose';\nimport { Injectable, Inject } from '@nestjs/common';\nimport { Cat } from './interfaces/cat.interface';\nimport { CreateCatDto } from './dto/create-cat.dto';\n\n@Injectable()\nexport class CatsService {\n  constructor(\n    @Inject('CAT_MODEL')\n    private catModel: Model<Cat>,\n  ) {}\n\n  async create(createCatDto: CreateCatDto): Promise<Cat> {\n    const createdCat = new this.catModel(createCatDto);\n    return createdCat.save();\n  }\n\n  async findAll(): Promise<Cat[]> {\n    return this.catModel.find().exec();\n  }\n}\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\n\n@Injectable()\n@Dependencies('CAT_MODEL')\nexport class CatsService {\n  constructor(catModel) {\n    this.catModel = catModel;\n  }\n\n  async create(createCatDto) {\n    const createdCat = new this.catModel(createCatDto);\n    return createdCat.save();\n  }\n\n  async findAll() {\n    return this.catModel.find().exec();\n  }\n}\n```\n\nIn the above example we have used the `Cat` interface. This interface extends the `Document` from the mongoose package:\n\n```typescript\nimport { Document } from 'mongoose';\n\nexport interface Cat extends Document {\n  readonly name: string;\n  readonly age: number;\n  readonly breed: string;\n}\n```\n\nThe database connection is **asynchronous**, but Nest makes this process completely invisible for the end-user. The `CatModel` class is waiting for the db connection, and the `CatsService` is delayed until model is ready to use. The entire application can start when each class is instantiated.\n\nHere is a final `CatsModule`:\n\n```typescript\n@@filename(cats.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\nimport { catsProviders } from './cats.providers';\nimport { DatabaseModule } from '../database/database.module';\n\n@Module({\n  imports: [DatabaseModule],\n  controllers: [CatsController],\n  providers: [\n    CatsService,\n    ...catsProviders,\n  ],\n})\nexport class CatsModule {}\n```\n\n> info **Hint** Do not forget to import the `CatsModule` into the root `AppModule`.\n"
  },
  {
    "path": "content/recipes/nest-commander.md",
    "content": "### Nest Commander\n\nExpanding on the [standalone application](/standalone-applications) docs there's also the [nest-commander](https://jmcdo29.github.io/nest-commander) package for writing command line applications in a structure similar to your typical Nest application.\n\n> info **info** `nest-commander` is a third party package and is not managed by the entirety of the NestJS core team. Please, report any issues found with the library in the [appropriate repository](https://github.com/jmcdo29/nest-commander/issues/new/choose)\n\n#### Installation\n\nJust like any other package, you've got to install it before you can use it.\n\n```bash\n$ npm i nest-commander\n```\n\n#### A Command file\n\n`nest-commander` makes it easy to write new command-line applications with [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) via the `@Command()` decorator for classes and the `@Option()` decorator for methods of that class. Every command file should implement the `CommandRunner` interface and should be decorated with a `@Command()` decorator.\n\nEvery command is seen as an `@Injectable()` by Nest, so your normal Dependency Injection still works as you would expect it to. The only thing to take note of is the interface `CommandRunner`, which should be implemented by each command. The `CommandRunner` interface ensures that all commands have a `run` method that returns a `Promise<void>` and takes in the parameters `string[], Record<string, any>`. The `run` command is where you can kick all of your logic off from, it will take in whatever parameters did not match option flags and pass them in as an array, just in case you are really meaning to work with multiple parameters. As for the options, the `Record<string, any>`, the names of these properties match the `name` property given to the `@Option()` decorators, while their value matches the return of the option handler. If you'd like better type safety, you are welcome to create an interface for your options as well.\n\n#### Running the Command\n\nSimilar to how in a NestJS application we can use the `NestFactory` to create a server for us, and run it using `listen`, the `nest-commander` package exposes a simple to use API to run your server. Import the `CommandFactory` and use the `static` method `run` and pass in the root module of your application. This would probably look like below\n\n```ts\nimport { CommandFactory } from 'nest-commander';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  await CommandFactory.run(AppModule);\n}\n\nbootstrap();\n```\n\nBy default, Nest's logger is disabled when using the `CommandFactory`. It's possible to provide it though, as the second argument to the `run` function. You can either provide a custom NestJS logger, or an array of log levels you want to keep - it might be useful to at least provide `['error']` here, if you only want to print out Nest's error logs.\n\n```ts\nimport { CommandFactory } from 'nest-commander';\nimport { AppModule } from './app.module';\nimport { LogService } './log.service';\n\nasync function bootstrap() {\n  await CommandFactory.run(AppModule, new LogService());\n\n  // or, if you only want to print Nest's warnings and errors\n  await CommandFactory.run(AppModule, ['warn', 'error']);\n}\n\nbootstrap();\n```\n\nAnd that's it. Under the hood, `CommandFactory` will worry about calling `NestFactory` for you and calling `app.close()` when necessary, so you shouldn't need to worry about memory leaks there. If you need to add in some error handling, there's always `try/catch` wrapping the `run` command, or you can chain on some `.catch()` method to the `bootstrap()` call.\n\n#### Testing\n\nSo what's the use of writing a super awesome command line script if you can't test it super easily, right? Fortunately, `nest-commander` has some utilities you can make use of that fits in perfectly with the NestJS ecosystem, it'll feel right at home to any Nestlings out there. Instead of using the `CommandFactory` for building the command in test mode, you can use `CommandTestFactory` and pass in your metadata, very similarly to how `Test.createTestingModule` from `@nestjs/testing` works. In fact, it uses this package under the hood. You're also still able to chain on the `overrideProvider` methods before calling `compile()` so you can swap out DI pieces right in the test.\n\n#### Putting it all together\n\nThe following class would equate to having a CLI command that can take in the subcommand `basic` or be called directly, with `-n`, `-s`, and `-b` (along with their long flags) all being supported and with custom parsers for each option. The `--help` flag is also supported, as is customary with commander.\n\n```ts\nimport { Command, CommandRunner, Option } from 'nest-commander';\nimport { LogService } from './log.service';\n\ninterface BasicCommandOptions {\n  string?: string;\n  boolean?: boolean;\n  number?: number;\n}\n\n@Command({ name: 'basic', description: 'A parameter parse' })\nexport class BasicCommand implements CommandRunner {\n  constructor(private readonly logService: LogService) {}\n\n  async run(\n    passedParam: string[],\n    options?: BasicCommandOptions,\n  ): Promise<void> {\n    if (options?.boolean !== undefined && options?.boolean !== null) {\n      this.runWithBoolean(passedParam, options.boolean);\n    } else if (options?.number) {\n      this.runWithNumber(passedParam, options.number);\n    } else if (options?.string) {\n      this.runWithString(passedParam, options.string);\n    } else {\n      this.runWithNone(passedParam);\n    }\n  }\n\n  @Option({\n    flags: '-n, --number [number]',\n    description: 'A basic number parser',\n  })\n  parseNumber(val: string): number {\n    return Number(val);\n  }\n\n  @Option({\n    flags: '-s, --string [string]',\n    description: 'A string return',\n  })\n  parseString(val: string): string {\n    return val;\n  }\n\n  @Option({\n    flags: '-b, --boolean [boolean]',\n    description: 'A boolean parser',\n  })\n  parseBoolean(val: string): boolean {\n    return JSON.parse(val);\n  }\n\n  runWithString(param: string[], option: string): void {\n    this.logService.log({ param, string: option });\n  }\n\n  runWithNumber(param: string[], option: number): void {\n    this.logService.log({ param, number: option });\n  }\n\n  runWithBoolean(param: string[], option: boolean): void {\n    this.logService.log({ param, boolean: option });\n  }\n\n  runWithNone(param: string[]): void {\n    this.logService.log({ param });\n  }\n}\n```\n\nMake sure the command class is added to a module\n\n```ts\n@Module({\n  providers: [LogService, BasicCommand],\n})\nexport class AppModule {}\n```\n\nAnd now to be able to run the CLI in your main.ts you can do the following\n\n```ts\nasync function bootstrap() {\n  await CommandFactory.run(AppModule);\n}\n\nbootstrap();\n```\n\nAnd just like that, you've got a command line application.\n\n#### More Information\n\nVisit the [nest-commander docs site](https://jmcdo29.github.io/nest-commander) for more information, examples, and API documentation.\n"
  },
  {
    "path": "content/recipes/prisma.md",
    "content": "### Prisma\n\n[Prisma](https://www.prisma.io) is an [open-source](https://github.com/prisma/prisma) ORM for Node.js and TypeScript. It is used as an **alternative** to writing plain SQL, or using another database access tool such as SQL query builders (like [knex.js](https://knexjs.org/)) or ORMs (like [TypeORM](https://typeorm.io/) and [Sequelize](https://sequelize.org/)). Prisma currently supports PostgreSQL, MySQL, SQL Server, SQLite and MongoDB (preview).\n\nWhile Prisma can be used with plain JavaScript, it embraces TypeScript and provides a level to type-safety that goes beyond the guarantees other ORMs in the TypeScript ecosystem. You can find an in-depth comparison of the type-safety guarantees of Prisma and TypeORM [here](https://www.prisma.io/docs/concepts/more/comparisons/prisma-and-typeorm#type-safety).\n\n> info **Note** If you want to get a quick overview of how Prisma works, you can follow the [Quickstart](https://www.prisma.io/docs/getting-started/quickstart) or read the [Introduction](https://www.prisma.io/docs/understand-prisma/introduction) in the [documentation](https://www.prisma.io/docs/). There also are ready-to-run examples for [REST](https://github.com/prisma/prisma-examples/tree/latest/typescript/rest-nestjs) and [GraphQL](https://github.com/prisma/prisma-examples/tree/latest/typescript/graphql-nestjs) in the [`prisma-examples`](https://github.com/prisma/prisma-examples/) repo. \n\n#### Getting started\n\nIn this recipe, you'll learn how to get started with NestJS and Prisma from scratch. You are going to build a sample NestJS application with a REST API that can read and write data in a database.\n\nFor the purpose of this guide, you'll use a [SQLite](https://sqlite.org/) database to save the overhead of setting up a database server. Note that you can still follow this guide, even if you're using PostgreSQL or MySQL – you'll get extra instructions for using these databases at the right places.\n\n> info **Note** If you already have an existing project and consider migrating to Prisma, you can follow the guide for [adding Prisma to an existing project](https://www.prisma.io/docs/getting-started/setup-prisma/add-to-existing-project-typescript-postgres). If you are migrating from TypeORM, you can read the guide [Migrating from TypeORM to Prisma](https://www.prisma.io/docs/guides/migrate-to-prisma/migrate-from-typeorm).\n\n\n#### Create your NestJS project\n\nTo get started, install the NestJS CLI and create your app skeleton with the following commands:\n\n```bash\n$ npm install -g @nestjs/cli\n$ nest new hello-prisma\n```\n\nSee the [First steps](https://docs.nestjs.com/first-steps) page to learn more about the project files created by this command. Note also that you can now run `npm start` to start your application. The REST API running at `http://localhost:3000/` currently serves a single route that's implemented in `src/app.controller.ts`. Over the course of this guide, you'll implement additional routes to store and retrieve data about _users_ and _posts_.\n\n#### Set up Prisma\n\nStart by installing the Prisma CLI as a development dependency in your project:\n\n```bash\n$ cd hello-prisma\n$ npm install prisma --save-dev\n```\n\nIn the following steps, we'll be utilizing the [Prisma CLI](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-cli). As a best practice, it's recommended to invoke the CLI locally by prefixing it with `npx`:\n\n```bash\n$ npx prisma\n```\n\n<details><summary>Expand if you're using Yarn</summary>\n\nIf you're using Yarn, then you can install the Prisma CLI as follows:\n\n```bash\n$ yarn add prisma --dev\n```\n\nOnce installed, you can invoke it by prefixing it with `yarn`:\n\n```bash\n$ yarn prisma\n```\n\n</details>\n\nNow create your initial Prisma setup using the `init` command of the Prisma CLI:\n\n```bash\n$ npx prisma init\n```\n\nThis command creates a new `prisma` directory with the following contents:\n\n- `schema.prisma`: Specifies your database connection and contains the database schema\n- `.env`: A [dotenv](https://github.com/motdotla/dotenv) file, typically used to store your database credentials in a group of environment variables\n\n#### Set the database connection\n\nYour database connection is configured in the `datasource` block in your `schema.prisma` file. By default it's set to `postgresql`, but since you're using a SQLite database in this guide you need to adjust the `provider` field of the `datasource` block to `sqlite`:\n\n```groovy\ndatasource db {\n  provider = \"sqlite\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n```\n\nNow, open up `.env` and adjust the `DATABASE_URL` environment variable to look as follows:\n\n```bash\nDATABASE_URL=\"file:./dev.db\"\n```\n\nSQLite databases are simple files; no server is required to use a SQLite database. So instead of configuring a connection URL with a _host_ and _port_, you can just point it to a local file which in this case is called `dev.db`. This file will be created in the next step.\n\n<details><summary>Expand if you're using PostgreSQL or MySQL</summary>\n\nWith PostgreSQL and MySQL, you need to configure the connection URL to point to the _database server_. You can learn more about the required connection URL format [here](https://www.prisma.io/docs/reference/database-reference/connection-urls).\n\n**PostgreSQL**\n\nIf you're using PostgreSQL, you have to adjust the `schema.prisma` and `.env` files as follows:\n\n**`schema.prisma`**\n\n```groovy\ndatasource db {\n  provider = \"postgresql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n```\n\n**`.env`**\n\n```bash\nDATABASE_URL=\"postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA\"\n```\n\nReplace the placeholders spelled in all uppercase letters with your database credentials. Note that if you're unsure what to provide for the `SCHEMA` placeholder, it's most likely the default value `public`:\n\n```bash\nDATABASE_URL=\"postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public\"\n```\n\nIf you want to learn how to set up a PostgreSQL database, you can follow this guide on [setting up a free PostgreSQL database on Heroku](https://dev.to/prisma/how-to-setup-a-free-postgresql-database-on-heroku-1dc1).\n\n**MySQL**\n\nIf you're using MySQL, you have to adjust the `schema.prisma` and `.env` files as follows:\n\n**`schema.prisma`**\n\n```groovy\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n```\n\n**`.env`**\n\n```bash\nDATABASE_URL=\"mysql://USER:PASSWORD@HOST:PORT/DATABASE\"\n```\n\nReplace the placeholders spelled in all uppercase letters with your database credentials.\n\n</details>\n\n#### Create two database tables with Prisma Migrate\n\nIn this section, you'll create two new tables in your database using [Prisma Migrate](https://www.prisma.io/docs/concepts/components/prisma-migrate). Prisma Migrate generates SQL migration files for your declarative data model definition in the Prisma schema. These migration files are fully customizable so that you can configure any additional features of the underlying database or include additional commands, e.g. for seeding.\n\nAdd the following two models to your `schema.prisma` file:\n\n```groovy\nmodel User {\n  id    Int     @default(autoincrement()) @id\n  email String  @unique\n  name  String?\n  posts Post[]\n}\n\nmodel Post {\n  id        Int      @default(autoincrement()) @id\n  title     String\n  content   String?\n  published Boolean? @default(false)\n  author    User?    @relation(fields: [authorId], references: [id])\n  authorId  Int?\n}\n```\n\nWith your Prisma models in place, you can generate your SQL migration files and run them against the database. Run the following commands in your terminal:\n\n```bash\n$ npx prisma migrate dev --name init\n```\n\nThis `prisma migrate dev` command generates SQL files and directly runs them against the database. In this case, the following migration files was created in the existing `prisma` directory:\n\n```bash\n$ tree prisma\nprisma\n├── dev.db\n├── migrations\n│   └── 20201207100915_init\n│       └── migration.sql\n└── schema.prisma\n```\n\n<details><summary>Expand to view the generated SQL statements</summary>\n\nThe following tables were created in your SQLite database:\n\n```sql\n-- CreateTable\nCREATE TABLE \"User\" (\n    \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n    \"email\" TEXT NOT NULL,\n    \"name\" TEXT\n);\n\n-- CreateTable\nCREATE TABLE \"Post\" (\n    \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n    \"title\" TEXT NOT NULL,\n    \"content\" TEXT,\n    \"published\" BOOLEAN DEFAULT false,\n    \"authorId\" INTEGER,\n\n    FOREIGN KEY (\"authorId\") REFERENCES \"User\"(\"id\") ON DELETE SET NULL ON UPDATE CASCADE\n);\n\n-- CreateIndex\nCREATE UNIQUE INDEX \"User.email_unique\" ON \"User\"(\"email\");\n```\n\n</details>\n\n#### Install and generate Prisma Client\n\nPrisma Client is a type-safe database client that's _generated_ from your Prisma model definition. Because of this approach, Prisma Client can expose [CRUD](https://www.prisma.io/docs/concepts/components/prisma-client/crud) operations that are _tailored_ specifically to your models.\n\nTo install Prisma Client in your project, run the following command in your terminal:\n\n```bash\n$ npm install @prisma/client\n```\n\nNote that during installation, Prisma automatically invokes the `prisma generate` command for you. In the future, you need to run this command after _every_ change to your Prisma models to update your generated Prisma Client.\n\n> info **Note** The `prisma generate` command reads your Prisma schema and updates the generated Prisma Client library inside `node_modules/@prisma/client`.\n\n#### Use Prisma Client in your NestJS services\n\nYou're now able to send database queries with Prisma Client. If you want to learn more about building queries with Prisma Client, check out the [API documentation](https://www.prisma.io/docs/reference/tools-and-interfaces/prisma-client/crud).\n\nWhen setting up your NestJS application, you'll want to abstract away the Prisma Client API for database queries within a service. To get started, you can create a new `PrismaService` that takes care of instantiating `PrismaClient` and connecting to your database.\n\nInside the `src` directory, create a new file called `prisma.service.ts` and add the following code to it:\n\n```typescript\nimport { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';\nimport { PrismaClient } from '@prisma/client';\n\n@Injectable()\nexport class PrismaService extends PrismaClient\n  implements OnModuleInit {\n\n  async onModuleInit() {\n    await this.$connect();\n  }\n\n  async enableShutdownHooks(app: INestApplication) {\n    this.$on('beforeExit', async () => {\n      await app.close();\n    });    \n  }\n}\n```\n\n> info **Note** The `onModuleInit` is optional — if you leave it out, Prisma will connect lazily on its first call to the database. We don't bother with `onModuleDestroy`, since Prisma has its own shutdown hooks where it will destroy the connection. For more info on `enableShutdownHooks`, please see [Issues with `enableShutdownHooks`](recipes/prisma#issues-with-enableshutdownhooks)\n\nNext, you can write services that you can use to make database calls for the `User` and `Post` models from your Prisma schema.\n\nStill inside the `src` directory, create a new file called `user.service.ts` and add the following code to it:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { PrismaService } from './prisma.service';\nimport {\n  User,\n  Prisma\n} from '@prisma/client';\n\n@Injectable()\nexport class UserService {\n  constructor(private prisma: PrismaService) {}\n\n  async user(userWhereUniqueInput: Prisma.UserWhereUniqueInput): Promise<User | null> {\n    return this.prisma.user.findUnique({\n      where: userWhereUniqueInput,\n    });\n  }\n\n  async users(params: {\n    skip?: number;\n    take?: number;\n    cursor?: Prisma.UserWhereUniqueInput;\n    where?: Prisma.UserWhereInput;\n    orderBy?: Prisma.UserOrderByWithRelationInput;\n  }): Promise<User[]> {\n    const { skip, take, cursor, where, orderBy } = params;\n    return this.prisma.user.findMany({\n      skip,\n      take,\n      cursor,\n      where,\n      orderBy,\n    });\n  }\n\n  async createUser(data: Prisma.UserCreateInput): Promise<User> {\n    return this.prisma.user.create({\n      data,\n    });\n  }\n\n  async updateUser(params: {\n    where: Prisma.UserWhereUniqueInput;\n    data: Prisma.UserUpdateInput;\n  }): Promise<User> {\n    const { where, data } = params;\n    return this.prisma.user.update({\n      data,\n      where,\n    });\n  }\n\n  async deleteUser(where: Prisma.UserWhereUniqueInput): Promise<User> {\n    return this.prisma.user.delete({\n      where,\n    });\n  }\n}\n```\n\nNotice how you're using Prisma Client's generated types to ensure that the methods that are exposed by your service are properly typed. You therefore save the boilerplate of typing your models and creating additional interface or DTO files.\n\nNow do the same for the `Post` model.\n\nStill inside the `src` directory, create a new file called `post.service.ts` and add the following code to it:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { PrismaService } from './prisma.service';\nimport {\n  Post,\n  Prisma,\n} from '@prisma/client';\n\n@Injectable()\nexport class PostService {\n  constructor(private prisma: PrismaService) {}\n\n  async post(postWhereUniqueInput: Prisma.PostWhereUniqueInput): Promise<Post | null> {\n    return this.prisma.post.findUnique({\n      where: postWhereUniqueInput,\n    });\n  }\n\n  async posts(params: {\n    skip?: number;\n    take?: number;\n    cursor?: Prisma.PostWhereUniqueInput;\n    where?: Prisma.PostWhereInput;\n    orderBy?: Prisma.PostOrderByWithRelationInput;\n  }): Promise<Post[]> {\n    const { skip, take, cursor, where, orderBy } = params;\n    return this.prisma.post.findMany({\n      skip,\n      take,\n      cursor,\n      where,\n      orderBy,\n    });\n  }\n\n  async createPost(data: Prisma.PostCreateInput): Promise<Post> {\n    return this.prisma.post.create({\n      data,\n    });\n  }\n\n  async updatePost(params: {\n    where: Prisma.PostWhereUniqueInput;\n    data: Prisma.PostUpdateInput;\n  }): Promise<Post> {\n    const { data, where } = params;\n    return this.prisma.post.update({\n      data,\n      where,\n    });\n  }\n\n  async deletePost(where: Prisma.PostWhereUniqueInput): Promise<Post> {\n    return this.prisma.post.delete({\n      where,\n    });\n  }\n}\n```\n\nYour `UserService` and `PostService` currently wrap the CRUD queries that are available in Prisma Client. In a real world application, the service would also be the place to add business logic to your application. For example, you could have a method called `updatePassword` inside the `UserService` that would be responsible for updating the password of a user.\n\n##### Implement your REST API routes in the main app controller\n\nFinally, you'll use the services you created in the previous sections to implement the different routes of your app. For the purpose of this guide, you'll put all your routes into the already existing `AppController` class.\n\nReplace the contents of the `app.controller.ts` file with the following code:\n\n```typescript\nimport {\n  Controller,\n  Get,\n  Param,\n  Post,\n  Body,\n  Put,\n  Delete,\n} from '@nestjs/common';\nimport { UserService } from './user.service';\nimport { PostService } from './post.service';\nimport { User as UserModel, Post as PostModel } from '@prisma/client';\n\n@Controller()\nexport class AppController {\n  constructor(\n    private readonly userService: UserService,\n    private readonly postService: PostService,\n  ) {}\n\n  @Get('post/:id')\n  async getPostById(@Param('id') id: string): Promise<PostModel> {\n    return this.postService.post({ id: Number(id) });\n  }\n\n  @Get('feed')\n  async getPublishedPosts(): Promise<PostModel[]> {\n    return this.postService.posts({\n      where: { published: true },\n    });\n  }\n\n  @Get('filtered-posts/:searchString')\n  async getFilteredPosts(\n    @Param('searchString') searchString: string,\n  ): Promise<PostModel[]> {\n    return this.postService.posts({\n      where: {\n        OR: [\n          {\n            title: { contains: searchString },\n          },\n          {\n            content: { contains: searchString },\n          },\n        ],\n      },\n    });\n  }\n\n  @Post('post')\n  async createDraft(\n    @Body() postData: { title: string; content?: string; authorEmail: string },\n  ): Promise<PostModel> {\n    const { title, content, authorEmail } = postData;\n    return this.postService.createPost({\n      title,\n      content,\n      author: {\n        connect: { email: authorEmail },\n      },\n    });\n  }\n\n  @Post('user')\n  async signupUser(\n    @Body() userData: { name?: string; email: string },\n  ): Promise<UserModel> {\n    return this.userService.createUser(userData);\n  }\n\n  @Put('publish/:id')\n  async publishPost(@Param('id') id: string): Promise<PostModel> {\n    return this.postService.updatePost({\n      where: { id: Number(id) },\n      data: { published: true },\n    });\n  }\n\n  @Delete('post/:id')\n  async deletePost(@Param('id') id: string): Promise<PostModel> {\n    return this.postService.deletePost({ id: Number(id) });\n  }\n}\n```\n\nThis controller implements the following routes:\n\n###### `GET`\n\n- `/post/:id`: Fetch a single post by its `id`\n- `/feed`: Fetch all _published_ posts\n- `/filter-posts/:searchString`: Filter posts by `title` or `content`\n\n###### `POST`\n\n- `/post`: Create a new post\n  - Body:\n    - `title: String` (required): The title of the post\n    - `content: String` (optional): The content of the post\n    - `authorEmail: String` (required): The email of the user that creates the post\n- `/user`: Create a new user\n  - Body:\n    - `email: String` (required): The email address of the user\n    - `name: String` (optional): The name of the user\n\n###### `PUT`\n\n- `/publish/:id`: Publish a post by its `id`\n\n###### `DELETE`\n\n- `/post/:id`: Delete a post by its `id`\n\n#### Issues with `enableShutdownHooks`\n\nPrisma interferes with NestJS `enableShutdownHooks`. Prisma listens for shutdown signals and will call `process.exit()` before your application shutdown hooks fire. To deal with this, you would need to add a listener for Prisma `beforeExit` event.\n\n```typescript\n// main.ts\n...\nimport { PrismaService } from './services/prisma/prisma.service';\n...\nasync function bootstrap() {\n  ...\n  const prismaService: PrismaService = app.get(PrismaService);\n  prismaService.enableShutdownHooks(app)\n  ...\n}\nbootstrap()\n```\n\nYou can [read more](https://github.com/prisma/prisma/issues/2917#issuecomment-708340112) about Prisma handling of shutdown signal, and `beforeExit` event.\n\n#### Summary\n\nIn this recipe, you learned how to use Prisma along with NestJS to implement a REST API. The controller that implements the routes of the API is calling a `PrismaService` which in turn uses Prisma Client to send queries to a database to fulfill the data needs of incoming requests.\n\nIf you want to learn more about using NestJS with Prisma, be sure to check out the following resources:\n\n- [NestJS & Prisma](https://www.prisma.io/nestjs)\n- [Ready-to-run example projects for REST & GraphQL](https://github.com/prisma/prisma-examples/)\n- [Production-ready starter kit](https://github.com/notiz-dev/nestjs-prisma-starter#instructions)\n- [Video: Accessing Databases using NestJS with Prisma (5min)](https://www.youtube.com/watch?v=UlVJ340UEuk&ab_channel=Prisma) by [Marc Stammerjohann](https://github.com/marcjulian)\n"
  },
  {
    "path": "content/recipes/router-module.md",
    "content": "### Router module\n\n> info **Hint** This chapter is only relevant to HTTP-based applications.\n\nIn an HTTP application (for example, REST API), the route path for a handler is determined by concatenating the (optional) prefix declared for the controller (inside the `@Controller` decorator),\nand any path specified in the method's decorator (e.g, `@Get('users')`). You can learn more about that in [this section](/controllers#routing). Additionally,\nyou can define a [global prefix](/faq/global-prefix) for all routes registered in your application, or enable [versioning](/techniques/versioning).\n\nAlso, there are edge-cases when defining a prefix at a module-level (and so for all controllers registered inside that module) may come in handy.\nFor example, imagine a REST application that exposes several different endpoints being used by a specific portion of your application called \"Dashboard\".\nIn such a case, instead of repeating the `/dashboard` prefix within each controller, you could use a utility `RouterModule` module, as follows:\n\n```typescript\n@Module({\n  imports: [\n    DashboardModule,\n    RouterModule.register([\n      {\n        path: 'dashboard',\n        module: DashboardModule,\n      },\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\n> info **Hint** The `RouterModule` class is exported from the `@nestjs/core` package.\n\nIn addition, you can define hierarchical structures. This means each module can have `children` modules.\nThe children modules will inherit their parent's prefix. In the following example, we'll register the `AdminModule` as a parent module of `DashboardModule` and `MetricsModule`.\n\n```typescript\nRouterModule.register([\n  {\n    path: 'admin',\n    module: AdminModule,\n    children: [\n      {\n        path: 'dashboard',\n        module: DashboardModule,\n      },\n      {\n        path: 'metrics',\n        module: MetricsModule,\n      },\n    ],\n  },\n]);\n```\n\n> info **Hint** This feature should be used very carefully, as overusing it can make code difficult to maintain over time.\n\nIn the example above, any controller registered inside the `DashboardModule` will have an extra `/admin/dashboard` prefix (as the module concatenates paths from top to bottom - recursively - parent to children).\nLikewise, each controller defined inside the `MetricsModule` will have an additional module-level prefix `/admin/metrics`.\n"
  },
  {
    "path": "content/recipes/serve-static.md",
    "content": "### Serve Static\n\nIn order to serve static content like a Single Page Application (SPA) we can use the `ServeStaticModule` from the [`@nestjs/serve-static`](https://www.npmjs.com/package/@nestjs/serve-static) package.\n\n#### Installation\n\nFirst we need to install the required package:\n\n```bash\n$ npm install --save @nestjs/serve-static\n```\n\n#### Bootstrap\n\nOnce the installation process is done, we can import the `ServeStaticModule` into the root `AppModule` and configure it by passing in a configuration object to the `forRoot()` method.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { AppService } from './app.service';\nimport { ServeStaticModule } from '@nestjs/serve-static';\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    ServeStaticModule.forRoot({\n      rootPath: join(__dirname, '..', 'client'),\n    }),\n  ],\n  controllers: [AppController],\n  providers: [AppService],\n})\nexport class AppModule {}\n```\n\nWith this in place, build the static website and place its content in the location specified by the `rootPath` property.\n\n#### Configuration\n\n[ServeStaticModule](https://github.com/nestjs/serve-static) can be configured with a variety of options to customize its behavior.\nYou can set the path to render your static app, specify excluded paths, enable or disable setting Cache-Control response header, etc. See the full list of options [here](https://github.com/nestjs/serve-static/blob/master/lib/interfaces/serve-static-options.interface.ts).\n\n> warning **Notice** The default `renderPath` of the Static App is `*` (all paths), and the module will send \"index.html\" files in response.\n> It lets you create Client-Side routing for your SPA. Paths, specified in your controllers will fallback to the server.\n> You can change this behavior setting `serveRoot`, `renderPath` combining them with other options.\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/24-serve-static).\n"
  },
  {
    "path": "content/recipes/sql-sequelize.md",
    "content": "### SQL (Sequelize)\n\n##### This chapter applies only to TypeScript\n\n> **Warning** In this article, you'll learn how to create a `DatabaseModule` based on the **Sequelize** package from scratch using custom components. As a consequence, this technique contains a lot of overhead that you can avoid by using the dedicated, out-of-the-box `@nestjs/sequelize` package. To learn more, see [here](/techniques/database#sequelize-integration).\n\n[Sequelize](https://github.com/sequelize/sequelize) is a popular Object Relational Mapper (ORM) written in a vanilla JavaScript, but there is a [sequelize-typescript](https://github.com/RobinBuschmann/sequelize-typescript) TypeScript wrapper which provides a set of decorators and other extras for the base sequelize.\n\n#### Getting started\n\nTo start the adventure with this library we have to install the following dependencies:\n\n```bash\n$ npm install --save sequelize sequelize-typescript mysql2\n$ npm install --save-dev @types/sequelize\n```\n\nThe first step we need to do is create a **Sequelize** instance with an options object passed into the constructor. Also, we need to add all models (the alternative is to use `modelPaths` property) and `sync()` our database tables.\n\n```typescript\n@@filename(database.providers)\nimport { Sequelize } from 'sequelize-typescript';\nimport { Cat } from '../cats/cat.entity';\n\nexport const databaseProviders = [\n  {\n    provide: 'SEQUELIZE',\n    useFactory: async () => {\n      const sequelize = new Sequelize({\n        dialect: 'mysql',\n        host: 'localhost',\n        port: 3306,\n        username: 'root',\n        password: 'password',\n        database: 'nest',\n      });\n      sequelize.addModels([Cat]);\n      await sequelize.sync();\n      return sequelize;\n    },\n  },\n];\n```\n\n> info **Hint** Following best practices, we declared the custom provider in the separated file which has a `*.providers.ts` suffix.\n\nThen, we need to export these providers to make them **accessible** for the rest part of the application.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n  providers: [...databaseProviders],\n  exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\nNow we can inject the `Sequelize` object using `@Inject()` decorator. Each class that would depend on the `Sequelize` async provider will wait until a `Promise` is resolved.\n\n#### Model injection\n\nIn [Sequelize](https://github.com/sequelize/sequelize) the **Model** defines a table in the database. Instances of this class represent a database row. Firstly, we need at least one entity:\n\n```typescript\n@@filename(cat.entity)\nimport { Table, Column, Model } from 'sequelize-typescript';\n\n@Table\nexport class Cat extends Model {\n  @Column\n  name: string;\n\n  @Column\n  age: number;\n\n  @Column\n  breed: string;\n}\n```\n\nThe `Cat` entity belongs to the `cats` directory. This directory represents the `CatsModule`. Now it's time to create a **Repository** provider:\n\n```typescript\n@@filename(cats.providers)\nimport { Cat } from './cat.entity';\n\nexport const catsProviders = [\n  {\n    provide: 'CATS_REPOSITORY',\n    useValue: Cat,\n  },\n];\n```\n\n> warning **Warning** In the real-world applications you should avoid **magic strings**. Both `CATS_REPOSITORY` and `SEQUELIZE` should be kept in the separated `constants.ts` file.\n\nIn Sequelize, we use static methods to manipulate the data, and thus we created an **alias** here.\n\nNow we can inject the `CATS_REPOSITORY` to the `CatsService` using the `@Inject()` decorator:\n\n```typescript\n@@filename(cats.service)\nimport { Injectable, Inject } from '@nestjs/common';\nimport { CreateCatDto } from './dto/create-cat.dto';\nimport { Cat } from './cat.entity';\n\n@Injectable()\nexport class CatsService {\n  constructor(\n    @Inject('CATS_REPOSITORY')\n    private catsRepository: typeof Cat\n  ) {}\n\n  async findAll(): Promise<Cat[]> {\n    return this.catsRepository.findAll<Cat>();\n  }\n}\n```\n\nThe database connection is **asynchronous**, but Nest makes this process completely invisible for the end-user. The `CATS_REPOSITORY` provider is waiting for the db connection, and the `CatsService` is delayed until repository is ready to use. The entire application can start when each class is instantiated.\n\nHere is a final `CatsModule`:\n\n```typescript\n@@filename(cats.module)\nimport { Module } from '@nestjs/common';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\nimport { catsProviders } from './cats.providers';\nimport { DatabaseModule } from '../database/database.module';\n\n@Module({\n  imports: [DatabaseModule],\n  controllers: [CatsController],\n  providers: [\n    CatsService,\n    ...catsProviders,\n  ],\n})\nexport class CatsModule {}\n```\n\n> info **Hint** Do not forget to import the `CatsModule` into the root `AppModule`.\n"
  },
  {
    "path": "content/recipes/sql-typeorm.md",
    "content": "### SQL (TypeORM)\n\n##### This chapter applies only to TypeScript\n\n> **Warning** In this article, you'll learn how to create a `DatabaseModule` based on the **TypeORM** package from scratch using custom providers mechanism. As a consequence, this solution contains a lot of overhead that you can omit using ready to use and available out-of-the-box dedicated `@nestjs/typeorm` package. To learn more, see [here](/techniques/sql).\n\n[TypeORM](https://github.com/typeorm/typeorm) is definitely the most mature Object Relational Mapper (ORM) available in the node.js world. Since it's written in TypeScript, it works pretty well with the Nest framework.\n\n#### Getting started\n\nTo start the adventure with this library we have to install all required dependencies:\n\n```bash\n$ npm install --save typeorm mysql2\n```\n\nThe first step we need to do is to establish the connection with our database using `createConnection()` function imported from the `typeorm` package. The `createConnection()` function returns a `Promise`, and therefore we have to create an [async provider](/fundamentals/async-components).\n\n```typescript\n@@filename(database.providers)\nimport { createConnection } from 'typeorm';\n\nexport const databaseProviders = [\n  {\n    provide: 'DATABASE_CONNECTION',\n    useFactory: async () => await createConnection({\n      type: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      entities: [\n          __dirname + '/../**/*.entity{.ts,.js}',\n      ],\n      synchronize: true,\n    }),\n  },\n];\n```\n\n> warning **Warning** Setting `synchronize: true` shouldn't be used in production - otherwise you can lose production data.\n\n> info **Hint** Following best practices, we declared the custom provider in the separated file which has a `*.providers.ts` suffix.\n\nThen, we need to export these providers to make them **accessible** for the rest of the application.\n\n```typescript\n@@filename(database.module)\nimport { Module } from '@nestjs/common';\nimport { databaseProviders } from './database.providers';\n\n@Module({\n  providers: [...databaseProviders],\n  exports: [...databaseProviders],\n})\nexport class DatabaseModule {}\n```\n\nNow we can inject the `Connection` object using `@Inject()` decorator. Each class that would depend on the `Connection` async provider will wait until a `Promise` is resolved.\n\n#### Repository pattern\n\nThe [TypeORM](https://github.com/typeorm/typeorm) supports the repository design pattern, thus each entity has its own Repository. These repositories can be obtained from the database connection.\n\nBut firstly, we need at least one entity. We are going to reuse the `Photo` entity from the official documentation.\n\n```typescript\n@@filename(photo.entity)\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class Photo {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column({ length: 500 })\n  name: string;\n\n  @Column('text')\n  description: string;\n\n  @Column()\n  filename: string;\n\n  @Column('int')\n  views: number;\n\n  @Column()\n  isPublished: boolean;\n}\n```\n\nThe `Photo` entity belongs to the `photo` directory. This directory represents the `PhotoModule`. Now, let's create a **Repository** provider:\n\n```typescript\n@@filename(photo.providers)\nimport { Connection } from 'typeorm';\nimport { Photo } from './photo.entity';\n\nexport const photoProviders = [\n  {\n    provide: 'PHOTO_REPOSITORY',\n    useFactory: (connection: Connection) => connection.getRepository(Photo),\n    inject: ['DATABASE_CONNECTION'],\n  },\n];\n```\n\n> warning **Warning** In the real-world applications you should avoid **magic strings**. Both `PHOTO_REPOSITORY` and `DATABASE_CONNECTION` should be kept in the separated `constants.ts` file.\n\nNow we can inject the `Repository<Photo>` to the `PhotoService` using the `@Inject()` decorator:\n\n```typescript\n@@filename(photo.service)\nimport { Injectable, Inject } from '@nestjs/common';\nimport { Repository } from 'typeorm';\nimport { Photo } from './photo.entity';\n\n@Injectable()\nexport class PhotoService {\n  constructor(\n    @Inject('PHOTO_REPOSITORY')\n    private photoRepository: Repository<Photo>,\n  ) {}\n\n  async findAll(): Promise<Photo[]> {\n    return this.photoRepository.find();\n  }\n}\n```\n\nThe database connection is **asynchronous**, but Nest makes this process completely invisible for the end-user. The `PhotoRepository` is waiting for the db connection, and the `PhotoService` is delayed until repository is ready to use. The entire application can start when each class is instantiated.\n\nHere is a final `PhotoModule`:\n\n```typescript\n@@filename(photo.module)\nimport { Module } from '@nestjs/common';\nimport { DatabaseModule } from '../database/database.module';\nimport { photoProviders } from './photo.providers';\nimport { PhotoService } from './photo.service';\n\n@Module({\n  imports: [DatabaseModule],\n  providers: [\n    ...photoProviders,\n    PhotoService,\n  ],\n})\nexport class PhotoModule {}\n```\n\n> info **Hint** Do not forget to import the `PhotoModule` into the root `AppModule`.\n"
  },
  {
    "path": "content/recipes/terminus.md",
    "content": "### Healthchecks (Terminus)\n\nTerminus integration provides you with **readiness/liveness** health checks. Healthchecks are crucial when it comes to complex\nbackend setups. In a nutshell, a health check in the realm of web development usually consists of a special address, for example, `https://my-website.com/health/readiness`.\nA service or a component of your infrastructure (e.g., Kubernetes) checks this address continuously. Depending on the HTTP status code returned from a `GET` request to this address the service will take action when it receives an \"unhealthy\" response.\nSince the definition of \"healthy\" or \"unhealthy\" varies with the type of service you provide, the **Terminus** integration supports you with a\nset of **health indicators**.\n\nAs an example, if your web server uses MongoDB to store its data, it would be vital information whether MongoDB is still up and running.\nIn that case, you can make use of the `MongooseHealthIndicator`. If configured correctly - more on that later - your health check address will return\na healthy or unhealthy HTTP status code, depending on whether MongoDB is running.\n\n#### Getting started\n\nTo get started with `@nestjs/terminus` we need to install the required dependency.\n\n```bash\n$ npm install --save @nestjs/terminus\n```\n\n#### Setting up a Healthcheck\n\nA health check represents a summary of **health indicators**. A health indicator executes a check of a service, whether it is in a healthy or unhealthy state. A health check is positive if all the assigned health indicators are up and running. Because a lot of applications will need similar health indicators, [`@nestjs/terminus`](https://github.com/nestjs/terminus) provides a set of predefined indicators, such as:\n\n- `HttpHealthIndicator`\n- `TypeOrmHealthIndicator`\n- `MongooseHealthIndicator`\n- `SequelizeHealthIndicator`\n- `MicroserviceHealthIndicator`\n- `GRPCHealthIndicator`\n- `MemoryHealthIndicator`\n- `DiskHealthIndicator`\n\nTo get started with our first health check, we need to import the `TerminusModule` into our `AppModule`.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { TerminusModule } from '@nestjs/terminus';\n\n@Module({\n  imports: [TerminusModule]\n})\nexport class AppModule {}\n```\n\nOur healthcheck(s) can be executed using a [controller](/controllers), which can be easily set up using the [Nest CLI](cli/overview).\n\n```bash\n$ nest g controller health\n```\n\n> info **Info** It is highly recommended to enable shutdown hooks in your application. Terminus integration makes use of this lifecycle event if enabled. Read more about shutdown hooks [here](fundamentals/lifecycle-events#application-shutdown).\n\n#### HTTP Healthcheck\n\nOnce we have installed `@nestjs/terminus`, imported our `TerminusModule` and created a new controller, we are ready to create a health check.\n\n```typescript\n@@filename(health.controller)\nimport { Controller, Get } from '@nestjs/common';\nimport { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';\n\n@Controller('health')\nexport class HealthController {\n  constructor(\n    private health: HealthCheckService,\n    private http: HttpHealthIndicator,\n  ) {}\n\n  @Get()\n  @HealthCheck()\n  check() {\n    return this.health.check([\n      () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),\n    ]);\n  }\n}\n@@switch\nimport { Controller, Get } from '@nestjs/common';\nimport { HealthCheckService, HttpHealthIndicator, HealthCheck } from '@nestjs/terminus';\n\n@Controller('health')\n@Dependencies(HealthCheckService, HttpHealthIndicator)\nexport class HealthController {\n  constructor(\n    private health,\n    private http,\n  ) { }\n\n  @Get()\n  @HealthCheck()\n  healthCheck() {\n    return this.health.check([\n      async () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),\n    ])\n  }\n}\n```\n\n> warning **Warning** `HttpHealthIndicator` requires the installation of the `@nestjs/axios` package and the import of `HttpModule`.\n\nOur health check will now send a _GET_-request to the `https://docs.nestjs.com` address. If\nwe get a healthy response from that address, our route at `http://localhost:3000/health` will return\nthe following object with a 200 status code.\n\n```json\n{\n  \"status\": \"ok\",\n  \"info\": {\n    \"nestjs-docs\": {\n      \"status\": \"up\"\n    }\n  },\n  \"error\": {},\n  \"details\": {\n    \"nestjs-docs\": {\n      \"status\": \"up\"\n    }\n  }\n}\n```\n\nThe interface of this response object can be accessed from the `@nestjs/terminus` package with the `HealthCheckResult` interface.\n\n|           |                                                                                                                                                                                             |                                      |\n| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |\n| `status`  | If any health indicator failed the status will be `'error'`. If the NestJS app is shutting down but still accepting HTTP requests, the health check will have the `'shutting_down'` status. | `'error' \\| 'ok' \\| 'shutting_down'` |\n| `info`    | Object containing information of each health indicator which is of status `'up'`, or in other words \"healthy\".                                                                              | `object`                             |\n| `error`   | Object containing information of each health indicator which is of status `'down'`, or in other words \"unhealthy\".                                                                          | `object`                             |\n| `details` | Object containing all information of each health indicator                                                                                                                                  | `object`                             |\n\n#### TypeOrm health indicator\n\nTerminus offers the capability to add database checks to your health check. In order to get started with this health indicator, you\nshould check out the [Database chapter](/techniques/sql) and make sure your database connection within your application is established.\n\n> info **Hint** Behind the scenes the `TypeOrmHealthIndicator` simply executes a `SELECT 1`-SQL command which is often used to verify whether the database still alive. In case you are using an Oracle database it uses `SELECT 1 FROM DUAL`.\n\n```typescript\n@@filename(health.controller)\n@Controller('health')\nexport class HealthController {\n  constructor(\n    private health: HealthCheckService,\n    private db: TypeOrmHealthIndicator,\n  ) {}\n\n  @Get()\n  @HealthCheck()\n  check() {\n    return this.health.check([\n      () => this.db.pingCheck('database'),\n    ]);\n  }\n}\n@@switch\n@Controller('health')\n@Dependencies(HealthCheckService, TypeOrmHealthIndicator)\nexport class HealthController {\n  constructor(\n    private health,\n    private db,\n  ) { }\n\n  @Get()\n  @HealthCheck()\n  healthCheck() {\n    return this.health.check([\n      async () => this.db.pingCheck('database'),\n    ])\n  }\n}\n```\n\nIf your database is reachable, you should now see the following JSON-result when requesting `http://localhost:3000` with a `GET` request:\n\n```json\n{\n  \"status\": \"ok\",\n  \"info\": {\n    \"database\": {\n      \"status\": \"up\"\n    }\n  },\n  \"error\": {},\n  \"details\": {\n    \"database\": {\n      \"status\": \"up\"\n    }\n  }\n}\n```\n\nIn case your app uses [multiple databases](techniques/database#multiple-databases), you need to inject each\nconnection into your `HealthController`. Then, you can simply pass the connection reference to the `TypeOrmHealthIndicator`.\n\n```typescript\n@@filename(health.controller)\n@Controller('health')\nexport class HealthController {\n  constructor(\n    private health: HealthCheckService,\n    private db: TypeOrmHealthIndicator,\n    @InjectConnection('albumsConnection')\n    private albumsConnection: Connection,\n    @InjectConnection()\n    private defaultConnection: Connection,\n  ) {}\n\n  @Get()\n  @HealthCheck()\n  check() {\n    return this.health.check([\n      () => this.db.pingCheck('albums-database', { connection: this.albumsConnection }),\n      () => this.db.pingCheck('database', { connection: this.defaultConnection }),\n    ]);\n  }\n}\n```\n\n#### Custom health indicator\n\nIn some cases, the predefined health indicators provided by `@nestjs/terminus` do not cover all of your health check requirements. In that case, you can set up a custom health indicator according to your needs.\n\nLet's get started by creating a service that will represent our custom indicator. To get a basic understanding of how an indicator is structured, we will create an example `DogHealthIndicator`. This service should have the state `'up'` if every `Dog` object has the type `'goodboy'`. If that condition is not satisfied then it should throw an error.\n\n```typescript\n@@filename(dog.health)\nimport { Injectable } from '@nestjs/common';\nimport { HealthIndicator, HealthIndicatorResult, HealthCheckError } from '@nestjs/terminus';\n\nexport interface Dog {\n  name: string;\n  type: string;\n}\n\n@Injectable()\nexport class DogHealthIndicator extends HealthIndicator {\n  private dogs: Dog[] = [\n    { name: 'Fido', type: 'goodboy' },\n    { name: 'Rex', type: 'badboy' },\n  ];\n\n  async isHealthy(key: string): Promise<HealthIndicatorResult> {\n    const badboys = this.dogs.filter(dog => dog.type === 'badboy');\n    const isHealthy = badboys.length === 0;\n    const result = this.getStatus(key, isHealthy, { badboys: badboys.length });\n\n    if (isHealthy) {\n      return result;\n    }\n    throw new HealthCheckError('Dogcheck failed', result);\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\nimport { HealthCheckError } from '@godaddy/terminus';\n\n@Injectable()\nexport class DogHealthIndicator extends HealthIndicator {\n  dogs = [\n    { name: 'Fido', type: 'goodboy' },\n    { name: 'Rex', type: 'badboy' },\n  ];\n\n  async isHealthy(key) {\n    const badboys = this.dogs.filter(dog => dog.type === 'badboy');\n    const isHealthy = badboys.length === 0;\n    const result = this.getStatus(key, isHealthy, { badboys: badboys.length });\n\n    if (isHealthy) {\n      return result;\n    }\n    throw new HealthCheckError('Dogcheck failed', result);\n  }\n}\n```\n\nThe next thing we need to do is register the health indicator as a provider.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { TerminusModule } from '@nestjs/terminus';\nimport { DogHealthIndicator } from './dog.health';\n\n@Module({\n  controllers: [HealthController],\n  imports: [TerminusModule],\n  providers: [DogHealthIndicator]\n})\nexport class AppModule { }\n```\n\n> info **Hint** In a real-world application the `DogHealthIndicator` should be provided in a separate module, for example, `DogModule`, which then will be imported by the `AppModule`.\n\nThe last required step is to add the now available health indicator in the required health check endpoint. For that, we go back to our `HealthController` and add it to our `check` function.\n\n```typescript\n@@filename(health.controller)\nimport { HealthCheckService } from '@nestjs/terminus';\nimport { Injectable } from '@nestjs/common';\nimport { DogHealthIndicator } from './dog.health';\n\n@Injectable()\nexport class HealthController {\n  constructor(\n    private health: HealthCheckService,\n    private dogHealthIndicator: DogHealthIndicator\n  ) {}\n\n  @Get()\n  @HealthCheck()\n  healthCheck() {\n    return this.health.check([\n      async () => this.dogHealthIndicator.isHealthy('dog'),\n    ])\n  }\n}\n@@switch\nimport { HealthCheckService } from '@nestjs/terminus';\nimport { Injectable } from '@nestjs/common';\nimport { DogHealthIndicator } from './dog.health';\n\n@Injectable()\n@Dependencies(HealthCheckService, DogHealthIndicator)\nexport class HealthController {\n  constructor(\n    private health,\n    private dogHealthIndicator\n  ) {}\n\n  @Get()\n  @HealthCheck()\n  healthCheck() {\n    return this.health.check([\n      async () => this.dogHealthIndicator.isHealthy('dog'),\n    ])\n  }\n}\n```\n\n#### Examples\n\nSome working examples are available [here](https://github.com/nestjs/terminus/tree/master/sample).\n"
  },
  {
    "path": "content/security/authentication.md",
    "content": "### Authentication\n\nAuthentication is an **essential** part of most applications. There are many different approaches and strategies to handle authentication. The approach taken for any project depends on its particular application requirements. This chapter presents several approaches to authentication that can be adapted to a variety of different requirements.\n\n[Passport](https://github.com/jaredhanson/passport) is the most popular node.js authentication library, well-known by the community and successfully used in many production applications. It's straightforward to integrate this library with a **Nest** application using the `@nestjs/passport` module. At a high level, Passport executes a series of steps to:\n\n- Authenticate a user by verifying their \"credentials\" (such as username/password, JSON Web Token ([JWT](https://jwt.io/)), or identity token from an Identity Provider)\n- Manage authenticated state (by issuing a portable token, such as a JWT, or creating an [Express session](https://github.com/expressjs/session))\n- Attach information about the authenticated user to the `Request` object for further use in route handlers\n\nPassport has a rich ecosystem of [strategies](http://www.passportjs.org/) that implement various authentication mechanisms. While simple in concept, the set of Passport strategies you can choose from is large and presents a lot of variety. Passport abstracts these varied steps into a standard pattern, and the `@nestjs/passport` module wraps and standardizes this pattern into familiar Nest constructs.\n\nIn this chapter, we'll implement a complete end-to-end authentication solution for a RESTful API server using these powerful and flexible modules. You can use the concepts described here to implement any Passport strategy to customize your authentication scheme. You can follow the steps in this chapter to build this complete example. You can find a repository with a completed sample app [here](https://github.com/nestjs/nest/tree/master/sample/19-auth-jwt).\n\n#### Authentication requirements\n\nLet's flesh out our requirements. For this use case, clients will start by authenticating with a username and password. Once authenticated, the server will issue a JWT that can be sent as a [bearer token in an authorization header](https://tools.ietf.org/html/rfc6750) on subsequent requests to prove authentication. We'll also create a protected route that is accessible only to requests that contain a valid JWT.\n\nWe'll start with the first requirement: authenticating a user. We'll then extend that by issuing a JWT. Finally, we'll create a protected route that checks for a valid JWT on the request.\n\nFirst we need to install the required packages. Passport provides a strategy called [passport-local](https://github.com/jaredhanson/passport-local) that implements a username/password authentication mechanism, which suits our needs for this portion of our use case.\n\n```bash\n$ npm install --save @nestjs/passport passport passport-local\n$ npm install --save-dev @types/passport-local\n```\n\n> warning **Notice** For **any** Passport strategy you choose, you'll always need the `@nestjs/passport` and `passport` packages. Then, you'll need to install the strategy-specific package (e.g., `passport-jwt` or `passport-local`) that implements the particular authentication strategy you are building. In addition, you can also install the type definitions for any Passport strategy, as shown above with `@types/passport-local`, which provides assistance while writing TypeScript code.\n\n#### Implementing Passport strategies\n\nWe're now ready to implement the authentication feature. We'll start with an overview of the process used for **any** Passport strategy. It's helpful to think of Passport as a mini framework in itself. The elegance of the framework is that it abstracts the authentication process into a few basic steps that you customize based on the strategy you're implementing. It's like a framework because you configure it by supplying customization parameters (as plain JSON objects) and custom code in the form of callback functions, which Passport calls at the appropriate time. The `@nestjs/passport` module wraps this framework in a Nest style package, making it easy to integrate into a Nest application. We'll use `@nestjs/passport` below, but first let's consider how **vanilla Passport** works.\n\nIn vanilla Passport, you configure a strategy by providing two things:\n\n1. A set of options that are specific to that strategy. For example, in a JWT strategy, you might provide a secret to sign tokens.\n2. A \"verify callback\", which is where you tell Passport how to interact with your user store (where you manage user accounts). Here, you verify whether a user exists (and/or create a new user), and whether their credentials are valid. The Passport library expects this callback to return a full user if the validation succeeds, or a null if it fails (failure is defined as either the user is not found, or, in the case of passport-local, the password does not match).\n\nWith `@nestjs/passport`, you configure a Passport strategy by extending the `PassportStrategy` class. You pass the strategy options (item 1 above) by calling the `super()` method in your subclass, optionally passing in an options object. You provide the verify callback (item 2 above) by implementing a `validate()` method in your subclass.\n\nWe'll start by generating an `AuthModule` and in it, an `AuthService`:\n\n```bash\n$ nest g module auth\n$ nest g service auth\n```\n\nAs we implement the `AuthService`, we'll find it useful to encapsulate user operations in a `UsersService`, so let's generate that module and service now:\n\n```bash\n$ nest g module users\n$ nest g service users\n```\n\nReplace the default contents of these generated files as shown below. For our sample app, the `UsersService` simply maintains a hard-coded in-memory list of users, and a find method to retrieve one by username. In a real app, this is where you'd build your user model and persistence layer, using your library of choice (e.g., TypeORM, Sequelize, Mongoose, etc.).\n\n```typescript\n@@filename(users/users.service)\nimport { Injectable } from '@nestjs/common';\n\n// This should be a real class/interface representing a user entity\nexport type User = any;\n\n@Injectable()\nexport class UsersService {\n  private readonly users = [\n    {\n      userId: 1,\n      username: 'john',\n      password: 'changeme',\n    },\n    {\n      userId: 2,\n      username: 'maria',\n      password: 'guess',\n    },\n  ];\n\n  async findOne(username: string): Promise<User | undefined> {\n    return this.users.find(user => user.username === username);\n  }\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class UsersService {\n  constructor() {\n    this.users = [\n      {\n        userId: 1,\n        username: 'john',\n        password: 'changeme',\n      },\n      {\n        userId: 2,\n        username: 'maria',\n        password: 'guess',\n      },\n    ];\n  }\n\n  async findOne(username) {\n    return this.users.find(user => user.username === username);\n  }\n}\n```\n\nIn the `UsersModule`, the only change needed is to add the `UsersService` to the exports array of the `@Module` decorator so that it is visible outside this module (we'll soon use it in our `AuthService`).\n\n```typescript\n@@filename(users/users.module)\nimport { Module } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Module({\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { UsersService } from './users.service';\n\n@Module({\n  providers: [UsersService],\n  exports: [UsersService],\n})\nexport class UsersModule {}\n```\n\nOur `AuthService` has the job of retrieving a user and verifying the password. We create a `validateUser()` method for this purpose. In the code below, we use a convenient ES6 spread operator to strip the password property from the user object before returning it. We'll be calling into the `validateUser()` method from our Passport local strategy in a moment.\n\n```typescript\n@@filename(auth/auth.service)\nimport { Injectable } from '@nestjs/common';\nimport { UsersService } from '../users/users.service';\n\n@Injectable()\nexport class AuthService {\n  constructor(private usersService: UsersService) {}\n\n  async validateUser(username: string, pass: string): Promise<any> {\n    const user = await this.usersService.findOne(username);\n    if (user && user.password === pass) {\n      const { password, ...result } = user;\n      return result;\n    }\n    return null;\n  }\n}\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { UsersService } from '../users/users.service';\n\n@Injectable()\n@Dependencies(UsersService)\nexport class AuthService {\n  constructor(usersService) {\n    this.usersService = usersService;\n  }\n\n  async validateUser(username, pass) {\n    const user = await this.usersService.findOne(username);\n    if (user && user.password === pass) {\n      const { password, ...result } = user;\n      return result;\n    }\n    return null;\n  }\n}\n```\n\n> Warning **Warning** Of course in a real application, you wouldn't store a password in plain text. You'd instead use a library like [bcrypt](https://github.com/kelektiv/node.bcrypt.js#readme), with a salted one-way hash algorithm. With that approach, you'd only store hashed passwords, and then compare the stored password to a hashed version of the **incoming** password, thus never storing or exposing user passwords in plain text. To keep our sample app simple, we violate that absolute mandate and use plain text. **Don't do this in your real app!**\n\nNow, we update our `AuthModule` to import the `UsersModule`.\n\n```typescript\n@@filename(auth/auth.module)\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { UsersModule } from '../users/users.module';\n\n@Module({\n  imports: [UsersModule],\n  providers: [AuthService],\n})\nexport class AuthModule {}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { UsersModule } from '../users/users.module';\n\n@Module({\n  imports: [UsersModule],\n  providers: [AuthService],\n})\nexport class AuthModule {}\n```\n\n#### Implementing Passport local\n\nNow we can implement our Passport **local authentication strategy**. Create a file called `local.strategy.ts` in the `auth` folder, and add the following code:\n\n```typescript\n@@filename(auth/local.strategy)\nimport { Strategy } from 'passport-local';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, UnauthorizedException } from '@nestjs/common';\nimport { AuthService } from './auth.service';\n\n@Injectable()\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n  constructor(private authService: AuthService) {\n    super();\n  }\n\n  async validate(username: string, password: string): Promise<any> {\n    const user = await this.authService.validateUser(username, password);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return user;\n  }\n}\n@@switch\nimport { Strategy } from 'passport-local';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable, UnauthorizedException, Dependencies } from '@nestjs/common';\nimport { AuthService } from './auth.service';\n\n@Injectable()\n@Dependencies(AuthService)\nexport class LocalStrategy extends PassportStrategy(Strategy) {\n  constructor(authService) {\n    super();\n    this.authService = authService;\n  }\n\n  async validate(username, password) {\n    const user = await this.authService.validateUser(username, password);\n    if (!user) {\n      throw new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\nWe've followed the recipe described earlier for all Passport strategies. In our use case with passport-local, there are no configuration options, so our constructor simply calls `super()`, without an options object.\n\n> info **Hint** We can pass an options object in the call to `super()` to customize the behavior of the passport strategy. In this example, the passport-local strategy by default expects properties called `username` and `password` in the request body. Pass an options object to specify different property names, for example: `super({{ '{' }} usernameField: 'email' {{ '}' }})`. See the [Passport documentation](http://www.passportjs.org/docs/configure/) for more information.\n\nWe've also implemented the `validate()` method. For each strategy, Passport will call the verify function (implemented with the `validate()` method in `@nestjs/passport`) using an appropriate strategy-specific set of parameters. For the local-strategy, Passport expects a `validate()` method with the following signature: `validate(username: string, password:string): any`.\n\nMost of the validation work is done in our `AuthService` (with the help of our `UsersService`), so this method is quite straightforward. The `validate()` method for **any** Passport strategy will follow a similar pattern, varying only in the details of how credentials are represented. If a user is found and the credentials are valid, the user is returned so Passport can complete its tasks (e.g., creating the `user` property on the `Request` object), and the request handling pipeline can continue. If it's not found, we throw an exception and let our <a href=\"exception-filters\">exceptions layer</a> handle it.\n\nTypically, the only significant difference in the `validate()` method for each strategy is **how** you determine if a user exists and is valid. For example, in a JWT strategy, depending on requirements, we may evaluate whether the `userId` carried in the decoded token matches a record in our user database, or matches a list of revoked tokens. Hence, this pattern of sub-classing and implementing strategy-specific validation is consistent, elegant and extensible.\n\nWe need to configure our `AuthModule` to use the Passport features we just defined. Update `auth.module.ts` to look like this:\n\n```typescript\n@@filename(auth/auth.module)\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { UsersModule } from '../users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\n\n@Module({\n  imports: [UsersModule, PassportModule],\n  providers: [AuthService, LocalStrategy],\n})\nexport class AuthModule {}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { UsersModule } from '../users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { LocalStrategy } from './local.strategy';\n\n@Module({\n  imports: [UsersModule, PassportModule],\n  providers: [AuthService, LocalStrategy],\n})\nexport class AuthModule {}\n```\n\n#### Built-in Passport Guards\n\nThe <a href=\"guards\">Guards</a> chapter describes the primary function of Guards: to determine whether a request will be handled by the route handler or not. That remains true, and we'll use that standard capability soon. However, in the context of using the `@nestjs/passport` module, we will also introduce a slight new wrinkle that may at first be confusing, so let's discuss that now. Consider that your app can exist in two states, from an authentication perspective:\n\n1. the user/client is **not** logged in (is not authenticated)\n2. the user/client **is** logged in (is authenticated)\n\nIn the first case (user is not logged in), we need to perform two distinct functions:\n\n- Restrict the routes an unauthenticated user can access (i.e., deny access to restricted routes). We'll use Guards in their familiar capacity to handle this function, by placing a Guard on the protected routes. As you may anticipate, we'll be checking for the presence of a valid JWT in this Guard, so we'll work on this Guard later, once we are successfully issuing JWTs.\n\n- Initiate the **authentication step** itself when a previously unauthenticated user attempts to login. This is the step where we'll **issue** a JWT to a valid user. Thinking about this for a moment, we know we'll need to `POST` username/password credentials to initiate authentication, so we'll set up a `POST /auth/login` route to handle that. This raises the question: how exactly do we invoke the passport-local strategy in that route?\n\nThe answer is straightforward: by using another, slightly different type of Guard. The `@nestjs/passport` module provides us with a built-in Guard that does this for us. This Guard invokes the Passport strategy and kicks off the steps described above (retrieving credentials, running the verify function, creating the `user` property, etc).\n\nThe second case enumerated above (logged in user) simply relies on the standard type of Guard we already discussed to enable access to protected routes for logged in users.\n\n<app-banner-courses></app-banner-courses>\n\n#### Login route\n\nWith the strategy in place, we can now implement a bare-bones `/auth/login` route, and apply the built-in Guard to initiate the passport-local flow.\n\nOpen the `app.controller.ts` file and replace its contents with the following:\n\n```typescript\n@@filename(app.controller)\nimport { Controller, Request, Post, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n  @UseGuards(AuthGuard('local'))\n  @Post('auth/login')\n  async login(@Request() req) {\n    return req.user;\n  }\n}\n@@switch\nimport { Controller, Bind, Request, Post, UseGuards } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Controller()\nexport class AppController {\n  @UseGuards(AuthGuard('local'))\n  @Post('auth/login')\n  @Bind(Request())\n  async login(req) {\n    return req.user;\n  }\n}\n```\n\nWith `@UseGuards(AuthGuard('local'))` we are using an `AuthGuard` that `@nestjs/passport` **automatically provisioned** for us when we extended the passport-local strategy. Let's break that down. Our Passport local strategy has a default name of `'local'`. We reference that name in the `@UseGuards()` decorator to associate it with code supplied by the `passport-local` package. This is used to disambiguate which strategy to invoke in case we have multiple Passport strategies in our app (each of which may provision a strategy-specific `AuthGuard`). While we only have one such strategy so far, we'll shortly add a second, so this is needed for disambiguation.\n\nIn order to test our route we'll have our `/auth/login` route simply return the user for now. This also lets us demonstrate another Passport feature: Passport automatically creates a `user` object, based on the value we return from the `validate()` method, and assigns it to the `Request` object as `req.user`. Later, we'll replace this with code to create and return a JWT instead.\n\nSince these are API routes, we'll test them using the commonly available [cURL](https://curl.haxx.se/) library. You can test with any of the `user` objects hard-coded in the `UsersService`.\n\n```bash\n$ # POST to /auth/login\n$ curl -X POST http://localhost:3000/auth/login -d '{\"username\": \"john\", \"password\": \"changeme\"}' -H \"Content-Type: application/json\"\n$ # result -> {\"userId\":1,\"username\":\"john\"}\n```\n\nWhile this works, passing the strategy name directly to the `AuthGuard()` introduces magic strings in the codebase. Instead, we recommend creating your own class, as shown below:\n\n```typescript\n@@filename(auth/local-auth.guard)\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class LocalAuthGuard extends AuthGuard('local') {}\n```\n\nNow, we can update the `/auth/login` route handler and use the `LocalAuthGuard` instead:\n\n```typescript\n@UseGuards(LocalAuthGuard)\n@Post('auth/login')\nasync login(@Request() req) {\n  return req.user;\n}\n```\n\n#### JWT functionality\n\nWe're ready to move on to the JWT portion of our auth system. Let's review and refine our requirements:\n\n- Allow users to authenticate with username/password, returning a JWT for use in subsequent calls to protected API endpoints. We're well on our way to meeting this requirement. To complete it, we'll need to write the code that issues a JWT.\n- Create API routes which are protected based on the presence of a valid JWT as a bearer token\n\nWe'll need to install a couple more packages to support our JWT requirements:\n\n```bash\n$ npm install --save @nestjs/jwt passport-jwt\n$ npm install --save-dev @types/passport-jwt\n```\n\nThe `@nestjs/jwt` package (see more [here](https://github.com/nestjs/jwt)) is a utility package that helps with JWT manipulation. The `passport-jwt` package is the Passport package that implements the JWT strategy and `@types/passport-jwt` provides the TypeScript type definitions.\n\nLet's take a closer look at how a `POST /auth/login` request is handled. We've decorated the route using the built-in `AuthGuard` provided by the passport-local strategy. This means that:\n\n1. The route handler **will only be invoked if the user has been validated**\n2. The `req` parameter will contain a `user` property (populated by Passport during the passport-local authentication flow)\n\nWith this in mind, we can now finally generate a real JWT, and return it in this route. To keep our services cleanly modularized, we'll handle generating the JWT in the `authService`. Open the `auth.service.ts` file in the `auth` folder, and add the `login()` method, and import the `JwtService` as shown:\n\n```typescript\n@@filename(auth/auth.service)\nimport { Injectable } from '@nestjs/common';\nimport { UsersService } from '../users/users.service';\nimport { JwtService } from '@nestjs/jwt';\n\n@Injectable()\nexport class AuthService {\n  constructor(\n    private usersService: UsersService,\n    private jwtService: JwtService\n  ) {}\n\n  async validateUser(username: string, pass: string): Promise<any> {\n    const user = await this.usersService.findOne(username);\n    if (user && user.password === pass) {\n      const { password, ...result } = user;\n      return result;\n    }\n    return null;\n  }\n\n  async login(user: any) {\n    const payload = { username: user.username, sub: user.userId };\n    return {\n      access_token: this.jwtService.sign(payload),\n    };\n  }\n}\n\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { UsersService } from '../users/users.service';\nimport { JwtService } from '@nestjs/jwt';\n\n@Dependencies(UsersService, JwtService)\n@Injectable()\nexport class AuthService {\n  constructor(usersService, jwtService) {\n    this.usersService = usersService;\n    this.jwtService = jwtService;\n  }\n\n  async validateUser(username, pass) {\n    const user = await this.usersService.findOne(username);\n    if (user && user.password === pass) {\n      const { password, ...result } = user;\n      return result;\n    }\n    return null;\n  }\n\n  async login(user) {\n    const payload = { username: user.username, sub: user.userId };\n    return {\n      access_token: this.jwtService.sign(payload),\n    };\n  }\n}\n```\n\nWe're using the `@nestjs/jwt` library, which supplies a `sign()` function to generate our JWT from a subset of the `user` object properties, which we then return as a simple object with a single `access_token` property. Note: we choose a property name of `sub` to hold our `userId` value to be consistent with JWT standards. Don't forget to inject the JwtService provider into the `AuthService`.\n\nWe now need to update the `AuthModule` to import the new dependencies and configure the `JwtModule`.\n\nFirst, create `constants.ts` in the `auth` folder, and add the following code:\n\n```typescript\n@@filename(auth/constants)\nexport const jwtConstants = {\n  secret: 'secretKey',\n};\n@@switch\nexport const jwtConstants = {\n  secret: 'secretKey',\n};\n```\n\nWe'll use this to share our key between the JWT signing and verifying steps.\n\n> Warning **Warning** **Do not expose this key publicly**. We have done so here to make it clear what the code is doing, but in a production system **you must protect this key** using appropriate measures such as a secrets vault, environment variable, or configuration service.\n\nNow, open `auth.module.ts` in the `auth` folder and update it to look like this:\n\n```typescript\n@@filename(auth/auth.module)\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { LocalStrategy } from './local.strategy';\nimport { UsersModule } from '../users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\n\n@Module({\n  imports: [\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n  providers: [AuthService, LocalStrategy],\n  exports: [AuthService],\n})\nexport class AuthModule {}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { LocalStrategy } from './local.strategy';\nimport { UsersModule } from '../users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\n\n@Module({\n  imports: [\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n  providers: [AuthService, LocalStrategy],\n  exports: [AuthService],\n})\nexport class AuthModule {}\n```\n\nWe configure the `JwtModule` using `register()`, passing in a configuration object. See [here](https://github.com/nestjs/jwt/blob/master/README.md) for more on the Nest `JwtModule` and [here](https://github.com/auth0/node-jsonwebtoken#usage) for more details on the available configuration options.\n\nNow we can update the `/auth/login` route to return a JWT.\n\n```typescript\n@@filename(app.controller)\nimport { Controller, Request, Post, UseGuards } from '@nestjs/common';\nimport { LocalAuthGuard } from './auth/local-auth.guard';\nimport { AuthService } from './auth/auth.service';\n\n@Controller()\nexport class AppController {\n  constructor(private authService: AuthService) {}\n\n  @UseGuards(LocalAuthGuard)\n  @Post('auth/login')\n  async login(@Request() req) {\n    return this.authService.login(req.user);\n  }\n}\n@@switch\nimport { Controller, Bind, Request, Post, UseGuards } from '@nestjs/common';\nimport { LocalAuthGuard } from './auth/local-auth.guard';\nimport { AuthService } from './auth/auth.service';\n\n@Controller()\nexport class AppController {\n  constructor(private authService: AuthService) {}\n\n  @UseGuards(LocalAuthGuard)\n  @Post('auth/login')\n  @Bind(Request())\n  async login(req) {\n    return this.authService.login(req.user);\n  }\n}\n```\n\nLet's go ahead and test our routes using cURL again. You can test with any of the `user` objects hard-coded in the `UsersService`.\n\n```bash\n$ # POST to /auth/login\n$ curl -X POST http://localhost:3000/auth/login -d '{\"username\": \"john\", \"password\": \"changeme\"}' -H \"Content-Type: application/json\"\n$ # result -> {\"access_token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...\"}\n$ # Note: above JWT truncated\n```\n\n#### Implementing Passport JWT\n\nWe can now address our final requirement: protecting endpoints by requiring a valid JWT be present on the request. Passport can help us here too. It provides the [passport-jwt](https://github.com/mikenicholson/passport-jwt) strategy for securing RESTful endpoints with JSON Web Tokens. Start by creating a file called `jwt.strategy.ts` in the `auth` folder, and add the following code:\n\n```typescript\n@@filename(auth/jwt.strategy)\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable } from '@nestjs/common';\nimport { jwtConstants } from './constants';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: jwtConstants.secret,\n    });\n  }\n\n  async validate(payload: any) {\n    return { userId: payload.sub, username: payload.username };\n  }\n}\n@@switch\nimport { ExtractJwt, Strategy } from 'passport-jwt';\nimport { PassportStrategy } from '@nestjs/passport';\nimport { Injectable } from '@nestjs/common';\nimport { jwtConstants } from './constants';\n\n@Injectable()\nexport class JwtStrategy extends PassportStrategy(Strategy) {\n  constructor() {\n    super({\n      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),\n      ignoreExpiration: false,\n      secretOrKey: jwtConstants.secret,\n    });\n  }\n\n  async validate(payload) {\n    return { userId: payload.sub, username: payload.username };\n  }\n}\n```\n\nWith our `JwtStrategy`, we've followed the same recipe described earlier for all Passport strategies. This strategy requires some initialization, so we do that by passing in an options object in the `super()` call. You can read more about the available options [here](https://github.com/mikenicholson/passport-jwt#configure-strategy). In our case, these options are:\n\n- `jwtFromRequest`: supplies the method by which the JWT will be extracted from the `Request`. We will use the standard approach of supplying a bearer token in the Authorization header of our API requests. Other options are described [here](https://github.com/mikenicholson/passport-jwt#extracting-the-jwt-from-the-request).\n- `ignoreExpiration`: just to be explicit, we choose the default `false` setting, which delegates the responsibility of ensuring that a JWT has not expired to the Passport module. This means that if our route is supplied with an expired JWT, the request will be denied and a `401 Unauthorized` response sent. Passport conveniently handles this automatically for us.\n- `secretOrKey`: we are using the expedient option of supplying a symmetric secret for signing the token. Other options, such as a PEM-encoded public key, may be more appropriate for production apps (see [here](https://github.com/mikenicholson/passport-jwt#configure-strategy) for more information). In any case, as cautioned earlier, **do not expose this secret publicly**.\n\nThe `validate()` method deserves some discussion. For the jwt-strategy, Passport first verifies the JWT's signature and decodes the JSON. It then invokes our `validate()` method passing the decoded JSON as its single parameter. Based on the way JWT signing works, **we're guaranteed that we're receiving a valid token** that we have previously signed and issued to a valid user.\n\nAs a result of all this, our response to the `validate()` callback is trivial: we simply return an object containing the `userId` and `username` properties. Recall again that Passport will build a `user` object based on the return value of our `validate()` method, and attach it as a property on the `Request` object.\n\nIt's also worth pointing out that this approach leaves us room ('hooks' as it were) to inject other business logic into the process. For example, we could do a database lookup in our `validate()` method to extract more information about the user, resulting in a more enriched `user` object being available in our `Request`. This is also the place we may decide to do further token validation, such as looking up the `userId` in a list of revoked tokens, enabling us to perform token revocation. The model we've implemented here in our sample code is a fast, \"stateless JWT\" model, where each API call is immediately authorized based on the presence of a valid JWT, and a small bit of information about the requester (its `userId` and `username`) is available in our Request pipeline.\n\nAdd the new `JwtStrategy` as a provider in the `AuthModule`:\n\n```typescript\n@@filename(auth/auth.module)\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtStrategy } from './jwt.strategy';\nimport { UsersModule } from '../users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\n\n@Module({\n  imports: [\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n  providers: [AuthService, LocalStrategy, JwtStrategy],\n  exports: [AuthService],\n})\nexport class AuthModule {}\n@@switch\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { LocalStrategy } from './local.strategy';\nimport { JwtStrategy } from './jwt.strategy';\nimport { UsersModule } from '../users/users.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt';\nimport { jwtConstants } from './constants';\n\n@Module({\n  imports: [\n    UsersModule,\n    PassportModule,\n    JwtModule.register({\n      secret: jwtConstants.secret,\n      signOptions: { expiresIn: '60s' },\n    }),\n  ],\n  providers: [AuthService, LocalStrategy, JwtStrategy],\n  exports: [AuthService],\n})\nexport class AuthModule {}\n```\n\nBy importing the same secret used when we signed the JWT, we ensure that the **verify** phase performed by Passport, and the **sign** phase performed in our AuthService, use a common secret.\n\nFinally, we define the `JwtAuthGuard` class which extends the built-in `AuthGuard`:\n\n```typescript\n@@filename(auth/jwt-auth.guard)\nimport { Injectable } from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {}\n```\n\n#### Implement protected route and JWT strategy guards\n\nWe can now implement our protected route and its associated Guard.\n\nOpen the `app.controller.ts` file and update it as shown below:\n\n```typescript\n@@filename(app.controller)\nimport { Controller, Get, Request, Post, UseGuards } from '@nestjs/common';\nimport { JwtAuthGuard } from './auth/jwt-auth.guard';\nimport { LocalAuthGuard } from './auth/local-auth.guard';\nimport { AuthService } from './auth/auth.service';\n\n@Controller()\nexport class AppController {\n  constructor(private authService: AuthService) {}\n\n  @UseGuards(LocalAuthGuard)\n  @Post('auth/login')\n  async login(@Request() req) {\n    return this.authService.login(req.user);\n  }\n\n  @UseGuards(JwtAuthGuard)\n  @Get('profile')\n  getProfile(@Request() req) {\n    return req.user;\n  }\n}\n@@switch\nimport { Controller, Dependencies, Bind, Get, Request, Post, UseGuards } from '@nestjs/common';\nimport { JwtAuthGuard } from './auth/jwt-auth.guard';\nimport { LocalAuthGuard } from './auth/local-auth.guard';\nimport { AuthService } from './auth/auth.service';\n\n@Dependencies(AuthService)\n@Controller()\nexport class AppController {\n  constructor(authService) {\n    this.authService = authService;\n  }\n\n  @UseGuards(LocalAuthGuard)\n  @Post('auth/login')\n  @Bind(Request())\n  async login(req) {\n    return this.authService.login(req.user);\n  }\n\n  @UseGuards(JwtAuthGuard)\n  @Get('profile')\n  @Bind(Request())\n  getProfile(req) {\n    return req.user;\n  }\n}\n```\n\nOnce again, we're applying the `AuthGuard` that the `@nestjs/passport` module has automatically provisioned for us when we configured the passport-jwt module. This Guard is referenced by its default name, `jwt`. When our `GET /profile` route is hit, the Guard will automatically invoke our passport-jwt custom configured logic, validating the JWT, and assigning the `user` property to the `Request` object.\n\nEnsure the app is running, and test the routes using `cURL`.\n\n```bash\n$ # GET /profile\n$ curl http://localhost:3000/profile\n$ # result -> {\"statusCode\":401,\"error\":\"Unauthorized\"}\n\n$ # POST /auth/login\n$ curl -X POST http://localhost:3000/auth/login -d '{\"username\": \"john\", \"password\": \"changeme\"}' -H \"Content-Type: application/json\"\n$ # result -> {\"access_token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm... }\n\n$ # GET /profile using access_token returned from previous step as bearer code\n$ curl http://localhost:3000/profile -H \"Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2Vybm...\"\n$ # result -> {\"userId\":1,\"username\":\"john\"}\n```\n\nNote that in the `AuthModule`, we configured the JWT to have an expiration of `60 seconds`. This is probably too short an expiration, and dealing with the details of token expiration and refresh is beyond the scope of this article. However, we chose that to demonstrate an important quality of JWTs and the passport-jwt strategy. If you wait 60 seconds after authenticating before attempting a `GET /profile` request, you'll receive a `401 Unauthorized` response. This is because Passport automatically checks the JWT for its expiration time, saving you the trouble of doing so in your application.\n\nWe've now completed our JWT authentication implementation. JavaScript clients (such as Angular/React/Vue), and other JavaScript apps, can now authenticate and communicate securely with our API Server. \n\n#### Example\n\nYou can find a complete version of the code in this chapter [here](https://github.com/nestjs/nest/tree/master/sample/19-auth-jwt).\n\n#### Extending guards\n\nIn most cases, using a provided `AuthGuard` class is sufficient. However, there might be use-cases when you would like to simply extend the default error handling or authentication logic. For this, you can extend the built-in class and override methods within a sub-class.\n\n```typescript\nimport {\n  ExecutionContext,\n  Injectable,\n  UnauthorizedException,\n} from '@nestjs/common';\nimport { AuthGuard } from '@nestjs/passport';\n\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  canActivate(context: ExecutionContext) {\n    // Add your custom authentication logic here\n    // for example, call super.logIn(request) to establish a session.\n    return super.canActivate(context);\n  }\n\n  handleRequest(err, user, info) {\n    // You can throw an exception based on either \"info\" or \"err\" arguments\n    if (err || !user) {\n      throw err || new UnauthorizedException();\n    }\n    return user;\n  }\n}\n```\n\nIn addition to extending the default error handling and authentication logic, we can allow authentication to go through a chain of strategies. The first strategy to succeed, redirect, or error will halt the chain.  Authentication failures will proceed through each strategy in series, ultimately failing if all strategies fail.\n\n```typescript\nexport class JwtAuthGuard extends AuthGuard(['strategy_jwt_1', 'strategy_jwt_2', '...']) { ... }\n```\n\n#### Enable authentication globally\n\nIf the vast majority of your endpoints should be protected by default, you can register the authentication guard as a [global guard](/guards#binding-guards) and instead of using `@UseGuards()` decorator on top of each controller, you could simply flag which routes should be public.\n\nFirst, register the `JwtAuthGuard` as a global guard using the following construction (in any module):\n\n```typescript\nproviders: [\n  {\n    provide: APP_GUARD,\n    useClass: JwtAuthGuard,\n  },\n],\n```\n\nWith this in place, Nest will automatically bind `JwtAuthGuard` to all endpoints.\n\nNow we must provide a mechanism for declaring routes as public. For this, we can create a custom decorator using the `SetMetadata` decorator factory function.\n\n```typescript\nimport { SetMetadata } from '@nestjs/common';\n\nexport const IS_PUBLIC_KEY = 'isPublic';\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true);\n```\n\nIn the file above, we exported two constants. One being our metadata key named `IS_PUBLIC_KEY`, and the other being our new decorator itself that we’re going to call `Public` (you can alternatively name it `SkipAuth` or `AllowAnon`, whatever fits your project).\n\nNow that we have a custom `@Public()` decorator, we can use it to decorate any method, as follows:\n\n```typescript\n@Public()\n@Get()\nfindAll() {\n  return [];\n}\n```\n\nLastly, we need the `JwtAuthGuard` to return `true` when the `\"isPublic\"` metadata is found. For this, we'll use the `Reflector` class (read more [here](/guards#putting-it-all-together)).\n\n```typescript\n@Injectable()\nexport class JwtAuthGuard extends AuthGuard('jwt') {\n  constructor(private reflector: Reflector) {\n    super();\n  }\n\n  canActivate(context: ExecutionContext) {\n    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n    if (isPublic) {\n      return true;\n    }\n    return super.canActivate(context);\n  }\n}\n```\n\n#### Request-scoped strategies\n\nThe passport API is based on registering strategies to the global instance of the library. Therefore strategies are not designed to have request-dependent options or to be dynamically instantiated per request (read more about the [request-scoped](/fundamentals/injection-scopes) providers). When you configure your strategy to be request-scoped, Nest will never instantiate it since it's not tied to any specific route. There is no physical way to determine which \"request-scoped\" strategies should be executed per request.\n\nHowever, there are ways to dynamically resolve request-scoped providers within the strategy. For this, we leverage the [module reference](/fundamentals/module-ref) feature.\n\nFirst, open the `local.strategy.ts` file and inject the `ModuleRef` in the normal way:\n\n```typescript\nconstructor(private moduleRef: ModuleRef) {\n  super({\n    passReqToCallback: true,\n  });\n}\n```\n\n> info **Hint** The `ModuleRef` class is imported from the `@nestjs/core` package.\n\nBe sure to set the `passReqToCallback` configuration property to `true`, as shown above.\n\nIn the next step, the request instance will be used to obtain the current context identifier, instead of generating a new one (read more about request context [here](/fundamentals/module-ref#getting-current-sub-tree)).\n\nNow, inside the `validate()` method of the `LocalStrategy` class, use the `getByRequest()` method of the `ContextIdFactory` class to create a context id based on the request object, and pass this to the `resolve()` call:\n\n```typescript\nasync validate(\n  request: Request,\n  username: string,\n  password: string,\n) {\n  const contextId = ContextIdFactory.getByRequest(request);\n  // \"AuthService\" is a request-scoped provider\n  const authService = await this.moduleRef.resolve(AuthService, contextId);\n  ...\n}\n```\n\nIn the example above, the `resolve()` method will asynchronously return the request-scoped instance of the `AuthService` provider (we assumed that `AuthService` is marked as a request-scoped provider).\n\n#### Customize Passport\n\nAny standard Passport customization options can be passed the same way, using the `register()` method. The available options depend on the strategy being implemented. For example:\n\n```typescript\nPassportModule.register({ session: true });\n```\n\nYou can also pass strategies an options object in their constructors to configure them.\nFor the local strategy you can pass e.g.:\n\n```typescript\nconstructor(private authService: AuthService) {\n  super({\n    usernameField: 'email',\n    passwordField: 'password',\n  });\n}\n```\n\nTake a look at the official [Passport Website](http://www.passportjs.org/docs/oauth/) for property names.\n\n#### Named strategies\n\nWhen implementing a strategy, you can provide a name for it by passing a second argument to the `PassportStrategy` function. If you don't do this, each strategy will have a default name (e.g., 'jwt' for jwt-strategy):\n\n```typescript\nexport class JwtStrategy extends PassportStrategy(Strategy, 'myjwt')\n```\n\nThen, you refer to this via a decorator like `@UseGuards(AuthGuard('myjwt'))`.\n\n#### GraphQL\n\nIn order to use an AuthGuard with [GraphQL](https://docs.nestjs.com/graphql/quick-start), extend the built-in AuthGuard class and override the getRequest() method.\n\n```typescript\n@Injectable()\nexport class GqlAuthGuard extends AuthGuard('jwt') {\n  getRequest(context: ExecutionContext) {\n    const ctx = GqlExecutionContext.create(context);\n    return ctx.getContext().req;\n  }\n}\n```\n\nTo get the current authenticated user in your graphql resolver, you can define a `@CurrentUser()` decorator:\n\n```typescript\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\nimport { GqlExecutionContext } from '@nestjs/graphql';\n\nexport const CurrentUser = createParamDecorator(\n  (data: unknown, context: ExecutionContext) => {\n    const ctx = GqlExecutionContext.create(context);\n    return ctx.getContext().req.user;\n  },\n);\n```\n\nTo use above decorator in your resolver, be sure to include it as a parameter of your query or mutation:\n\n```typescript\n@Query(returns => User)\n@UseGuards(GqlAuthGuard)\nwhoAmI(@CurrentUser() user: User) {\n  return this.usersService.findById(user.id);\n}\n```\n"
  },
  {
    "path": "content/security/authorization.md",
    "content": "### Authorization\n\n**Authorization** refers to the process that determines what a user is able to do. For example, an administrative user is allowed to create, edit, and delete posts. A non-administrative user is only authorized to read the posts.\n\nAuthorization is orthogonal and independent from authentication. However, authorization requires an authentication mechanism.\n\nThere are many different approaches and strategies to handle authorization. The approach taken for any project depends on its particular application requirements. This chapter presents a few approaches to authorization that can be adapted to a variety of different requirements.\n\n#### Basic RBAC implementation\n\nRole-based access control (**RBAC**) is a policy-neutral access-control mechanism defined around roles and privileges. In this section, we'll demonstrate how to implement a very basic RBAC mechanism using Nest [guards](/guards).\n\nFirst, let's create a `Role` enum representing roles in the system:\n\n```typescript\n@@filename(role.enum)\nexport enum Role {\n  User = 'user',\n  Admin = 'admin',\n}\n```\n\n> info **Hint** In more sophisticated systems, you may store roles within a database, or pull them from the external authentication provider.\n\nWith this in place, we can create a `@Roles()` decorator. This decorator allows specifying what roles are required to access specific resources.\n\n```typescript\n@@filename(roles.decorator)\nimport { SetMetadata } from '@nestjs/common';\nimport { Role } from '../enums/role.enum';\n\nexport const ROLES_KEY = 'roles';\nexport const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);\n@@switch\nimport { SetMetadata } from '@nestjs/common';\n\nexport const ROLES_KEY = 'roles';\nexport const Roles = (...roles) => SetMetadata(ROLES_KEY, roles);\n```\n\nNow that we have a custom `@Roles()` decorator, we can use it to decorate any route handler.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@Roles(Role.Admin)\ncreate(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@Roles(Role.Admin)\n@Bind(Body())\ncreate(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\nFinally, we create a `RolesGuard` class which will compare the roles assigned to the current user to the actual roles required by the current route being processed. In order to access the route's role(s) (custom metadata), we'll use the `Reflector` helper class, which is provided out of the box by the framework and exposed from the `@nestjs/core` package.\n\n```typescript\n@@filename(roles.guard)\nimport { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\nexport class RolesGuard implements CanActivate {\n  constructor(private reflector: Reflector) {}\n\n  canActivate(context: ExecutionContext): boolean {\n    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n    if (!requiredRoles) {\n      return true;\n    }\n    const { user } = context.switchToHttp().getRequest();\n    return requiredRoles.some((role) => user.roles?.includes(role));\n  }\n}\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { Reflector } from '@nestjs/core';\n\n@Injectable()\n@Dependencies(Reflector)\nexport class RolesGuard {\n  constructor(reflector) {\n    this.reflector = reflector;\n  }\n\n  canActivate(context) {\n    const requiredRoles = this.reflector.getAllAndOverride(ROLES_KEY, [\n      context.getHandler(),\n      context.getClass(),\n    ]);\n    if (!requiredRoles) {\n      return true;\n    }\n    const { user } = context.switchToHttp().getRequest();\n    return requiredRoles.some((role) => user.roles.includes(role));\n  }\n}\n```\n\n> info **Hint** Refer to the [Reflection and metadata](/fundamentals/execution-context#reflection-and-metadata) section of the Execution context chapter for more details on utilizing `Reflector` in a context-sensitive way.\n\n> warning **Notice** This example is named \"**basic**\" as we only check for the presence of roles on the route handler level. In real-world applications, you may have endpoints/handlers that involve several operations, in which each of them requires a specific set of permissions. In this case, you'll have to provide a mechanism to check roles somewhere within your business-logic, making it somewhat harder to maintain as there will be no centralized place that associates permissions with specific actions.\n\nIn this example, we assumed that `request.user` contains the user instance and allowed roles (under the `roles` property). In your app, you will probably make that association in your custom **authentication guard** - see [authentication](/security/authentication) chapter for more details.\n\nTo make sure this example works, your `User` class must look as follows:\n\n```typescript\nclass User {\n  // ...other properties\n  roles: Role[];\n}\n```\n\nLastly, make sure to register the `RolesGuard`, for example, at the controller level, or globally:\n\n```typescript\nproviders: [\n  {\n    provide: APP_GUARD,\n    useClass: RolesGuard,\n  },\n],\n```\n\nWhen a user with insufficient privileges requests an endpoint, Nest automatically returns the following response:\n\n```typescript\n{\n  \"statusCode\": 403,\n  \"message\": \"Forbidden resource\",\n  \"error\": \"Forbidden\"\n}\n```\n\n> info **Hint** If you want to return a different error response, you should throw your own specific exception instead of returning a boolean value.\n\n#### Claims-based authorization\n\nWhen an identity is created it may be assigned one or more claims issued by a trusted party. A claim is a name-value pair that represents what the subject can do, not what the subject is.\n\nTo implement a Claims-based authorization in Nest, you can follow the same steps we have shown above in the [RBAC](/security/authorization#basic-rbac-implementation) section with one significant difference: instead of checking for specific roles, you should compare **permissions**. Every user would have a set of permissions assigned. Likewise, each resource/endpoint would define what permissions are required (for example, through a dedicated `@RequirePermissions()` decorator) to access them.\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@RequirePermissions(Permission.CREATE_CAT)\ncreate(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n@@switch\n@Post()\n@RequirePermissions(Permission.CREATE_CAT)\n@Bind(Body())\ncreate(createCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\n> info **Hint** In the example above, `Permission` (similar to `Role` we have shown in RBAC section) is a TypeScript enum that contains all the permissions available in your system.\n\n#### Integrating CASL\n\n[CASL](https://casl.js.org/) is an isomorphic authorization library which restricts what resources a given client is allowed to access. It's designed to be incrementally adoptable and can easily scale between a simple claim based and fully featured subject and attribute based authorization.\n\nTo start, first install the `@casl/ability` package:\n\n```bash\n$ npm i @casl/ability\n```\n\n> info **Hint** In this example, we chose CASL, but you can use any other library like `accesscontrol` or `acl`, depending on your preferences and project needs.\n\nOnce the installation is complete, for the sake of illustrating the mechanics of CASL, we'll define two entity classes: `User` and `Article`.\n\n```typescript\nclass User {\n  id: number;\n  isAdmin: boolean;\n}\n```\n\n`User` class consists of two properties, `id`, which is a unique user identifier, and `isAdmin`, indicating whether a user has administrator privileges.\n\n```typescript\nclass Article {\n  id: number;\n  isPublished: boolean;\n  authorId: number;\n}\n```\n\n`Article` class has three properties, respectively `id`, `isPublished`, and `authorId`. `id` is a unique article identifier, `isPublished` indicates whether an article was already published or not, and `authorId`, which is an ID of a user who wrote the article.\n\nNow let's review and refine our requirements for this example:\n\n- Admins can manage (create/read/update/delete) all entities\n- Users have read-only access to everything\n- Users can update their articles (`article.authorId === userId`)\n- Articles that are published already cannot be removed (`article.isPublished === true`)\n\nWith this in mind, we can start off by creating an `Action` enum representing all possible actions that the users can perform with entities:\n\n```typescript\nexport enum Action {\n  Manage = 'manage',\n  Create = 'create',\n  Read = 'read',\n  Update = 'update',\n  Delete = 'delete',\n}\n```\n\n> warning **Notice** `manage` is a special keyword in CASL which represents \"any\" action.\n\nTo encapsulate CASL library, let's generate the `CaslModule` and `CaslAbilityFactory` now.\n\n```bash\n$ nest g module casl\n$ nest g class casl/casl-ability.factory\n```\n\nWith this in place, we can define the `createForUser()` method on the `CaslAbilityFactory`. This method will create the `Ability` object for a given user:\n\n```typescript\ntype Subjects = InferSubjects<typeof Article | typeof User> | 'all';\n\nexport type AppAbility = Ability<[Action, Subjects]>;\n\n@Injectable()\nexport class CaslAbilityFactory {\n  createForUser(user: User) {\n    const { can, cannot, build } = new AbilityBuilder<\n      Ability<[Action, Subjects]>\n    >(Ability as AbilityClass<AppAbility>);\n\n    if (user.isAdmin) {\n      can(Action.Manage, 'all'); // read-write access to everything\n    } else {\n      can(Action.Read, 'all'); // read-only access to everything\n    }\n\n    can(Action.Update, Article, { authorId: user.id });\n    cannot(Action.Delete, Article, { isPublished: true });\n\n    return build({\n      // Read https://casl.js.org/v5/en/guide/subject-type-detection#use-classes-as-subject-types for details\n      detectSubjectType: item => item.constructor as ExtractSubjectType<Subjects>\n    });\n  }\n}\n```\n\n> warning **Notice** `all` is a special keyword in CASL that represents \"any subject\".\n\n> info **Hint** `Ability`, `AbilityBuilder`, `AbilityClass`, and `ExtractSubjectType` classes are exported from the `@casl/ability` package.\n\n> info **Hint** `detectSubjectType` option let CASL understand how to get subject type out of an object. For more information read  [CASL documentation](https://casl.js.org/v5/en/guide/subject-type-detection#use-classes-as-subject-types) for details.\n\nIn the example above, we created the `Ability` instance using the `AbilityBuilder` class. As you probably guessed, `can` and `cannot` accept the same arguments but has different meanings, `can` allows to do an action on the specified subject and `cannot` forbids. Both may accept up to 4 arguments. To learn more about these functions, visit the official [CASL documentation](https://casl.js.org/v5/en/guide/intro).\n\nLastly, make sure to add the `CaslAbilityFactory` to the `providers` and `exports` arrays in the `CaslModule` module definition:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { CaslAbilityFactory } from './casl-ability.factory';\n\n@Module({\n  providers: [CaslAbilityFactory],\n  exports: [CaslAbilityFactory],\n})\nexport class CaslModule {}\n```\n\nWith this in place, we can inject the `CaslAbilityFactory` to any class using standard constructor injection as long as the `CaslModule` is imported in the host context:\n\n```typescript\nconstructor(private caslAbilityFactory: CaslAbilityFactory) {}\n```\n\nThen use it in a class as follows.\n\n```typescript\nconst ability = this.caslAbilityFactory.createForUser(user);\nif (ability.can(Action.Read, 'all')) {\n  // \"user\" has read access to everything\n}\n```\n\n> info **Hint** Learn more about the `Ability` class in the official [CASL documentation](https://casl.js.org/v5/en/guide/intro).\n\nFor example, let's say we have a user who is not an admin. In this case, the user should be able to read articles, but creating new ones or removing the existing articles should be prohibited.\n\n```typescript\nconst user = new User();\nuser.isAdmin = false;\n\nconst ability = this.caslAbilityFactory.createForUser(user);\nability.can(Action.Read, Article); // true\nability.can(Action.Delete, Article); // false\nability.can(Action.Create, Article); // false\n```\n\n> info **Hint** Although both `Ability` and `AbilityBuilder` classes provide `can` and `cannot` methods, they have different purposes and accept slightly different arguments.\n\nAlso, as we have specified in our requirements, the user should be able to update its articles:\n\n```typescript\nconst user = new User();\nuser.id = 1;\n\nconst article = new Article();\narticle.authorId = user.id;\n\nconst ability = this.caslAbilityFactory.createForUser(user);\nability.can(Action.Update, article); // true\n\narticle.authorId = 2;\nability.can(Action.Update, article); // false\n```\n\nAs you can see, `Ability` instance allows us to check permissions in pretty readable way. Likewise, `AbilityBuilder` allows us to define permissions (and specify various conditions) in a similar fashion. To find more examples, visit the official documentation.\n\n#### Advanced: Implementing a `PoliciesGuard`\n\nIn this section, we'll demonstrate how to build a somewhat more sophisticated guard, which checks if a user meets specific **authorization policies** that can be configured on the method-level (you can extend it to respect policies configured on the class-level too). In this example, we are going to use the CASL package just for illustration purposes, but using this library is not required. Also, we will use the `CaslAbilityFactory` provider that we've created in the previous section.\n\nFirst, let's flesh out the requirements. The goal is to provide a mechanism that allows specifying policy checks per route handler. We will support both objects and functions (for simpler checks and for those who prefer more functional-style code).\n\nLet's start off by defining interfaces for policy handlers:\n\n```typescript\nimport { AppAbility } from '../casl/casl-ability.factory';\n\ninterface IPolicyHandler {\n  handle(ability: AppAbility): boolean;\n}\n\ntype PolicyHandlerCallback = (ability: AppAbility) => boolean;\n\nexport type PolicyHandler = IPolicyHandler | PolicyHandlerCallback;\n```\n\nAs mentioned above, we provided two possible ways of defining a policy handler, an object (instance of a class that implements the `IPolicyHandler` interface) and a function (which meets the `PolicyHandlerCallback` type).\n\nWith this in place, we can create a `@CheckPolicies()` decorator. This decorator allows specifying what policies have to be met to access specific resources.\n\n```typescript\nexport const CHECK_POLICIES_KEY = 'check_policy';\nexport const CheckPolicies = (...handlers: PolicyHandler[]) =>\n  SetMetadata(CHECK_POLICIES_KEY, handlers);\n```\n\nNow let's create a `PoliciesGuard` that will extract and execute all the policy handlers bound to a route handler.\n\n```typescript\n@Injectable()\nexport class PoliciesGuard implements CanActivate {\n  constructor(\n    private reflector: Reflector,\n    private caslAbilityFactory: CaslAbilityFactory,\n  ) {}\n\n  async canActivate(context: ExecutionContext): Promise<boolean> {\n    const policyHandlers =\n      this.reflector.get<PolicyHandler[]>(\n        CHECK_POLICIES_KEY,\n        context.getHandler(),\n      ) || [];\n\n    const { user } = context.switchToHttp().getRequest();\n    const ability = this.caslAbilityFactory.createForUser(user);\n\n    return policyHandlers.every((handler) =>\n      this.execPolicyHandler(handler, ability),\n    );\n  }\n\n  private execPolicyHandler(handler: PolicyHandler, ability: AppAbility) {\n    if (typeof handler === 'function') {\n      return handler(ability);\n    }\n    return handler.handle(ability);\n  }\n}\n```\n\n> info **Hint** In this example, we assumed that `request.user` contains the user instance. In your app, you will probably make that association in your custom **authentication guard** - see [authentication](/security/authentication) chapter for more details.\n\nLet's break this example down. The `policyHandlers` is an array of handlers assigned to the method through the `@CheckPolicies()` decorator. Next, we use the `CaslAbilityFactory#create` method which constructs the `Ability` object, allowing us to verify whether a user has sufficient permissions to perform specific actions. We are passing this object to the policy handler which is either a function or an instance of a class that implements the `IPolicyHandler`, exposing the `handle()` method that returns a boolean. Lastly, we use the `Array#every` method to make sure that every handler returned `true` value.\n\nFinally, to test this guard, bind it to any route handler, and register an inline policy handler (functional approach), as follows:\n\n```typescript\n@Get()\n@UseGuards(PoliciesGuard)\n@CheckPolicies((ability: AppAbility) => ability.can(Action.Read, Article))\nfindAll() {\n  return this.articlesService.findAll();\n}\n```\n\nAlternatively, we can define a class which implements the `IPolicyHandler` interface:\n\n```typescript\nexport class ReadArticlePolicyHandler implements IPolicyHandler {\n  handle(ability: AppAbility) {\n    return ability.can(Action.Read, Article);\n  }\n}\n```\n\nAnd use it as follows:\n\n```typescript\n@Get()\n@UseGuards(PoliciesGuard)\n@CheckPolicies(new ReadArticlePolicyHandler())\nfindAll() {\n  return this.articlesService.findAll();\n}\n```\n\n> warning **Notice** Since we must instantiate the policy handler in-place using the `new` keyword, `ReadArticlePolicyHandler` class cannot use the Dependency Injection. This can be addressed with the `ModuleRef#get` method (read more [here](/fundamentals/module-ref)). Basically, instead of registering functions and instances through the `@CheckPolicies()` decorator, you must allow passing a `Type<IPolicyHandler>`. Then, inside your guard, you could retrieve an instance using a type reference: `moduleRef.get(YOUR_HANDLER_TYPE)` or even dynamically instantiate it using the `ModuleRef#create` method.\n"
  },
  {
    "path": "content/security/cors.md",
    "content": "### CORS\n\nCross-origin resource sharing (CORS)은 다른 도메인에서 리소스를 요청하는 것을 허용하는 메커니즘입니다. Nest에서는 내부적으로 Express의 [cors](https://github.com/expressjs/cors) 패키지를 사용합니다. 이 패키지는 요구사항에 따라 커스터마이징 할 수 있도록 다양한 옵션을 제공합니다.\n\n#### 시작하기\n\nCORS를 활성화하려면, Nest 애플리케이션 객체의 `enableCors()`를 호출해야 합니다.\n\n```typescript\nconst app = await NestFactory.create(AppModule);\napp.enableCors();\nawait app.listen(3000);\n```\n\n`enableCors()` 메서드에는 선택적으로 설정 객체를 인자로 넘길 수 있습니다. 이 객체에서 사용할 수 있는 프로퍼티들은 [CORS](https://github.com/expressjs/cors#configuration-options) 공식 문서에 명시되어 있습니다. 또 다른 방법은 요청을 기반하여(그 즉시) 비동기적으로 설정 객체를 정의하는 [콜백 함수](https://github.com/expressjs/cors#configuring-cors-asynchronously)를 넘기는 것입니다.\n\n`create()` 메서드의 옵션 객체를 통해서도 CORS를 활성화할 수 있습니다. `cors` 프로퍼티를 `true`로 설정하면 기본 세팅값으로 COSR가 활성화됩니다. 아니면 [CORS 설정 객체](https://github.com/expressjs/cors#configuration-options)나 [콜백 함수](https://github.com/expressjs/cors#configuring-cors-asynchronously)를 `cors` 프로퍼티의 값으로 넘겨 동작을 커스터마이징 할 수도 있습니다.\n\n```typescript\nconst app = await NestFactory.create(AppModule, { cors: true });\nawait app.listen(3000);\n```\n\n위 메서드는 REST 엔드포인트에만 적용됩니다.\n\nCORS를 GraphQ에서 활성화하려면, GraphQL 모듈을 import할 때 `cors` 프로퍼티를 `true`로 설정하거나 [CORS 설정 객체](https://github.com/expressjs/cors#configuration-options) 또는 [콜백 함수](https://github.com/expressjs/cors#configuring-cors-asynchronously)를 `cors` 프로퍼티의 값으로 넘깁니다.\n\n> wargin **주의** `apollo-server-fastify` 패키지에서는 아직 `CorsOptionsDelegate` 솔루션을 지원하지 않습니다.\n\n```typescript\nGraphQLModule.forRoot({\n  cors: {\n    origin: 'http://localhost:3000',\n    credentials: true,\n  },\n}),\n```\n"
  },
  {
    "path": "content/security/csrf.md",
    "content": "### CSRF 보호\n\nCSRF나 XSRF로 잘 알려진 Cross-site request forgery는 웹 에플리케이션이 신뢰하는 사용자로부터 **승인되지 않은**명령이 전송되게 만들도록 웹사이트를 악용하는 수법입니다. [csurf](https://github.com/expressjs/csurf) 패키지를 이용하면 이러한 유형의 공격을 완화시킬 수 있습니다.\n\n#### Express와 함께 사용하기 (기본)\n\n먼저 필요한 패키지를 설치합니다:\n\n```bash\n$ npm i --save csurf\n```\n\n> warning **주의** [`csurf` 문서](https://github.com/expressjs/csurf#csurf)에서 설명하는 바에 따르면, 이 미들웨어는 세션 미들웨어나 `cookie-parser`를 먼저 설치해야 사용할 수 있습니다. 문서를 참조하시어 추가 지침을 확인하시길 바랍니다.\n\n설치가 완료되었으면 `csurf` 미들웨어를 전역 미들웨어로 적용합니다.\n\n```typescript\nimport * as csurf from \"csurf\";\n// ...\n// somewhere in your initialization file\napp.use(csurf());\n```\n\n#### Fastify와 함께 사용하기\n\n먼저 필요한 패키지를 설치합니다:\n\n```bash\n$ npm i --save fastify-csrf\n```\n\n설치가 완료되었다면, 다음과 같이 `fastify-csrf` 플러그인을 등록합니다:\n\n```typescript\nimport fastifyCsrf from \"fastify-csrf\";\n// ...\n// somewhere in your initialization file after registering some storage plugin\napp.register(fastifyCsrf);\n```\n\n> warning **주의** [여기](https://github.com/fastify/fastify-csrf#usage) `fastify-csrf` 문서에서 설명하는 바에 따르면, 이 플러그인은 저장소 플러그인을 먼저 설치해야 사용할 수 있습니다. 문서를 참조하시어 추가 지침을 확인하시길 바랍니다.\n"
  },
  {
    "path": "content/security/encryption-hashing.md",
    "content": "### 암호화와 해싱\n\n**암호화**는 정보를 인코딩하는 작업입니다. 이 작업은 평문이라 불리는 정보의 원래 표현을 암호문이라 불리는 또다른 형태로 변환합니다. 이상적으로는 승인된 당사자만이 암호문을 다시 평문으로 해독하여 원본 정보에 액세스할 수 있습니다. 암호화는 그 자체로 간섭을 막지는 못하지만, 잠재적인 인터셉터가 이해할 수 있는 내용은 거부합니다. 암호화는 양방향 기능입니다. 이는 암호화된 내용을 적절한 키를 사용하여 복호화할 수 있다는 것입니다.\n\n**해싱**은 주어진 키를 다른 값으로 변환하는 작업입니다. 이 때 수학적인 알고리즘에 따라 새로운 값을 생성하는 역할을 하는 것이 해시 함수입니다. 해싱되고 나면 그 결과를 가지고 다시 입력값을 구해낼 수 없습니다.\n\n#### 암호화\n\nNode.js는 문자열, 숫자, 버퍼, 스트림 등을 암호화 및 복호화할 수 있는 [crypto 모듈](https://nodejs.org/api/crypto.html)을 자체적으로 제공합니다. Nest 자체는 불필요한 추상화를 피하기 위해 이 모듈 위에서 동작하는 추가적인 패키지를 제공하지는 않습니다.\n\n예를 들어, AES (Advanced Encryption System) 알고리즘의 CTR 암호화 모드인 `'aes-256-ctr'`을 사용해 보겠습니다.\n\n```typescript\nimport { createCipheriv, randomBytes, scrypt } from \"crypto\";\nimport { promisify } from \"util\";\n\nconst iv = randomBytes(16);\nconst password = \"Password used to generate key\";\n\n// The key length is dependent on the algorithm.\n// In this case for aes256, it is 32 bytes.\nconst key = (await promisify(scrypt)(password, \"salt\", 32)) as Buffer;\nconst cipher = createCipheriv(\"aes-256-ctr\", key, iv);\n\nconst textToEncrypt = \"Nest\";\nconst encryptedText = Buffer.concat([\n  cipher.update(textToEncrypt),\n  cipher.final(),\n]);\n```\n\n이제 `encryptedText`값을 복호화 해보겠습니다:\n\n```typescript\nimport { createDecipheriv } from \"crypto\";\n\nconst decipher = createDecipheriv(\"aes-256-ctr\", key, iv);\nconst decryptedText = Buffer.concat([\n  decipher.update(encryptedText),\n  decipher.final(),\n]);\n```\n\n#### 해싱\n\n해생을 위해서는 [bcrypt](https://www.npmjs.com/package/bcrypt) 패키지나 [argon2](https://www.npmjs.com/package/argon2) 패키지를 사용하기를 권장합니다. Nest 자체는 불필요한 추상화를 피하기 위해 (러닝커브를 완만하게 만들기 위해) 이 모듈들 위에 추가 래퍼를 제공하지 않습니다.\n\n예를 들어, 랜덤한 비밀번호를 해싱하기 위해 `bcrypt`를 사용해 보겠습나다.\n\n우선 필요한 패키지들을 설치합니다:\n\n```shell\n$ npm i bcrypt\n$ npm i -D @types/bcrypt\n```\n\n설치가 완료되면, 다음과 같이 `hash` 함수를 사용할 수 있습니다:\n\n```typescript\nimport * as bcrypt from \"bcrypt\";\n\nconst saltOrRounds = 10;\nconst password = \"random_password\";\nconst hash = await bcrypt.hash(password, saltOrRounds);\n```\n\nsalt를 생성하려면 `genSalt` 함수를 사용합니다:\n\n```typescript\nconst salt = await bcrypt.genSalt();\n```\n\n비밀번호를 확인 및 비교하려면 `compare` 함수를 사용합니다:\n\n```typescript\nconst isMatch = await bcrypt.compare(password, hash);\n```\n\n관련하여 [여기](https://www.npmjs.com/package/bcrypt)에서 더 많은 함수들을 확인할 수 있습니다.\n"
  },
  {
    "path": "content/security/helmet.md",
    "content": "### Helmet\n\n[Helmet](https://github.com/helmetjs/helmet)은 HTTP 헤더를 적절하게 설정해 줘서 우리의 앱을 잘 알려진 웹 취약점으로부터 보호하는 데 도움을 줍니다. 일반적으로 Helmet은 보안과 관련된 HTTP 헤더를 설정하는 작은 미들웨어 함수의 집합체입니다(자세한 정보는 [여기](https://github.com/helmetjs/helmet#how-it-works)를 참조하세요).\n\n> info **힌트** `helmet`을 전역적으로 등록하고 적용하는 일은 다른 `app.use()` 구문들 혹은 `app.use()`를 호출하는 설정 함수들보다 먼저 실행되어야 합니다. 이는 기본 플랫폼(즉, Express 또는 Fastify)이 동작할 때 미들웨어/라우트들이 정의된 순서가 중요하기 때문입니다. 만약 라우트를 정의한 이후에 `helmet`이나 `cors`같은 미들웨어를 사용한다면, 그 미들웨어는 해당 라우트들에게 적용되지 않고 미들웨어 다음에 정의된 라우트에만 적용될 것입니다.\n\n#### Express와 함께 사용하기 (기본)\n\n우선 필요한 패키지를 설치합니다.\n\n```bash\n$ npm i --save helmet\n```\n\n설치가 완료되면, 이를 전역 미들웨어로 적용합니다.\n\n```typescript\nimport * as helmet from \"helmet\";\n// somewhere in your initialization file\napp.use(helmet());\n```\n\n> info **힌트** 만약 `Helmet`을 import할 때 `This expression is not callable`라는 에러가 발생한다면 프로젝트의 `tsconfig.json` 파일에 `allowSyntheticDefaultImports` 옵션과 `esModuleInterop` 옵션이 `true`로 설정되었을 가능성이 큽니다. 만약 그렇다면 import 구문을 이렇게 바꿔 주세요: `import helmet from 'helmet'`.\n\n#### Fastify와 함께 사용하기\n\n만약 `FastifyAdapter`를 사용한다면 [fastify-helmet](https://github.com/fastify/fastify-helmet) 패키지를 설치해야 합니다:\n\n```bash\n$ npm i --save fastify-helmet\n```\n\n[fastify-helmet](https://github.com/fastify/fastify-helmet)는 미들웨어가 아닌 [Fastify 플러그인](https://www.fastify.io/docs/latest/Plugins/)으로 사용합니다. 즉, `app.register()`을 사용합니다:\n\n```typescript\nimport { fastifyHelmet } from \"fastify-helmet\";\n// somewhere in your initialization file\nawait app.register(fastifyHelmet);\n```\n\n> warning **주의** `apollo-server-fastify`과 `fastify-helmet`를 사용한다면, GraphQL playground에서 [CSP](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)와 관련된 문제가 있을 수도 있습니다. 이 충돌을 해결하기 위해 아래와 같이 CSP를 설정해 주세요:\n>\n> ```typescript\n> await app.register(fastifyHelmet, {\n>   contentSecurityPolicy: {\n>     directives: {\n>       defaultSrc: [`'self'`],\n>       styleSrc: [\n>         `'self'`,\n>         `'unsafe-inline'`,\n>         \"cdn.jsdelivr.net\",\n>         \"fonts.googleapis.com\",\n>       ],\n>       fontSrc: [`'self'`, \"fonts.gstatic.com\"],\n>       imgSrc: [`'self'`, \"data:\", \"cdn.jsdelivr.net\"],\n>       scriptSrc: [`'self'`, `https: 'unsafe-inline'`, `cdn.jsdelivr.net`],\n>     },\n>   },\n> });\n>\n> // If you are not going to use CSP at all, you can use this:\n> await app.register(fastifyHelmet, {\n>   contentSecurityPolicy: false,\n> });\n> ```\n"
  },
  {
    "path": "content/security/rate-limiting.md",
    "content": "### 비율 제한\n\n**비율 제한**은 브루트-포스 공격으로부터 애플리케이션을 보호하는 일반적인 방법입니다. 이를 위해 `@nestjs/throttler` 패키지를 설치해야 합니다.\n\n```bash\n$ npm i --save @nestjs/throttler\n```\n\n설치가 완료되면, `ThrottlerModule`을 다른 Nest 패키지들처럼 `forRoot`나 `forRootAsync` 메서드를 이용하여 설정할 수 있습니다.\n\n```typescript\n@Module({\n  imports: [\n    ThrottlerModule.forRoot({\n      ttl: 60,\n      limit: 10,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n위의 예제에서는 보호받을 라우트들에게 적용될 전역 옵션을 설정합니다. 단위 시간인 `ttl`과 ttl동안의 최대 요청 횟수인 `limit`을 설정했습니다.\n\n모듈이 import되면, `ThrottlerGuard`를 어떻게 바인딩할지 선택할 수 있습니다. [가드](/guards) 섹션에서 언급한 어느 유형의 바인딩이든 사용할 수 있습니다. 가드를 전역적으로 바인딩하고 싶다면, 어느 모듈에서든 아래 예와 같이 해당 프로바이더를 추가하면 됩니다:\n\n```typescript\n{\n  provide: APP_GUARD,\n  useClass: ThrottlerGuard\n}\n```\n\n#### 사용자 정의\n\n가드를 전역이나 컨트롤러에 바인딩하고 싶지만, 하나 혹은 여러 엔드포인트에 대해서는 비율 제한을 비활성화하고 싶은 경우도 있을 수 있습니다. 그런 경우에는 `@SkipThrottler()` 데코레이터를 사용하여 전체 클래스 또는 하나의 라우트에 쓰로틀러를 배제시킬 수 있습니다. 전체 라우트는 아니지만 특정 컨트롤러의 *대부분*은 제외하고 싶다면 `@SkipThrottler()` 데코레이터에 boolean을 취할 수도 있습니다.\n\n보안 옵션을 더 엄격하거나 느슨하게 조절할 수 있도록, 전역 모듈에 설정된 `limit`과 `ttl`을 덮어씌울 수 있는 `@Throttele()` 데코레이터도 있습니다. 이 데코레이터 또한 클래스나 함수 위에 사용할 수 있습니다. 이 데코레이터에는 인자를 `limit, ttl`의 순서로 넘기는 것에 유의해야 합니다.\n\n#### 프록시\n\n만약 애플리케이션이 프록시 서버 뒤에서 실행된다면, `프록시 신뢰` 옵션에 대한 HTTP 어댑터 옴션([express](http://expressjs.com/en/guide/behind-proxies.html), [fastify](https://www.fastify.io/docs/latest/Server/#trustproxy))을 찾아서 활성화 하면 됩니다. 그렇게 하면 `X-Forward-For` 헤더에 원래 IP 주소가 포함되며, `getTracker()` 메서드를 오버라이딩하여 `req.ip`가 아니라 헤더에서 그 값을 받아올 수 있습니다. 아래 예제는 express와 fastify 모두 동일합니다:\n\n```ts\n// throttler-behind-proxy.guard.ts\nimport { ThrottlerGuard } from '@nestjs/throttler';\nimport { Injectable } from '@nestjs/common';\n\n@Injectable()\nexport class ThrottlerBehindProxyGuard extends ThrottlerGuard {\n  protected getTracker(req: Record<string, any>): string {\n    return req.ips.length ? req.ips[0] : req.ip; // individualize IP extraction to meet your own needs\n  }\n}\n\n// app.controller.ts\nimport { ThrottlerBehindProxyGuard } from './throttler-behind-proxy.guard';\n\n@UseGuards(ThrottlerBehindProxyGuard)\n```\n\n> info **힌트** 요청 객체 `req`에 대한 API는 express는 [여기](https://expressjs.com/en/api.html#req.ips)에서, fastify는 [여기](https://www.fastify.io/docs/latest/Request/)에서 확인할 수 있습니다.\n\n#### 웹소켓\n\n이 모듈은 웹소켓에서도 동작하지만 몇 가지 확장 클래스가 필요합니다. 다음과 같이 `ThrottlerGuard`를 상속받고 `handleRequest` 메서드를 오버라이딩합니다:\n\n```typescript\n@Injectable()\nexport class WsThrottlerGuard extends ThrottlerGuard {\n  async handleRequest(\n    context: ExecutionContext,\n    limit: number,\n    ttl: number\n  ): Promise<boolean> {\n    const client = context.switchToWs().getClient();\n    const ip = client.conn.remoteAddress;\n    const key = this.generateKey(context, ip);\n    const ttls = await this.storageService.getRecord(key);\n\n    if (ttls.length >= limit) {\n      throw new ThrottlerException();\n    }\n\n    await this.storageService.addRecord(key, ttl);\n    return true;\n  }\n}\n```\n\n> info **힌트** 만약 `@nestjs/platform-ws` 패키지를 사용한다면 `client._socket.remoteAddress`를 사용해야 합니다.\n\n#### GraphQL\n\n`ThrottlerGuard`는 GraphQL 요청에 대해서도 동작합니다. 역시 가드를 확장해야 하는데, 이번에는 `getRequestResponse` 메서드를 오버라이딩합니다.\n\n```typescript\n@Injectable()\nexport class GqlThrottlerGuard extends ThrottlerGuard {\n  getRequestResponse(context: ExecutionContext) {\n    const gqlCtx = GqlExecutionContext.create(context);\n    const ctx = gqlCtx.getContext();\n    return { req: ctx.req, res: ctx.res };\n  }\n}\n```\n\n#### 설정\n\n아래는 `ThrottlerModule`이 가질 수 있는 옵션들입니다:\n\n<table>\n  <tr>\n    <td><code>ttl</code></td>\n    <td>각 요청이 저장소에 존재하는 시간</td>\n    <td></td>\n  </tr>\n  <tr>\n    <td><code>limit</code></td>\n    <td>TTL 제한 내 최대 요청 횟수</td>\n  </tr>\n  <tr>\n    <td><code>ignoreUserAgents</code></td>\n    <td>쓰로틀링 요청이 들어왔을 때 무시할 user-agents에서 무시할 정규표현식들을 담은 배열</td>\n  </tr>\n  <tr>\n    <td><code>storage</code></td>\n    <td>요청을 추적하는 방법에 대한 저장소 설정</td>\n  </tr>\n</table>\n\n#### 비동기 설정\n\n비율 제한에 대한 설정을 동기적이 아닌 비동기적으로 하고 싶다면, `forRootAsync()` 메서드를 사용하여 `async` 메서드와 의존성 주입을 허용할 수 있습니다.\n\n팩토리 함수를 사용하는 것도 하나의 방법입니다:\n\n```typescript\n@Module({\n  imports: [\n    ThrottlerModule.forRootAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) => ({\n        ttl: config.get(\"THROTTLE_TTL\"),\n        limit: config.get(\"THROTTLE_LIMIT\"),\n      }),\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n`useClass` 구문을 사용할 수도 있습니다:\n\n```typescript\n@Module({\n  imports: [\n    ThrottlerModule.forRootAsync({\n      imports: [ConfigModule],\n      useClass: ThrottlerConfigService,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n이는 `ThrottlerConfigService`가 구현하는 `ThrottlerOptionsFactory` 인터페이스를 따르는 한 얼마든지 자유롭게 작성할 수 있습니다.\n\n#### 저장소\n\n내장 저장소는 메모리에 캐시되어, 전역 옵션으로 설정한 TTL값을 넘길 때까지 요청을 추적합니다. `ThrottlerModule`의 `storage` 옵션에 `ThrottlerStorage` 인터페이스를 따르는 한에서 자유롭게 자신의 저장소 옵션을 추가할 수 있습니다.\n\n분산 서버 환경의 경우, [Redis](https://github.com/kkoomen/nestjs-throttler-storage-redis)용 커뮤니티 저장소 프로바이더를 사용함으로써 신뢰할 수 있는 단일 소스를 가질 수 있습니다.\n\n> info **참고** `ThrottlerStorage`는 `@nestjs/throttler`에서 import합니다.\n"
  },
  {
    "path": "content/support.md",
    "content": "### Support\n\nNest is an MIT-licensed open source project with its ongoing development made possible thanks to the support by the community. This framework is a result of the long road, full of sleepless nights, working **after hours**, and busy weekends.\n\n#### How can you help?\n\nNest doesn't have a large company that sits behind and is continuously paying for hours spent on the development. I fully rely on the **goodness** ❤️ of the people. However, I would love to make this framework even more **powerful**, to be fully focused on delivering you great solutions that make coding process enjoyable: In order to help me, I run few supporting platforms:\n\n- become a backer or sponsor on [OpenCollective](https://opencollective.com/nest)\n- use [PayPal](https://paypal.me/kamilmysliwiec) to send a one-time donation\n- or reach me directly: [mail@kamilmysliwiec.com](mailto:mail@kamilmysliwiec.com)\n\nIf you fell in love with Nest, or you run a business which is using Nest, consider sponsoring its development to ensure that the project which your product relies on is **actively maintained** and improved. Also, your support could help me to work more on content that benefits whole Nest community, writing either educational blog posts or recording videos.\n"
  },
  {
    "path": "content/techniques/caching.md",
    "content": "### 캐싱\n\n캐싱은 앱의 성능을 향상시킬 수 있는 훌륭하면서도 간단한 **테크닉** 입니다. 캐싱은 고성능 데이터 액세스를 제공하는 임시 데이터 저장소 역할을 합니다.  \n\n#### 설치\n\n먼저 캐싱을 사용하는 데 필요한 패키지를 설치합니다.\n\n```bash\n$ npm install cache-manager\n$ npm install -D @types/cache-manager\n```\n\n#### 인메모리 캐시\n\n네스트는 다양한 캐시 스토리지 프로바이더를 사용할 수 있도록 통합 API를 제공하며, 네스트 내에 인메모리 데이터 저장소가 내장되어 있습니다. 레디스 같은 포괄적인 솔루션도 쉽게 사용할 수 있습니다. \n\n캐싱을 사용하려면, `CacheModule` 를 임포트 하고 해당 모듈의 `register()` 매소드를 호출합니다.\n\n```typescript\nimport { CacheModule, Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\n\n@Module({\n  imports: [CacheModule.register()],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n#### 캐시 저장소와 상호작용\n\n캐시 매니저 인스턴스를 사용하려면, 아래와 같이 `CACHE_MANAGER` 토큰을 사용해 클래스에 주입합니다.\n\n```typescript\nconstructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}\n```\n\n> 정보 **힌트** `Cache` 클래스는 `cache-manager`에서 임포트 합니다. `CACHE_MANAGER` 토큰은 `@nestjs/common` 패키지에서 임포트 합니다.\n\n`Cache` 인스턴스(`cache-manager` 패키지) 의 `get` 메소드는 캐시에서 아이템을 갖고오는데 사용합니다. 만약 캐시에 항목이 없으면 `null` 을 반환합니다.\n\n```typescript\nconst value = await this.cacheManager.get('key');\n```\n\n캐시에 아이템을 추가하려면, `set` 메소드를 사용합니다:\n\n```typescript\nawait this.cacheManager.set('key', 'value');\n```\n\n캐시의 기본 만료 시간은 5초 입니다.\n\n다음과 같이 이 특정 키에 대한 TTL(초단위 만료시간)를 수동으로 지정할 수 있습니다. \n\n```typescript\nawait this.cacheManager.set('key', 'value', { ttl: 1000 });\n```\n\n캐시 만료를 비활성화하려면, `ttl` 구성 속성을 `0` 으로 설정합니다:\n\n```typescript\nawait this.cacheManager.set('key', 'value', { ttl: 0 });\n```\n\n캐시에서 아이템을 삭제하려면, `del` 메소드를 사용합니다:\n\n```typescript\nawait this.cacheManager.del('key');\n```\n\n캐시 전체를 비우려면, `reset` 메소드를 사용합니다:\n\n```typescript\nawait this.cacheManager.reset();\n```\n\n#### 오토-캐싱 리스폰스(Auto-caching responses)\n\n> **경고** [GraphQL](/graphql/quick-start) 어플리케이션에서 인터셉터는 각 필드 리졸버 마다 별도로 실행합니다. 따라서 `CacheModule` (인터셉터를 사용해서 응답을 캐시) 이 제대로 작동하지 않을 수 도 있습니다.\n\n오토-캐싱 리스폰스를 활성화하려면, 캐시하려는 데이터에 `CacheInterceptor` 를 연결하면 됩니다.\n\n```typescript\n@Controller()\n@UseInterceptors(CacheInterceptor)\nexport class AppController {\n  @Get()\n  findAll(): string[] {\n    return [];\n  }\n}\n```\n\n> 경고**경고** 오직 `GET` 엔드포인트만 캐시합니다. 또한 네이티브 리스폰스 오브젝트(`@Res()`)를 주입한 HTTP 서버 라우트는 캐시 인터셉터를 사용할 수 없습니다.\n> 자세한 내용은 <a href=\"https://docs.nestjs.com/interceptors#response-mapping\">리스폰스 매핑</a> 을 참조하세요.\n\n필요한 보일러플레이트의 양을 줄이기 위해, `CacheInterceptor` 를 전역으로 모든 엔드포인트에 바인딩 할 수 있습니다.\n\n```typescript\nimport { CacheModule, Module, CacheInterceptor } from '@nestjs/common';\nimport { AppController } from './app.controller';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\n\n@Module({\n  imports: [CacheModule.register()],\n  controllers: [AppController],\n  providers: [\n    {\n      provide: APP_INTERCEPTOR,\n      useClass: CacheInterceptor,\n    },\n  ],\n})\nexport class AppModule {}\n```\n\n#### 커스터마이즈 캐시 \n\n캐시된 모든 데이터에는 고유한 만료 시간이 있습니다. ([TTL](https://en.wikipedia.org/wiki/Time_to_live)). 기본값을 사용자가 정의하려면, options 객체를 `register()` 메소드로 전달합니다.\n\n```typescript\nCacheModule.register({\n  ttl: 5, // 초\n  max: 10, // 캐시의 최대 아이템 수\n});\n```\n\n#### 모듈 전역 사용\n\n다른 모듈에서 `CacheModule` 을 사용하려면, 임포트를 해야 합니다. (모든 Nest 모듈이 기본적으로 임포트가 필요합니다). 또는 아래와 같이 옵션 객체의 `isGlobal` 속성을 `true` 로 설정해 [전역 모듈](https://docs.nestjs.com/modules#global-modules) 로 선언할 수 있습니다. 이런 경우에는, 루트 모듈 (예: `AppModule`) 이 로드 된 뒤 다른 모듈에 `CacheModule` 를 임포트할 필요가 없습니다.\n\n```typescript\nCacheModule.register({\n  isGlobal: true,\n});\n```\n\n#### 글로벌 캐시 오버라이드\n\n전역 캐시가 활성화되어 있는 동안에는 경로를 기반으로 자동 생성되는 `CacheKey` 아래에 캐시 항목을 저장합니다. 메소드 별로 특정 캐시 설정 (`@CacheKey()` 과 `@CacheTTL()`)을 오버라이드해 개별 컨트롤러 메소드마다 맞춤형 캐싱 전략을 사용할 수 있습니다. [다른 캐시 저장소.](https://docs.nestjs.com/techniques/caching#different-stores)를 사용할 때 필요할 수 있습니다.\n\n```typescript\n@Controller()\nexport class AppController {\n  @CacheKey('custom_key')\n  @CacheTTL(20)\n  findAll(): string[] {\n    return [];\n  }\n}\n```\n\n> 정보 **힌트** `@CacheKey()` 와 `@CacheTTL()` 데코레이터는 `@nestjs/common` 패키지에서 임포트 합니다.\n\n`@CacheKey()` 데코레이터는 `@CacheTTL()` 데코레이터와 함께 또는 단독으로 사용할 수 있으며, 그 반대도 가능합니다. `@CacheKey()` 만, `@CacheTTL()` 만 오버라이드 하도록 선택할 수 있으며 데코레이터로 오버라이드하지 않은 설정은 전역으로 등록된 기본값을 사용합니다. ([캐시 사용자 지정](https://docs.nestjs.com/techniques/caching#customize-caching) 보기).\n\n#### 웹소켓과 마이크로서비스\n\n웹소켓 구독자와 마이크로서비스 패턴에 `CacheInterceptor` 적용할 수 도 있습니다. (사용중인 전송방법과 관계없이 적용 가능합니다).\n\n```typescript\n@@filename()\n@CacheKey('events')\n@UseInterceptors(CacheInterceptor)\n@SubscribeMessage('events')\nhandleEvent(client: Client, data: string[]): Observable<string[]> {\n  return [];\n}\n@@switch\n@CacheKey('events')\n@UseInterceptors(CacheInterceptor)\n@SubscribeMessage('events')\nhandleEvent(client, data) {\n  return [];\n}\n```\n\n그러나 데이터를 캐시에 저장하거나 가져오는 데 사용하는 키를 지정하려면 `@CacheKey()` 데코레이터가 추가로 필요합니다. 또한 **모든 걸 캐시하면 안된다**는 걸 명심하세요. 단순 데이터 쿼리가 아닌 비즈니스 작업을 수행하는 작업은 캐시해서는 안됩니다. \n \n또한 `@CacheTTL()` 데코레이터를 사용해서 캐시 만료 시간(TTL)을 지정하면 전역 캐시 만료 시간(TTL)을 오버라이드합니다.\n\n```typescript\n@@filename()\n@CacheTTL(10)\n@UseInterceptors(CacheInterceptor)\n@SubscribeMessage('events')\nhandleEvent(client: Client, data: string[]): Observable<string[]> {\n  return [];\n}\n@@switch\n@CacheTTL(10)\n@UseInterceptors(CacheInterceptor)\n@SubscribeMessage('events')\nhandleEvent(client, data) {\n  return [];\n}\n```\n\n> 정보 **힌트** `@CacheTTL()` 데코레이터는 `CacheModule` 데코레이터와 함께 또는 단독으로 사용할 수 있습니다. \n\n#### 트래킹 조정\n\n기본적으로 Nest는 요청 URL(HTTP 앱에서) 또는 캐시 키(웹 소켓 및 마이크로서비스 앱에서 `@CacheKey()` 데코레이터를 통해 설정)를 사용하여 캐시 레코드를 엔드포인트와 연결합니다. 그럼에도 불구하고 HTTP 헤더(예: `profile` 엔드포인트를 올바르게 식별하기 위한 `Authorization`)를 사용과 같이 다양한 요소를 기반으로 추적을 설정하고 싶을 수도 있습니다.\n\n이렇게 하려면 `CacheInterceptor` 의 서브클래스를 생성하고 `trackBy()` 메소드를 사용해 오버라이드 합니다.\n\n```typescript\n@Injectable()\nclass HttpCacheInterceptor extends CacheInterceptor {\n  trackBy(context: ExecutionContext): string | undefined {\n    return 'key';\n  }\n}\n```\n\n#### 다른 저장소\n\n이 서비스는 [캐시 매니저](https://github.com/BryanDonovan/node-cache-manager)를 사용합니다. `cache-manager` 패키지는 [레디스](https://github.com/dabroek/node-cache-manager-redis-store)와 같은 다양한 유용한 저장소를 지원합니다. 지원되는 스토어의 전체 목록은 [여기](https://github.com/BryanDonovan/node-cache-manager#store-engines)에서 확인할 수 있습니다. 레디스를 설정하려면 해당 옵션과 함께 패키지를 `register()` 메소드에 전달하기만 하면 됩니다.\n\n```typescript\nimport type { ClientOpts as RedisClientOpts } from 'redis'\nimport * as redisStore from 'cache-manager-redis-store';\nimport { CacheModule, Module } from '@nestjs/common';\nimport { AppController } from './app.controller';\n\n@Module({\n  imports: [\n    CacheModule.register<RedisClientOpts>({\n      store: redisStore,\n      // Store-specific configuration:\n      host: 'localhost',\n      port: 6379,\n    }),\n  ],\n  controllers: [AppController],\n})\nexport class AppModule {}\n```\n\n#### 비동기 구성\n\n컴파일 시간에 정적으로 전달하는 대신, 모듈 옵션을 비동기로 전달할 수 있습니다. 이 경우 비동기 구성을 처리하는 여러가지 방법을 제공하는 `registerAsync()`  메소드를 사용합니다.  \n\n팩토리 함수를 사용합니다:\n\n```typescript\nCacheModule.registerAsync({\n  useFactory: () => ({\n    ttl: 5,\n  }),\n});\n```\n\n팩토리는 다른 비동기 모듈 팩토리처럼 작동합니다. (`async` 이거나 `inject`를 통해 종속성을 주입받을 수 있습니다).\n\n```typescript\nCacheModule.registerAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    ttl: configService.get('CACHE_TTL'),\n  }),\n  inject: [ConfigService],\n});\n```\n\n또는 `useClass` 메소드를 사용할 수 있습니다:\n\n```typescript\nCacheModule.registerAsync({\n  useClass: CacheConfigService,\n});\n```\n\n위의 구성은 `CacheModule` 내부의 `CacheConfigService` 를 인스턴스화 하고 이를 사용해 옵션 객체를 가져옵니다. `CacheConfigService` 는 `CacheOptionsFactory` 인터페이스를 구현해야 구성옵션을 제공할 수 있습니다:\n\n```typescript\n@Injectable()\nclass CacheConfigService implements CacheOptionsFactory {\n  createCacheOptions(): CacheModuleOptions {\n    return {\n      ttl: 5,\n    };\n  }\n}\n```\n\n다른 모듈에서 가져온 기존 구성 공급자를 사용하려면 `useExisting` 구문을 사용합니다:\n\n```typescript\nCacheModule.registerAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n});\n```\n\n이것은 `useClass` 와 동일하게 작동하지만 단 한가지 큰 차이점이 있습니다. `CacheModule` 은 인스턴스를 생성하지 않고, 이미 생성된 `ConfigService` 을 재사용하기 위해 임포트 하고 있는 모듈을 조회합니다.\n\n> 정보 **힌트** `CacheModule#register` 와 `CacheModule#registerAsync` 와 `CacheOptionsFactory` 는 저장소별 구성 옵션 까지 좁혀진 선택적 제네릭 (타입 아규먼트) 을 사용해 타입을 안전하게 합니다. \n\n#### 예제\n\n작업 예시는 [여기](https://github.com/nestjs/nest/tree/master/sample/20-cache)에서 볼 수 있습니다.\n"
  },
  {
    "path": "content/techniques/compression.md",
    "content": "### Compression\n\nCompression can greatly decrease the size of the response body, thereby increasing the speed of a web app.\n\nFor **high-traffic** websites in production, it is strongly recommended to offload compression from the application server - typically in a reverse proxy (e.g., Nginx). In that case, you should not use compression middleware.\n\n#### Use with Express (default)\n\nUse the [compression](https://github.com/expressjs/compression) middleware package to enable gzip compression.\n\nFirst install the required package:\n\n```bash\n$ npm i --save compression\n```\n\nOnce the installation is complete, apply the compression middleware as global middleware.\n\n```typescript\nimport * as compression from 'compression';\n// somewhere in your initialization file\napp.use(compression());\n```\n\n#### Use with Fastify\n\nIf using the `FastifyAdapter`, you'll want to use [fastify-compress](https://github.com/fastify/fastify-compress):\n\n```bash\n$ npm i --save fastify-compress\n```\n\nOnce the installation is complete, apply the fastify-compress middleware as global middleware.\n\n```typescript\nimport compression from 'fastify-compress';\n// somewhere in your initialization file\napp.register(compression);\n```\n\nBy default, fastify-compress will use Brotli compression (on Node >= 11.7.0) when browsers indicate support for the encoding. While Brotli is quite efficient in terms of compression ratio, it's also quite slow. Due to this, you may want to tell fastify-compress to only use deflate and gzip to compress responses; you'll end up with larger responses but they'll be delivered much more quickly.\n\nTo specify encodings, provide a second argument to `app.register`:\n\n```typescript\napp.register(compression, { encodings: ['gzip', 'deflate'] });\n```\n\nThe above tells `fastify-compress` to only use gzip and deflate encodings, preferring gzip if the client supports both.\n"
  },
  {
    "path": "content/techniques/configuration.md",
    "content": "### Configuration\n\nApplications often run in different **environments**. Depending on the environment, different configuration settings should be used. For example, usually the local environment relies on specific database credentials, valid only for the local DB instance. The production environment would use a separate set of DB credentials. Since configuration variables change, best practice is to [store configuration variables](https://12factor.net/config) in the environment.\n\nExternally defined environment variables are visible inside Node.js through the `process.env` global. We could try to solve the problem of multiple environments by setting the environment variables separately in each environment. This can quickly get unwieldy, especially in the development and testing environments where these values need to be easily mocked and/or changed.\n\nIn Node.js applications, it's common to use `.env` files, holding key-value pairs where each key represents a particular value, to represent each environment. Running an app in different environments is then just a matter of swapping in the correct `.env` file.\n\nA good approach for using this technique in Nest is to create a `ConfigModule` that exposes a `ConfigService` which loads the appropriate `.env` file. While you may choose to write such a module yourself, for convenience Nest provides the `@nestjs/config` package out-of-the box. We'll cover this package in the current chapter.\n\n#### Installation\n\nTo begin using it, we first install the required dependency.\n\n```bash\n$ npm i --save @nestjs/config\n```\n\n> info **Hint** The `@nestjs/config` package internally uses [dotenv](https://github.com/motdotla/dotenv).\n\n> warning **Note** `@nestjs/config` requires TypeScript 4.1 or later.\n\n#### Getting started\n\nOnce the installation process is complete, we can import the `ConfigModule`. Typically, we'll import it into the root `AppModule` and control its behavior using the `.forRoot()` static method. During this step, environment variable key/value pairs are parsed and resolved. Later, we'll see several options for accessing the `ConfigService` class of the `ConfigModule` in our other feature modules.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { ConfigModule } from '@nestjs/config';\n\n@Module({\n  imports: [ConfigModule.forRoot()],\n})\nexport class AppModule {}\n```\n\nThe above code will load and parse a `.env` file from the default location (the project root directory), merge key/value pairs from the `.env` file with environment variables assigned to `process.env`, and store the result in a private structure that you can access through the `ConfigService`. The `forRoot()` method registers the `ConfigService` provider, which provides a `get()` method for reading these parsed/merged configuration variables. Since `@nestjs/config` relies on [dotenv](https://github.com/motdotla/dotenv), it uses that package's rules for resolving conflicts in environment variable names. When a key exists both in the runtime environment as an environment variable (e.g., via OS shell exports like `export DATABASE_USER=test`) and in a `.env` file, the runtime environment variable takes precedence.\n\nA sample `.env` file looks something like this:\n\n```json\nDATABASE_USER=test\nDATABASE_PASSWORD=test\n```\n\n#### Custom env file path\n\nBy default, the package looks for a `.env` file in the root directory of the application. To specify another path for the `.env` file, set the `envFilePath` property of an (optional) options object you pass to `forRoot()`, as follows:\n\n```typescript\nConfigModule.forRoot({\n  envFilePath: '.development.env',\n});\n```\n\nYou can also specify multiple paths for `.env` files like this:\n\n```typescript\nConfigModule.forRoot({\n  envFilePath: ['.env.development.local', '.env.development'],\n});\n```\n\nIf a variable is found in multiple files, the first one takes precedence.\n\n#### Disable env variables loading\n\nIf you don't want to load the `.env` file, but instead would like to simply access environment variables from the runtime environment (as with OS shell exports like `export DATABASE_USER=test`), set the options object's `ignoreEnvFile` property to `true`, as follows:\n\n```typescript\nConfigModule.forRoot({\n  ignoreEnvFile: true,\n});\n```\n\n#### Use module globally\n\nWhen you want to use `ConfigModule` in other modules, you'll need to import it (as is standard with any Nest module). Alternatively, declare it as a [global module](https://docs.nestjs.com/modules#global-modules) by setting the options object's `isGlobal` property to `true`, as shown below. In that case, you will not need to import `ConfigModule` in other modules once it's been loaded in the root module (e.g., `AppModule`).\n\n```typescript\nConfigModule.forRoot({\n  isGlobal: true,\n});\n```\n\n#### Custom configuration files\n\nFor more complex projects, you may utilize custom configuration files to return nested configuration objects. This allows you to group related configuration settings by function (e.g., database-related settings), and to store related settings in individual files to help manage them independently.\n\nA custom configuration file exports a factory function that returns a configuration object. The configuration object can be any arbitrarily nested plain JavaScript object. The `process.env` object will contain the fully resolved environment variable key/value pairs (with `.env` file and externally defined variables resolved and merged as described <a href=\"techniques/configuration#getting-started\">above</a>). Since you control the returned configuration object, you can add any required logic to cast values to an appropriate type, set default values, etc. For example:\n\n```typescript\n@@filename(config/configuration)\nexport default () => ({\n  port: parseInt(process.env.PORT, 10) || 3000,\n  database: {\n    host: process.env.DATABASE_HOST,\n    port: parseInt(process.env.DATABASE_PORT, 10) || 5432\n  }\n});\n```\n\nWe load this file using the `load` property of the options object we pass to the `ConfigModule.forRoot()` method:\n\n```typescript\nimport configuration from './config/configuration';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      load: [configuration],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n> info **Notice** The value assigned to the `load` property is an array, allowing you to load multiple configuration files (e.g. `load: [databaseConfig, authConfig]`)\n\nWith custom configuration files, we can also manage custom files such as YAML files. Here is an example of a configuration using YAML format:\n\n```yaml\nhttp:\n  host: 'localhost'\n  port: 8080\n\ndb:\n  postgres:\n    url: 'localhost'\n    port: 5432\n    database: 'yaml-db'\n\n  sqlite:\n    database: 'sqlite.db'\n```\n\nTo read and parse YAML files, we can leverage the `js-yaml` package.\n\n```bash\n$ npm i js-yaml\n$ npm i -D @types/js-yaml\n```\n\nOnce the package is installed, we use `yaml#load` function to load YAML file we just created above.\n\n```typescript\n@@filename(config/configuration)\nimport { readFileSync } from 'fs';\nimport * as yaml from 'js-yaml';\nimport { join } from 'path';\n\nconst YAML_CONFIG_FILENAME = 'config.yaml';\n\nexport default () => {\n  return yaml.load(\n    readFileSync(join(__dirname, YAML_CONFIG_FILENAME), 'utf8'),\n  ) as Record<string, any>;\n};\n```\n\n> warning **Note** Nest CLI does not automatically move your \"assets\" (non-TS files) to the `dist` folder during the build process. To make sure that your YAML files are copied, you have to specify this in the `compilerOptions#assets` object in the `nest-cli.json` file. As an example, if the `config` folder is at the same level as the `src` folder, add `compilerOptions#assets` with the value `\"assets\": [{{ '{' }}\"include\": \"../config/*.yaml\", \"outDir\": \"./dist/config\"{{ '}' }}]`. Read more [here](/cli/monorepo#assets).\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Using the `ConfigService`\n\nTo access configuration values from our `ConfigService`, we first need to inject `ConfigService`. As with any provider, we need to import its containing module - the `ConfigModule` - into the module that will use it (unless you set the `isGlobal` property in the options object passed to the `ConfigModule.forRoot()` method to `true`). Import it into a feature module as shown below.\n\n```typescript\n@@filename(feature.module)\n@Module({\n  imports: [ConfigModule],\n  // ...\n})\n```\n\nThen we can inject it using standard constructor injection:\n\n```typescript\nconstructor(private configService: ConfigService) {}\n```\n\n> info **Hint** The `ConfigService` is imported from the `@nestjs/config` package.\n\nAnd use it in our class:\n\n```typescript\n// get an environment variable\nconst dbUser = this.configService.get<string>('DATABASE_USER');\n\n// get a custom configuration value\nconst dbHost = this.configService.get<string>('database.host');\n```\n\nAs shown above, use the `configService.get()` method to get a simple environment variable by passing the variable name. You can do TypeScript type hinting by passing the type, as shown above (e.g., `get<string>(...)`). The `get()` method can also traverse a nested custom configuration object (created via a <a href=\"techniques/configuration#custom-configuration-files\">Custom configuration file</a>), as shown in the second example above.\n\nYou can also get the whole nested custom configuration object using an interface as the type hint:\n\n```typescript\ninterface DatabaseConfig {\n  host: string;\n  port: number;\n}\n\nconst dbConfig = this.configService.get<DatabaseConfig>('database');\n\n// you can now use `dbConfig.port` and `dbConfig.host`\nconst port = dbConfig.port;\n```\n\nThe `get()` method also takes an optional second argument defining a default value, which will be returned when the key doesn't exist, as shown below:\n\n```typescript\n// use \"localhost\" when \"database.host\" is not defined\nconst dbHost = this.configService.get<string>('database.host', 'localhost');\n```\n\n`ConfigService` has two optional generics (type arguments). The first one is to help prevent accessing a config property that does not exist. Use it as shown below:\n\n```typescript\ninterface EnvironmentVariables {\n  PORT: number;\n  TIMEOUT: string;\n}\n\n// somewhere in the code\nconstructor(private configService: ConfigService<EnvironmentVariables>) {\n  const port = this.configService.get('PORT', { infer: true });\n\n  // TypeScript Error: this is invalid as the URL property is not defined in EnvironmentVariables\n  const url = this.configService.get('URL', { infer: true });\n}\n```\n\nWith the `infer` property set to `true`, the `ConfigService#get` method will automatically infer the property type based on the interface, so for example, `typeof port === \"number\"` (if you're not using `strictNullChecks` flag from TypeScript) since `PORT` has a `number` type in the `EnvironmentVariables` interface.\n\nAlso, with the `infer` feature, you can infer the type of a nested custom configuration object's property, even when using dot notation, as follows:\n\n```typescript\nconstructor(private configService: ConfigService<{ database: { host: string } }>) {\n  const dbHost = this.configService.get('database.host', { infer: true })!;\n  // typeof dbHost === \"string\"                                          |\n  //                                                                     +--> non-null assertion operator\n}\n```\n\nThe second generic relies on the first one, acting as a type assertion to get rid of all `undefined` types that `ConfigService`'s methods can return when `strictNullChecks` is on. For instance:\n\n```typescript\n// ...\nconstructor(private configService: ConfigService<{ PORT: number }, true>) {\n  //                                                               ^^^^\n  const port = this.configService.get('PORT', { infer: true });\n  //    ^^^ The type of port will be 'number' thus you don't need TS type assertions anymore\n}\n```\n\n#### Configuration namespaces\n\nThe `ConfigModule` allows you to define and load multiple custom configuration files, as shown in <a href=\"techniques/configuration#custom-configuration-files\">Custom configuration files</a> above. You can manage complex configuration object hierarchies with nested configuration objects as shown in that section. Alternatively, you can return a \"namespaced\" configuration object with the `registerAs()` function as follows:\n\n```typescript\n@@filename(config/database.config)\nexport default registerAs('database', () => ({\n  host: process.env.DATABASE_HOST,\n  port: process.env.DATABASE_PORT || 5432\n}));\n```\n\nAs with custom configuration files, inside your `registerAs()` factory function, the `process.env` object will contain the fully resolved environment variable key/value pairs (with `.env` file and externally defined variables resolved and merged as described <a href=\"techniques/configuration#getting-started\">above</a>).\n\n> info **Hint** The `registerAs` function is exported from the `@nestjs/config` package.\n\nLoad a namespaced configuration with the `load` property of the `forRoot()` method's options object, in the same way you load a custom configuration file:\n\n```typescript\nimport databaseConfig from './config/database.config';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      load: [databaseConfig],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nNow, to get the `host` value from the `database` namespace, use dot notation. Use `'database'` as the prefix to the property name, corresponding to the name of the namespace (passed as the first argument to the `registerAs()` function):\n\n```typescript\nconst dbHost = this.configService.get<string>('database.host');\n```\n\nA reasonable alternative is to inject the `database` namespace directly. This allows us to benefit from strong typing:\n\n```typescript\nconstructor(\n  @Inject(databaseConfig.KEY)\n  private dbConfig: ConfigType<typeof databaseConfig>,\n) {}\n```\n\n> info **Hint** The `ConfigType` is exported from the `@nestjs/config` package.\n\n#### Cache environment variables\n\nAs accessing `process.env` can be slow, you can set the `cache` property of the options object passed to `ConfigModule.forRoot()` to increase the performance of `ConfigService#get` method when it comes to variables stored in `process.env`.\n\n```typescript\nConfigModule.forRoot({\n  cache: true,\n});\n```\n\n#### Partial registration\n\nThus far, we've processed configuration files in our root module (e.g., `AppModule`), with the `forRoot()` method. Perhaps you have a more complex project structure, with feature-specific configuration files located in multiple different directories. Rather than load all these files in the root module, the `@nestjs/config` package provides a feature called **partial registration**, which references only the configuration files associated with each feature module. Use the `forFeature()` static method within a feature module to perform this partial registration, as follows:\n\n```typescript\nimport databaseConfig from './config/database.config';\n\n@Module({\n  imports: [ConfigModule.forFeature(databaseConfig)],\n})\nexport class DatabaseModule {}\n```\n\n> info **Warning** In some circumstances, you may need to access properties loaded via partial registration using the `onModuleInit()` hook, rather than in a constructor. This is because the `forFeature()` method is run during module initialization, and the order of module initialization is indeterminate. If you access values loaded this way by another module, in a constructor, the module that the configuration depends upon may not yet have initialized. The `onModuleInit()` method runs only after all modules it depends upon have been initialized, so this technique is safe.\n\n#### Schema validation\n\nIt is standard practice to throw an exception during application startup if required environment variables haven't been provided or if they don't meet certain validation rules. The `@nestjs/config` package enables two different ways to do this:\n\n- [Joi](https://github.com/sideway/joi) built-in validator. With Joi, you define an object schema and validate JavaScript objects against it.\n- A custom `validate()` function which takes environment variables as an input.\n\nTo use Joi, we must install Joi package:\n\n```bash\n$ npm install --save joi\n```\n\n> warning **Notice** The latest version of `joi` requires you to be running Node v12 or later. For older versions of node, please install `v16.1.8`. This is mainly after the release of `v17.0.2` which causes errors during build time. For more information, please refer to [their 17.0.0 release notes](https://github.com/sideway/joi/issues/2262).\n\nNow we can define a Joi validation schema and pass it via the `validationSchema` property of the `forRoot()` method's options object, as shown below:\n\n```typescript\n@@filename(app.module)\nimport * as Joi from 'joi';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      validationSchema: Joi.object({\n        NODE_ENV: Joi.string()\n          .valid('development', 'production', 'test', 'provision')\n          .default('development'),\n        PORT: Joi.number().default(3000),\n      }),\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nBy default, all schema keys are considered optional. Here, we set default values for `NODE_ENV` and `PORT` which will be used if we don't provide these variables in the environment (`.env` file or process environment). Alternatively, we can use the `required()` validation method to require that a value must be defined in the environment (`.env` file or process environment). In this case, the validation step will throw an exception if we don't provide the variable in the environment. See [Joi validation methods](https://joi.dev/api/?v=17.3.0#example) for more on how to construct validation schemas.\n\nBy default, unknown environment variables (environment variables whose keys are not present in the schema) are allowed and do not trigger a validation exception. By default, all validation errors are reported. You can alter these behaviors by passing an options object via the `validationOptions` key of the `forRoot()` options object. This options object can contain any of the standard validation options properties provided by [Joi validation options](https://joi.dev/api/?v=17.3.0#anyvalidatevalue-options). For example, to reverse the two settings above, pass options like this:\n\n```typescript\n@@filename(app.module)\nimport * as Joi from 'joi';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      validationSchema: Joi.object({\n        NODE_ENV: Joi.string()\n          .valid('development', 'production', 'test', 'provision')\n          .default('development'),\n        PORT: Joi.number().default(3000),\n      }),\n      validationOptions: {\n        allowUnknown: false,\n        abortEarly: true,\n      },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nThe `@nestjs/config` package uses default settings of:\n\n- `allowUnknown`: controls whether or not to allow unknown keys in the environment variables. Default is `true`\n- `abortEarly`: if true, stops validation on the first error; if false, returns all errors. Defaults to `false`.\n\nNote that once you decide to pass a `validationOptions` object, any settings you do not explicitly pass will default to `Joi` standard defaults (not the `@nestjs/config` defaults). For example, if you leave `allowUnknowns` unspecified in your custom `validationOptions` object, it will have the `Joi` default value of `false`. Hence, it is probably safest to specify **both** of these settings in your custom object.\n\n#### Custom validate function\n\nAlternatively, you can specify a **synchronous** `validate` function that takes an object containing the environment variables (from env file and process) and returns an object containing validated environment variables so that you can convert/mutate them if needed. If the function throws an error, it will prevent the application from bootstrapping.\n\nIn this example, we'll proceed with the `class-transformer` and `class-validator` packages. First, we have to define:\n\n- a class with validation constraints,\n- a validate function that makes use of the `plainToClass` and `validateSync` functions.\n\n```typescript\n@@filename(env.validation)\nimport { plainToClass } from 'class-transformer';\nimport { IsEnum, IsNumber, validateSync } from 'class-validator';\n\nenum Environment {\n  Development = \"development\",\n  Production = \"production\",\n  Test = \"test\",\n  Provision = \"provision\",\n}\n\nclass EnvironmentVariables {\n  @IsEnum(Environment)\n  NODE_ENV: Environment;\n\n  @IsNumber()\n  PORT: number;\n}\n\nexport function validate(config: Record<string, unknown>) {\n  const validatedConfig = plainToClass(\n    EnvironmentVariables,\n    config,\n    { enableImplicitConversion: true },\n  );\n  const errors = validateSync(validatedConfig, { skipMissingProperties: false });\n\n  if (errors.length > 0) {\n    throw new Error(errors.toString());\n  }\n  return validatedConfig;\n}\n```\n\nWith this in place, use the `validate` function as a configuration option of the `ConfigModule`, as follows:\n\n```typescript\n@@filename(app.module)\nimport { validate } from './env.validation';\n\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      validate,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n<app-banner-shop></app-banner-shop>\n\n#### Custom getter functions\n\n`ConfigService` defines a generic `get()` method to retrieve a configuration value by key. We may also add `getter` functions to enable a little more natural coding style:\n\n```typescript\n@@filename()\n@Injectable()\nexport class ApiConfigService {\n  constructor(private configService: ConfigService) {}\n\n  get isAuthEnabled(): boolean {\n    return this.configService.get('AUTH_ENABLED') === 'true';\n  }\n}\n@@switch\n@Dependencies(ConfigService)\n@Injectable()\nexport class ApiConfigService {\n  constructor(configService) {\n    this.configService = configService;\n  }\n\n  get isAuthEnabled() {\n    return this.configService.get('AUTH_ENABLED') === 'true';\n  }\n}\n```\n\nNow we can use the getter function as follows:\n\n```typescript\n@@filename(app.service)\n@Injectable()\nexport class AppService {\n  constructor(apiConfigService: ApiConfigService) {\n    if (apiConfigService.isAuthEnabled) {\n      // Authentication is enabled\n    }\n  }\n}\n@@switch\n@Dependencies(ApiConfigService)\n@Injectable()\nexport class AppService {\n  constructor(apiConfigService) {\n    if (apiConfigService.isAuthEnabled) {\n      // Authentication is enabled\n    }\n  }\n}\n```\n\n#### Expandable variables\n\nThe `@nestjs/config` package supports environment variable expansion. With this technique, you can create nested environment variables, where one variable is referred to within the definition of another. For example:\n\n```json\nAPP_URL=mywebsite.com\nSUPPORT_EMAIL=support@${APP_URL}\n```\n\nWith this construction, the variable `SUPPORT_EMAIL` resolves to `'support@mywebsite.com'`. Note the use of the `${{ '{' }}...{{ '}' }}` syntax to trigger resolving the value of the variable `APP_URL` inside the definition of `SUPPORT_EMAIL`.\n\n> info **Hint** For this feature, `@nestjs/config` package internally uses [dotenv-expand](https://github.com/motdotla/dotenv-expand).\n\nEnable environment variable expansion using the `expandVariables` property in the options object passed to the `forRoot()` method of the `ConfigModule`, as shown below:\n\n```typescript\n@@filename(app.module)\n@Module({\n  imports: [\n    ConfigModule.forRoot({\n      // ...\n      expandVariables: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n#### Using in the `main.ts`\n\nWhile our config is a stored in a service, it can still be used in the `main.ts` file. This way, you can use it to store variables such as the application port or the CORS host.\n\nTo access it, you must use the `app.get()` method, followed by the service reference:\n\n```typescript\nconst configService = app.get(ConfigService);\n```\n\nYou can then use it as usual, by calling the `get` method with the configuration key:\n\n```typescript\nconst port = configService.get('PORT');\n```\n"
  },
  {
    "path": "content/techniques/cookies.md",
    "content": "### Cookies\n\nAn **HTTP cookie** is a small piece of data stored by the user's browser. Cookies were designed to be a reliable mechanism for websites to remember stateful information. When the user visits the website again, the cookie is automatically sent with the request.\n\n#### Use with Express (default)\n\nFirst install the required package (and its types for TypeScript users):\n\n```shell\n$ npm i cookie-parser\n$ npm i -D @types/cookie-parser\n```\n\nOnce the installation is complete, apply the `cookie-parser` middleware as global middleware (for example, in your `main.ts` file).\n\n```typescript\nimport * as cookieParser from 'cookie-parser';\n// somewhere in your initialization file\napp.use(cookieParser());\n```\n\nYou can pass several options to the `cookieParser` middleware:\n\n- `secret` a string or array used for signing cookies. This is optional and if not specified, will not parse signed cookies. If a string is provided, this is used as the secret. If an array is provided, an attempt will be made to unsign the cookie with each secret in order.\n- `options` an object that is passed to `cookie.parse` as the second option. See [cookie](https://www.npmjs.org/package/cookie) for more information.\n\nThe middleware will parse the `Cookie` header on the request and expose the cookie data as the property `req.cookies` and, if a secret was provided, as the property `req.signedCookies`. These properties are name value pairs of the cookie name to cookie value.\n\nWhen secret is provided, this module will unsign and validate any signed cookie values and move those name value pairs from req.cookies into `req.signedCookies`. A signed cookie is a cookie that has a value prefixed with `s:`. Signed cookies that fail signature validation will have the value `false` instead of the tampered value.\n\nWith this in place, you can now read cookies from within the route handlers, as follows:\n\n```typescript\n@Get()\nfindAll(@Req() request: Request) {\n  console.log(request.cookies); // or \"request.cookies['cookieKey']\"\n  // or console.log(request.signedCookies);\n}\n```\n\n> info **Hint** The `@Req()` decorator is imported from the `@nestjs/common`, while `Request` from the `express` package.\n\nTo attach a cookie to an outgoing response, use the `Response#cookie()` method:\n\n```typescript\n@Get()\nfindAll(@Res({ passthrough: true }) response: Response) {\n  response.cookie('key', 'value')\n}\n```\n\n> warning **Warning** If you want to leave the response handling logic to the framework, remember to set the `passthrough` option to `true`, as shown above. Read more [here](/controllers#appendix-library-specific-approach).\n\n> info **Hint** The `@Res()` decorator is imported from the `@nestjs/common`, while `Response` from the `express` package.\n\n#### Use with Fastify\n\nFirst install the required package:\n\n```shell\n$ npm i fastify-cookie\n```\n\nOnce the installation is complete, register the `fastify-cookie` plugin:\n\n```typescript\nimport fastifyCookie from 'fastify-cookie';\n\n// somewhere in your initialization file\nconst app = await NestFactory.create<NestFastifyApplication>(\n  AppModule,\n  new FastifyAdapter(),\n);\napp.register(fastifyCookie, {\n  secret: 'my-secret', // for cookies signature\n});\n```\n\nWith this in place, you can now read cookies from within the route handlers, as follows:\n\n```typescript\n@Get()\nfindAll(@Req() request: FastifyRequest) {\n  console.log(request.cookies); // or \"request.cookies['cookieKey']\"\n}\n```\n\n> info **Hint** The `@Req()` decorator is imported from the `@nestjs/common`, while `FastifyRequest` from the `fastify` package.\n\nTo attach a cookie to an outgoing response, use the `FastifyReply#setCookie()` method:\n\n```typescript\n@Get()\nfindAll(@Res({ passthrough: true }) response: FastifyReply) {\n  response.setCookie('key', 'value')\n}\n```\n\nTo read more about `FastifyReply#setCookie()` method, check out this [page](https://github.com/fastify/fastify-cookie#sending).\n\n> warning **Warning** If you want to leave the response handling logic to the framework, remember to set the `passthrough` option to `true`, as shown above. Read more [here](/controllers#appendix-library-specific-approach).\n\n> info **Hint** The `@Res()` decorator is imported from the `@nestjs/common`, while `FastifyReply` from the `fastify` package.\n\n#### Creating a custom decorator (cross-platform)\n\nTo provide a convenient, declarative way of accessing incoming cookies, we can create a [custom decorator](/custom-decorators).\n\n```typescript\nimport { createParamDecorator, ExecutionContext } from '@nestjs/common';\n\nexport const Cookies = createParamDecorator(\n  (data: string, ctx: ExecutionContext) => {\n    const request = ctx.switchToHttp().getRequest();\n    return data ? request.cookies?.[data] : request.cookies;\n  },\n);\n```\n\nThe `@Cookies()` decorator will extract all cookies, or a named cookie from the `req.cookies` object and populate the decorated parameter with that value.\n\nWith this in place, we can now use the decorator in a route handler signature, as follows:\n\n```typescript\n@Get()\nfindAll(@Cookies('name') name: string) {}\n```\n"
  },
  {
    "path": "content/techniques/events.md",
    "content": "### Events\n\n[Event Emitter](https://www.npmjs.com/package/@nestjs/event-emitter) package (`@nestjs/event-emitter`) provides a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other.\n\n`EventEmitterModule` internally uses the [eventemitter2](https://github.com/EventEmitter2/EventEmitter2) package.\n\n#### Getting started\n\nFirst install the required package:\n\n```shell\n$ npm i --save @nestjs/event-emitter\n```\n\nOnce the installation is complete, import the `EventEmitterModule` into the root `AppModule` and run the `forRoot()` static method as shown below:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { EventEmitterModule } from '@nestjs/event-emitter';\n\n@Module({\n  imports: [\n    EventEmitterModule.forRoot()\n  ],\n})\nexport class AppModule {}\n```\n\nThe `.forRoot()` call initializes the event emitter and registers any declarative event listeners that exist within your app. Registration occurs when the `onApplicationBootstrap` lifecycle hook occurs, ensuring that all modules have loaded and declared any scheduled jobs.\n\nTo configure the underlying `EventEmitter` instance, pass the configuration object to the `.forRoot()` method, as follows:\n\n```typescript\nEventEmitterModule.forRoot({\n  // set this to `true` to use wildcards\n  wildcard: false,\n  // the delimiter used to segment namespaces\n  delimiter: '.',\n  // set this to `true` if you want to emit the newListener event\n  newListener: false,\n  // set this to `true` if you want to emit the removeListener event\n  removeListener: false,\n  // the maximum amount of listeners that can be assigned to an event\n  maxListeners: 10,\n  // show event name in memory leak message when more than maximum amount of listeners is assigned\n  verboseMemoryLeak: false,\n  // disable throwing uncaughtException if an error event is emitted and it has no listeners\n  ignoreErrors: false,\n});\n```\n\n#### Dispatching Events\n\nTo dispatch (i.e., fire) an event, first inject `EventEmitter2` using standard constructor injection:\n\n```typescript\nconstructor(private eventEmitter: EventEmitter2) {}\n```\n\n> info **Hint** Import the `EventEmitter2` from the `@nestjs/event-emitter` package.\n\nThen use it in a class as follows:\n\n```typescript\nthis.eventEmitter.emit(\n  'order.created',\n  new OrderCreatedEvent({\n    orderId: 1,\n    payload: {},\n  }),\n);\n```\n\n#### Listening to Events\n\nTo declare an event listener, decorate a method with the `@OnEvent()` decorator preceding the method definition containing the code to be executed, as follows:\n\n```typescript\n@OnEvent('order.created')\nhandleOrderCreatedEvent(payload: OrderCreatedEvent) {\n  // handle and process \"OrderCreatedEvent\" event\n}\n```\n\n> warning **Warning** Event subscribers cannot be request-scoped.\n\nThe first argument can be a `string` or `symbol` for a simple event emitter and a `string | symbol | Array<string | symbol>` in a case of a wildcard emitter. The second argument (optional) is a listener options object ([read more](https://github.com/EventEmitter2/EventEmitter2#emitteronevent-listener-options-objectboolean)).\n\n```typescript\n@OnEvent('order.created', { async: true })\nhandleOrderCreatedEvent(payload: OrderCreatedEvent) {\n  // handle and process \"OrderCreatedEvent\" event\n}\n```\n\nTo use namespaces/wildcards, pass the `wildcard` option into the `EventEmitterModule#forRoot()` method. When namespaces/wildcards are enabled, events can either be strings (`foo.bar`) separated by a delimiter or arrays (`['foo', 'bar']`). The delimiter is also configurable as a configuration property (`delimiter`). With namespaces feature enabled, you can subscribe to events using a wildcard:\n\n```typescript\n@OnEvent('order.*')\nhandleOrderEvents(payload: OrderCreatedEvent | OrderRemovedEvent | OrderUpdatedEvent) {\n  // handle and process an event\n}\n```\n\nNote that such a wildcard only applies to one block. The argument `order.*` will match, for example, the events `order.created` and `order.shipped` but not `order.delayed.out_of_stock`. In order to listen to such events,\nuse the `multilevel wildcard` pattern (i.e, `**`), described in the `EventEmitter2` [documentation](https://github.com/EventEmitter2/EventEmitter2#multi-level-wildcards).\n\nWith this pattern, you can, for example, create an event listener that catches all events.\n\n```typescript\n@OnEvent('**')\nhandleEverything(payload: any) {\n  // handle and process an event\n}\n```\n\n> info **Hint** `EventEmitter2` class provides several useful methods for interacting with events, like `waitFor` and `onAny`. You can read more about them [here](https://github.com/EventEmitter2/EventEmitter2).\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/30-event-emitter).\n"
  },
  {
    "path": "content/techniques/file-upload.md",
    "content": "### 파일 업로드\n\n파일 업로드를 처리하기 위해, 네스트는 익스프레스의 미들웨어인 [multer](https://github.com/expressjs/multer) 에 기반한 빌트인 모듈을 제공합니다. Multer는 HTTP POST 요청을 통해 파일을 업로드 할 때 자주 사용되는 `multipart/form-data` 형식으로 전송된 데이터를 다룹니다. 이 모듈은 사용자의 어플리케이션에 맞게 옵션을 설정하여 사용할 수 있습니다.\n\n> warning **주의** Multer는 (`multipart/form-data`) 형식을 지원하지 않는 데이터를 처리할 수 없습니다. 또한, 이 패키지는 `FastifyAdapter`와 호환이 되지 않는 것을 명심하세요.\n\n더 나은 타입 안정성을 위해, Multer 타입 패키지를 설치합니다:\n\n```shell\n$ npm i -D @types/multer\n```\n\n이 패키지를 설치함으로써, 우리는 `Express.Multer.File` 타입을 사용할 수 있습니다. (다음과 같이 타입을 임포트할 수 있습니다 `import {{ '{' }} Express {{ '}' }} from 'express'`).\n\n#### 기본 예제\n\n단일 파일을 업로드하기 위해, `FileInterceptor()` 인터셉터를 라우트 핸들러에 연결하고 `@UploadedFile()` 데코레이터를 이용하여 `request` 로 부터 `파일`을 추출합니다.\n\n```typescript\n@@filename()\n@Post('upload')\n@UseInterceptors(FileInterceptor('file'))\nuploadFile(@UploadedFile() file: Express.Multer.File) {\n  console.log(file);\n}\n@@switch\n@Post('upload')\n@UseInterceptors(FileInterceptor('file'))\n@Bind(UploadedFile())\nuploadFile(file) {\n  console.log(file);\n}\n```\n\n> info **힌트** `FileInterceptor()` 데코레이터는 `@nestjs/platform-express` 패키지에서 export 됩니다. The `@UploadedFile()` 데코레이터는 `@nestjs/common` 패키지에서 export 됩니다.\n\n`FileInterceptor()` 데코레이터는 2개의 인수를 받습니다:\n\n- `fieldName`: 파일이 있는 HTML form에서 제공하는 필드 이름\n- `options`: (선택적) `MulterOptions` 타입의 객체입니다. multer 생성자에서 사용되는 것과 같은 객체입니다. (자세히 알아보기 [여기](https://github.com/expressjs/multer#multeropts)).\n\n> warning **주의** `FileInterceptor()` 는 Google Firebase 등의 타사 클라우드 공급자와 호환되지 않을 수 있습니다.\n\n#### 파일 배열\n\n파일로 이루어진 배열을 업로드 하기 위해 (하나의 필드 이름으로 되어있는), `FilesInterceptor()` 데코레이터를 사용합니다. (데코레이터의 이름이 Files인 것을 확인하세요). 이 데코레이터는 3개의 인수를 받습니다:\n\n- `fieldName`: 위의 설명과 동일합니다.\n- `maxCount`: (선택적) 허용 할 최대 파일의 수\n- `options`: (선택적) `MulterOptions` 객체, 위의 설명과 동일합니다.\n\n`FilesInterceptor()` 를 사용할 때 , `@UploadedFiles()` 데코레이터를 이용하여 `request` 로 부터 파일들을 추출합니다 .\n\n```typescript\n@@filename()\n@Post('upload')\n@UseInterceptors(FilesInterceptor('files'))\nuploadFile(@UploadedFiles() files: Array<Express.Multer.File>) {\n  console.log(files);\n}\n@@switch\n@Post('upload')\n@UseInterceptors(FilesInterceptor('files'))\n@Bind(UploadedFiles())\nuploadFile(files) {\n  console.log(files);\n}\n```\n\n> info **힌트** `FilesInterceptor()` 데코레이터는 `@nestjs/platform-express` 패키지에서 export 됩니다. The `@UploadedFiles()` 데코레이터는 `@nestjs/common` 패키지에서 export 됩니다.\n\n#### Multiple files\n\nTo upload multiple fields (all with different field name keys), use the `FileFieldsInterceptor()` decorator. This decorator takes two arguments:\n\n- `uploadedFields`: an array of objects, where each object specifies a required `name` property with a string value specifying a field name, as described above, and an optional `maxCount` property, as described above\n- `options`: optional `MulterOptions` object, as described above\n\nWhen using `FileFieldsInterceptor()`, extract files from the `request` with the `@UploadedFiles()` decorator.\n\n```typescript\n@@filename()\n@Post('upload')\n@UseInterceptors(FileFieldsInterceptor([\n  { name: 'avatar', maxCount: 1 },\n  { name: 'background', maxCount: 1 },\n]))\nuploadFile(@UploadedFiles() files: { avatar?: Express.Multer.File[], background?: Express.Multer.File[] }) {\n  console.log(files);\n}\n@@switch\n@Post('upload')\n@Bind(UploadedFiles())\n@UseInterceptors(FileFieldsInterceptor([\n  { name: 'avatar', maxCount: 1 },\n  { name: 'background', maxCount: 1 },\n]))\nuploadFile(files) {\n  console.log(files);\n}\n```\n\n#### Any files\n\nTo upload all fields with arbitrary field name keys, use the `AnyFilesInterceptor()` decorator. This decorator can accept an optional `options` object as described above.\n\nWhen using `AnyFilesInterceptor()`, extract files from the `request` with the `@UploadedFiles()` decorator.\n\n```typescript\n@@filename()\n@Post('upload')\n@UseInterceptors(AnyFilesInterceptor())\nuploadFile(@UploadedFiles() files: Array<Express.Multer.File>) {\n  console.log(files);\n}\n@@switch\n@Post('upload')\n@Bind(UploadedFiles())\n@UseInterceptors(AnyFilesInterceptor())\nuploadFile(files) {\n  console.log(files);\n}\n```\n\n#### Default options\n\nYou can specify multer options in the file interceptors as described above. To set default options, you can call the static `register()` method when you import the `MulterModule`, passing in supported options. You can use all options listed [here](https://github.com/expressjs/multer#multeropts).\n\n```typescript\nMulterModule.register({\n  dest: './upload',\n});\n```\n\n> info **Hint** The `MulterModule` class is exported from the `@nestjs/platform-express` package.\n\n#### Async configuration\n\nWhen you need to set `MulterModule` options asynchronously instead of statically, use the `registerAsync()` method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.\n\nOne technique is to use a factory function:\n\n```typescript\nMulterModule.registerAsync({\n  useFactory: () => ({\n    dest: './upload',\n  }),\n});\n```\n\nLike other [factory providers](https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory), our factory function can be `async` and can inject dependencies through `inject`.\n\n```typescript\nMulterModule.registerAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    dest: configService.getString('MULTER_DEST'),\n  }),\n  inject: [ConfigService],\n});\n```\n\nAlternatively, you can configure the `MulterModule` using a class instead of a factory, as shown below:\n\n```typescript\nMulterModule.registerAsync({\n  useClass: MulterConfigService,\n});\n```\n\nThe construction above instantiates `MulterConfigService` inside `MulterModule`, using it to create the required options object. Note that in this example, the `MulterConfigService` has to implement the `MulterOptionsFactory` interface, as shown below. The `MulterModule` will call the `createMulterOptions()` method on the instantiated object of the supplied class.\n\n```typescript\n@Injectable()\nclass MulterConfigService implements MulterOptionsFactory {\n  createMulterOptions(): MulterModuleOptions {\n    return {\n      dest: './upload',\n    };\n  }\n}\n```\n\nIf you want to reuse an existing options provider instead of creating a private copy inside the `MulterModule`, use the `useExisting` syntax.\n\n```typescript\nMulterModule.registerAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n});\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/29-file-upload).\n"
  },
  {
    "path": "content/techniques/http-module.md",
    "content": "### HTTP module\n\n[Axios](https://github.com/axios/axios) is richly featured HTTP client package that is widely used. Nest wraps Axios and exposes it via the built-in `HttpModule`. The `HttpModule` exports the `HttpService` class, which exposes Axios-based methods to perform HTTP requests. The library also transforms the resulting HTTP responses into `Observables`.\n\n> info **Hint** You can also use any general purpose Node.js HTTP client library directly, including [got](https://github.com/sindresorhus/got) or [undici](https://github.com/nodejs/undici).\n\n#### Installation\n\nTo begin using it, we first install the required dependency.\n\n```bash\n$ npm i --save @nestjs/axios\n```\n\n#### Getting started\n\nOnce the installation process is complete, to use the `HttpService`, first import `HttpModule`.\n\n```typescript\n@Module({\n  imports: [HttpModule],\n  providers: [CatsService],\n})\nexport class CatsModule {}\n```\n\nNext, inject `HttpService` using normal constructor injection.\n\n> info **Hint** `HttpModule` and `HttpService` are imported from `@nestjs/axios` package.\n\n```typescript\n@@filename()\n@Injectable()\nexport class CatsService {\n  constructor(private httpService: HttpService) {}\n\n  findAll(): Observable<AxiosResponse<Cat[]>> {\n    return this.httpService.get('http://localhost:3000/cats');\n  }\n}\n@@switch\n@Injectable()\n@Dependencies(HttpService)\nexport class CatsService {\n  constructor(httpService) {\n    this.httpService = httpService;\n  }\n\n  findAll() {\n    return this.httpService.get('http://localhost:3000/cats');\n  }\n}\n```\n\n> info **Hint** `AxiosResponse` is an interface exported from the `axios` package (`$ npm i axios`). \n\nAll `HttpService` methods return an `AxiosResponse` wrapped in an `Observable` object.\n\n#### Configuration\n\n[Axios](https://github.com/axios/axios) can be configured with a variety of options to customize the behavior of the `HttpService`. Read more about them [here](https://github.com/axios/axios#request-config). To configure the underlying Axios instance, pass an optional options object to the `register()` method of `HttpModule` when importing it. This options object will be passed directly to the underlying Axios constructor.\n\n```typescript\n@Module({\n  imports: [\n    HttpModule.register({\n      timeout: 5000,\n      maxRedirects: 5,\n    }),\n  ],\n  providers: [CatsService],\n})\nexport class CatsModule {}\n```\n\n#### Async configuration\n\nWhen you need to pass module options asynchronously instead of statically, use the `registerAsync()` method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.\n\nOne technique is to use a factory function:\n\n```typescript\nHttpModule.registerAsync({\n  useFactory: () => ({\n    timeout: 5000,\n    maxRedirects: 5,\n  }),\n});\n```\n\nLike other factory providers, our factory function can be [async](https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory) and can inject dependencies through `inject`.\n\n```typescript\nHttpModule.registerAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    timeout: configService.get('HTTP_TIMEOUT'),\n    maxRedirects: configService.get('HTTP_MAX_REDIRECTS'),\n  }),\n  inject: [ConfigService],\n});\n```\n\nAlternatively, you can configure the `HttpModule` using a class instead of a factory, as shown below.\n\n```typescript\nHttpModule.registerAsync({\n  useClass: HttpConfigService,\n});\n```\n\nThe construction above instantiates `HttpConfigService` inside `HttpModule`, using it to create an options object. Note that in this example, the `HttpConfigService` has to implement `HttpModuleOptionsFactory` interface as shown below. The `HttpModule` will call the `createHttpOptions()` method on the instantiated object of the supplied class.\n\n```typescript\n@Injectable()\nclass HttpConfigService implements HttpModuleOptionsFactory {\n  createHttpOptions(): HttpModuleOptions {\n    return {\n      timeout: 5000,\n      maxRedirects: 5,\n    };\n  }\n}\n```\n\nIf you want to reuse an existing options provider instead of creating a private copy inside the `HttpModule`, use the `useExisting` syntax.\n\n```typescript\nHttpModule.registerAsync({\n  imports: [ConfigModule],\n  useExisting: HttpConfigService,\n});\n```\n"
  },
  {
    "path": "content/techniques/logger.md",
    "content": "### Logger\n\nNest comes with a built-in text-based logger which is used during application bootstrapping and several other circumstances such as displaying caught exceptions (i.e., system logging). This functionality is provided via the `Logger` class in the `@nestjs/common` package. You can fully control the behavior of the logging system, including any of the following:\n\n- disable logging entirely\n- specify the log level of detail (e.g., display errors, warnings, debug information, etc.)\n- override timestamp in the default logger (e.g., use ISO8601 standard as date format)\n- completely override the default logger\n- customize the default logger by extending it\n- make use of dependency injection to simplify composing and testing your application\n\nYou can also make use of the built-in logger, or create your own custom implementation, to log your own application-level events and messages.\n\nFor more advanced logging functionality, you can make use of any Node.js logging package, such as [Winston](https://github.com/winstonjs/winston), to implement a completely custom, production grade logging system.\n\n#### Basic customization\n\nTo disable logging, set the `logger` property to `false` in the (optional) Nest application options object passed as the second argument to the `NestFactory.create()` method.\n\n```typescript\nconst app = await NestFactory.create(AppModule, {\n  logger: false,\n});\nawait app.listen(3000);\n```\n\nTo enable specific logging levels, set the `logger` property to an array of strings specifying the log levels to display, as follows:\n\n```typescript\nconst app = await NestFactory.create(AppModule, {\n  logger: ['error', 'warn'],\n});\nawait app.listen(3000);\n```\n\nValues in the array can be any combination of `'log'`, `'error'`, `'warn'`, `'debug'`, and `'verbose'`.\n\n> info **Hint** To disable color in the default logger's messages, set the `NO_COLOR` environment variable to some non-empty string.\n\n#### Custom implementation\n\nYou can provide a custom logger implementation to be used by Nest for system logging by setting the value of the `logger` property to an object that fulfills the `LoggerService` interface. For example, you can tell Nest to use the built-in global JavaScript `console` object (which implements the `LoggerService` interface), as follows:\n\n```typescript\nconst app = await NestFactory.create(AppModule, {\n  logger: console,\n});\nawait app.listen(3000);\n```\n\nImplementing your own custom logger is straightforward. Simply implement each of the methods of the `LoggerService` interface as shown below.\n\n```typescript\nimport { LoggerService } from '@nestjs/common';\n\nexport class MyLogger implements LoggerService {\n  /**\n   * Write a 'log' level log.\n   */\n  log(message: any, ...optionalParams: any[]) {}\n\n  /**\n   * Write an 'error' level log.\n   */\n  error(message: any, ...optionalParams: any[]) {}\n\n  /**\n   * Write a 'warn' level log.\n   */\n  warn(message: any, ...optionalParams: any[]) {}\n\n  /**\n   * Write a 'debug' level log.\n   */\n  debug?(message: any, ...optionalParams: any[]) {}\n\n  /**\n   * Write a 'verbose' level log.\n   */\n  verbose?(message: any, ...optionalParams: any[]) {}\n}\n```\n\nYou can then supply an instance of `MyLogger` via the `logger` property of the Nest application options object.\n\n```typescript\nconst app = await NestFactory.create(AppModule, {\n  logger: new MyLogger(),\n});\nawait app.listen(3000);\n```\n\nThis technique, while simple, doesn't utilize dependency injection for the `MyLogger` class. This can pose some challenges, particularly for testing, and limit the reusability of `MyLogger`. For a better solution, see the <a href=\"techniques/logger#dependency-injection\">Dependency Injection</a> section below.\n\n#### Extend built-in logger\n\nRather than writing a logger from scratch, you may be able to meet your needs by extending the built-in `ConsoleLogger` class and overriding selected behavior of the default implementation.\n\n```typescript\nimport { ConsoleLogger } from '@nestjs/common';\n\nexport class MyLogger extends ConsoleLogger {\n  error(message: any, stack?: string, context?: string) {\n    // add your tailored logic here\n    super.error(...arguments);\n  }\n}\n```\n\nYou can use such an extended logger in your feature modules as described in the <a href=\"techniques/logger#using-the-logger-for-application-logging\">Using the logger for application logging</a> section below.\n\nYou can tell Nest to use your extended logger for system logging by passing an instance of it via the `logger` property of the application options object (as shown in the <a href=\"techniques/logger#custom-logger-implementation\">Custom implementation</a> section above), or by using the technique shown in the <a href=\"techniques/logger#dependency-injection\">Dependency Injection</a> section below. If you do so, you should take care to call `super`, as shown in the sample code above, to delegate the specific log method call to the parent (built-in) class so that Nest can rely on the built-in features it expects.\n\n<app-banner-courses></app-banner-courses>\n\n#### Dependency injection\n\nFor more advanced logging functionality, you'll want to take advantage of dependency injection. For example, you may want to inject a `ConfigService` into your logger to customize it, and in turn inject your custom logger into other controllers and/or providers. To enable dependency injection for your custom logger, create a class that implements `LoggerService` and register that class as a provider in some module. For example, you can\n\n1. Define a `MyLogger` class that either extends the built-in `ConsoleLogger` or completely overrides it, as shown in previous sections. Be sure to implement the `LoggerService` interface.\n2. Create a `LoggerModule` as shown below, and provide `MyLogger` from that module.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { MyLogger } from './my-logger.service';\n\n@Module({\n  providers: [MyLogger],\n  exports: [MyLogger],\n})\nexport class LoggerModule {}\n```\n\nWith this construct, you are now providing your custom logger for use by any other module. Because your `MyLogger` class is part of a module, it can use dependency injection (for example, to inject a `ConfigService`). There's one more technique needed to provide this custom logger for use by Nest for system logging (e.g., for bootstrapping and error handling).\n\nBecause application instantiation (`NestFactory.create()`) happens outside the context of any module, it doesn't participate in the normal Dependency Injection phase of initialization. So we must ensure that at least one application module imports the `LoggerModule` to trigger Nest to instantiate a singleton instance of our `MyLogger` class.\n\nWe can then instruct Nest to use the same singleton instance of `MyLogger` with the following construction:\n\n```typescript\nconst app = await NestFactory.create(ApplicationModule, {\n  bufferLogs: true,\n});\napp.useLogger(app.get(MyLogger));\nawait app.listen(3000);\n```\n\n> info **Note** In the example above, we set the `bufferLogs` to `true` to make sure all logs will be buffered until a custom logger is attached (`MyLogger` in this case) and the application initialisation process either completes or fails. If the initialisation process fails, Nest will fallback to the original `ConsoleLogger` to print out any reported error messages. Also, you can set the `autoFlushLogs` to `false` (default `true`) to manually flush logs (using the `Logger#flush()` method).\n\nHere we use the `get()` method on the `NestApplication` instance to retrieve the singleton instance of the `MyLogger` object. This technique is essentially a way to \"inject\" an instance of a logger for use by Nest. The `app.get()` call retrieves the singleton instance of `MyLogger`, and depends on that instance being first injected in another module, as described above.\n\nYou can also inject this `MyLogger` provider in your feature classes, thus ensuring consistent logging behavior across both Nest system logging and application logging. See <a href=\"techniques/logger#using-the-logger-for-application-logging\">Using the logger for application logging</a> and <a href=\"techniques/logger#injecting-a-custom-logger\">Injecting a custom logger</a> below for more information.\n\n#### Using the logger for application logging\n\nWe can combine several of the techniques above to provide consistent behavior and formatting across both Nest system logging and our own application event/message logging.\n\nA good practice is to instantiate `Logger` class from `@nestjs/common` in each of our services. We can supply our service name as the `context` argument in the `Logger` constructor, like so:\n\n```typescript\nimport { Logger, Injectable } from '@nestjs/common';\n\n@Injectable()\nclass MyService {\n  private readonly logger = new Logger(MyService.name);\n\n  doSomething() {\n    this.logger.log('Doing something...');\n  }\n}\n```\n\nIn the default logger implementation, `context` is printed in the square brackets, like `NestFactory` in the example below:\n\n```bash\n[Nest] 19096   - 12/08/2019, 7:12:59 AM   [NestFactory] Starting Nest application...\n```\n\nIf we supply a custom logger via `app.useLogger()`, it will actually be used by Nest internally. That means that our code remains implementation agnostic, while we can easily substitute the default logger for our custom one by calling `app.useLogger()`.\n\nThat way if we follow the steps from the previous section and call `app.useLogger(app.get(MyLogger))`, the following calls to `this.logger.log()` from `MyService` would result in calls to method `log` from `MyLogger` instance.\n\nThis should be suitable for most cases. But if you need more customization (like adding and calling custom methods), move to the next section.\n\n#### Injecting a custom logger\n\nTo start, extend the built-in logger with code like the following. We supply the `scope` option as configuration metadata for the `ConsoleLogger` class, specifying a [transient](/fundamentals/injection-scopes) scope, to ensure that we'll have a unique instance of the `MyLogger` in each feature module. In this example, we do not extend the individual `ConsoleLogger` methods (like `log()`, `warn()`, etc.), though you may choose to do so.\n\n```typescript\nimport { Injectable, Scope, ConsoleLogger } from '@nestjs/common';\n\n@Injectable({ scope: Scope.TRANSIENT })\nexport class MyLogger extends ConsoleLogger {\n  customLog() {\n    this.log('Please feed the cat!');\n  }\n}\n```\n\nNext, create a `LoggerModule` with a construction like this:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { MyLogger } from './my-logger.service';\n\n@Module({\n  providers: [MyLogger],\n  exports: [MyLogger],\n})\nexport class LoggerModule {}\n```\n\nNext, import the `LoggerModule` into your feature module. Since we extended default `Logger` we have the convenience of using `setContext` method. So we can start using the context-aware custom logger, like this:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { MyLogger } from './my-logger.service';\n\n@Injectable()\nexport class CatsService {\n  private readonly cats: Cat[] = [];\n\n  constructor(private myLogger: MyLogger) {\n    // Due to transient scope, CatsService has its own unique instance of MyLogger,\n    // so setting context here will not affect other instances in other services\n    this.myLogger.setContext('CatsService');\n  }\n\n  findAll(): Cat[] {\n    // You can call all the default methods\n    this.myLogger.warn('About to return cats!');\n    // And your custom methods\n    this.myLogger.customLog();\n    return this.cats;\n  }\n}\n```\n\nFinally, instruct Nest to use an instance of the custom logger in your `main.ts` file as shown below. Of course in this example, we haven't actually customized the logger behavior (by extending the `Logger` methods like `log()`, `warn()`, etc.), so this step isn't actually needed. But it **would** be needed if you added custom logic to those methods and wanted Nest to use the same implementation.\n\n```typescript\nconst app = await NestFactory.create(ApplicationModule, {\n  bufferLogs: true,\n});\napp.useLogger(new MyLogger());\nawait app.listen(3000);\n```\n\n> info **Hint** Alternatively, instead of setting `bufferLogs` to `true`, you could temporarily disable the logger with `logger: false` instruction. Be mindful that if you supply `logger: false` to `NestFactory.create`, nothing will be logged until you call `useLogger`, so you may miss some important initialization errors. If you don't mind that some of your initial messages will be logged with the default logger, you can just omit the `logger: false` option.\n\n#### Use external logger\n\nProduction applications often have specific logging requirements, including advanced filtering, formatting and centralized logging. Nest's built-in logger is used for monitoring Nest system behavior, and can also be useful for basic formatted text logging in your feature modules while in development, but production applications often take advantage of dedicated logging modules like [Winston](https://github.com/winstonjs/winston). As with any standard Node.js application, you can take full advantage of such modules in Nest.\n"
  },
  {
    "path": "content/techniques/mongo.md",
    "content": "### Mongo\n\nNest supports two methods for integrating with the [MongoDB](https://www.mongodb.com/) database. You can either use the built-in [TypeORM](https://github.com/typeorm/typeorm) module described [here](/techniques/database), which has a connector for MongoDB, or use [Mongoose](https://mongoosejs.com), the most popular MongoDB object modeling tool. In this chapter we'll describe the latter, using the dedicated `@nestjs/mongoose` package.\n\nStart by installing the required dependencies:\n\n```bash\n$ npm install --save @nestjs/mongoose mongoose\n```\n\nOnce the installation process is complete, we can import the `MongooseModule` into the root `AppModule`.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({\n  imports: [MongooseModule.forRoot('mongodb://localhost/nest')],\n})\nexport class AppModule {}\n```\n\nThe `forRoot()` method accepts the same configuration object as `mongoose.connect()` from the Mongoose package, as described [here](https://mongoosejs.com/docs/connections.html).\n\n#### Model injection\n\nWith Mongoose, everything is derived from a [Schema](http://mongoosejs.com/docs/guide.html). Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. Schemas are used to define [Models](https://mongoosejs.com/docs/models.html). Models are responsible for creating and reading documents from the underlying MongoDB database.\n\nSchemas can be created with NestJS decorators, or with Mongoose itself manually. Using decorators to create schemas greatly reduces boilerplate and improves overall code readability.\n\nLet's define the `CatSchema`:\n\n```typescript\n@@filename(schemas/cat.schema)\nimport { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';\nimport { Document } from 'mongoose';\n\nexport type CatDocument = Cat & Document;\n\n@Schema()\nexport class Cat {\n  @Prop()\n  name: string;\n\n  @Prop()\n  age: number;\n\n  @Prop()\n  breed: string;\n}\n\nexport const CatSchema = SchemaFactory.createForClass(Cat);\n```\n\n> info **Hint** Note you can also generate a raw schema definition using the `DefinitionsFactory` class (from the `nestjs/mongoose`). This allows you to manually modify the schema definition generated based on the metadata you provided. This is useful for certain edge-cases where it may be hard to represent everything with decorators.\n\nThe `@Schema()` decorator marks a class as a schema definition. It maps our `Cat` class to a MongoDB collection of the same name, but with an additional “s” at the end - so the final mongo collection name will be `cats`. This decorator accepts a single optional argument which is a schema options object. Think of it as the object you would normally pass as a second argument of the `mongoose.Schema` class' constructor (e.g., `new mongoose.Schema(_, options)`)). To learn more about available schema options, see [this](https://mongoosejs.com/docs/guide.html#options) chapter.\n\nThe `@Prop()` decorator defines a property in the document. For example, in the schema definition above, we defined three properties: `name`, `age`, and `breed`. The [schema types](https://mongoosejs.com/docs/schematypes.html) for these properties are automatically inferred thanks to TypeScript metadata (and reflection) capabilities. However, in more complex scenarios in which types cannot be implicitly reflected (for example, arrays or nested object structures), types must be indicated explicitly, as follows:\n\n```typescript\n@Prop([String])\ntags: string[];\n```\n\nAlternatively, the `@Prop()` decorator accepts an options object argument ([read more](https://mongoosejs.com/docs/schematypes.html#schematype-options) about the available options). With this, you can indicate whether a property is required or not, specify a default value, or mark it as immutable. For example:\n\n```typescript\n@Prop({ required: true })\nname: string;\n```\n\nIn case you want to specify relation to another model, later for populating, you can use `@Prop()` decorator as well. For example, if `Cat` has `Owner` which is stored in a different collection called `owners`, the property should have type and ref. For example:\n\n```typescript\nimport * as mongoose from 'mongoose';\nimport { Owner } from '../owners/schemas/owner.schema';\n\n// inside the class definition\n@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' })\nowner: Owner;\n```\n\nIn case there are multiple owners, your property configuration should look as follows:\n\n```typescript\n@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' }] })\nowner: Owner[];\n```\n\nFinally, the **raw** schema definition can also be passed to the decorator. This is useful when, for example, a property represents a nested object which is not defined as a class. For this, use the `raw()` function from the `@nestjs/mongoose` package, as follows:\n\n```typescript\n@Prop(raw({\n  firstName: { type: String },\n  lastName: { type: String }\n}))\ndetails: Record<string, any>;\n```\n\nAlternatively, if you prefer **not using decorators**, you can define a schema manually. For example:\n\n```typescript\nexport const CatSchema = new mongoose.Schema({\n  name: String,\n  age: Number,\n  breed: String,\n});\n```\n\nThe `cat.schema` file resides in a folder in the `cats` directory, where we also define the `CatsModule`. While you can store schema files wherever you prefer, we recommend storing them near their related **domain** objects, in the appropriate module directory.\n\nLet's look at the `CatsModule`:\n\n```typescript\n@@filename(cats.module)\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\nimport { CatsController } from './cats.controller';\nimport { CatsService } from './cats.service';\nimport { Cat, CatSchema } from './schemas/cat.schema';\n\n@Module({\n  imports: [MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }])],\n  controllers: [CatsController],\n  providers: [CatsService],\n})\nexport class CatsModule {}\n```\n\nThe `MongooseModule` provides the `forFeature()` method to configure the module, including defining which models should be registered in the current scope. If you also want to use the models in another module, add MongooseModule to the `exports` section of `CatsModule` and import `CatsModule` in the other module.\n\nOnce you've registered the schema, you can inject a `Cat` model into the `CatsService` using the `@InjectModel()` decorator:\n\n```typescript\n@@filename(cats.service)\nimport { Model } from 'mongoose';\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/mongoose';\nimport { Cat, CatDocument } from './schemas/cat.schema';\nimport { CreateCatDto } from './dto/create-cat.dto';\n\n@Injectable()\nexport class CatsService {\n  constructor(@InjectModel(Cat.name) private catModel: Model<CatDocument>) {}\n\n  async create(createCatDto: CreateCatDto): Promise<Cat> {\n    const createdCat = new this.catModel(createCatDto);\n    return createdCat.save();\n  }\n\n  async findAll(): Promise<Cat[]> {\n    return this.catModel.find().exec();\n  }\n}\n@@switch\nimport { Model } from 'mongoose';\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { getModelToken } from '@nestjs/mongoose';\nimport { Cat } from './schemas/cat.schema';\n\n@Injectable()\n@Dependencies(getModelToken(Cat.name))\nexport class CatsService {\n  constructor(catModel) {\n    this.catModel = catModel;\n  }\n\n  async create(createCatDto) {\n    const createdCat = new this.catModel(createCatDto);\n    return createdCat.save();\n  }\n\n  async findAll() {\n    return this.catModel.find().exec();\n  }\n}\n```\n\n#### Connection\n\nAt times you may need to access the native [Mongoose Connection](https://mongoosejs.com/docs/api.html#Connection) object. For example, you may want to make native API calls on the connection object. You can inject the Mongoose Connection by using the `@InjectConnection()` decorator as follows:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { InjectConnection } from '@nestjs/mongoose';\nimport { Connection } from 'mongoose';\n\n@Injectable()\nexport class CatsService {\n  constructor(@InjectConnection() private connection: Connection) {}\n}\n```\n\n#### Multiple databases\n\nSome projects require multiple database connections. This can also be achieved with this module. To work with multiple connections, first create the connections. In this case, connection naming becomes **mandatory**.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://localhost/test', {\n      connectionName: 'cats',\n    }),\n    MongooseModule.forRoot('mongodb://localhost/users', {\n      connectionName: 'users',\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n> warning **Notice** Please note that you shouldn't have multiple connections without a name, or with the same name, otherwise they will get overridden.\n\nWith this setup, you have to tell the `MongooseModule.forFeature()` function which connection should be used.\n\n```typescript\n@Module({\n  imports: [\n    MongooseModule.forFeature([{ name: Cat.name, schema: CatSchema }], 'cats'),\n  ],\n})\nexport class AppModule {}\n```\n\nYou can also inject the `Connection` for a given connection:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { InjectConnection } from '@nestjs/mongoose';\nimport { Connection } from 'mongoose';\n\n@Injectable()\nexport class CatsService {\n  constructor(@InjectConnection('cats') private connection: Connection) {}\n}\n```\n\nTo inject a given `Connection` to a custom provider (for example, factory provider), use the `getConnectionToken()` function passing the name of the connection as an argument.\n\n```typescript\n{\n  provide: CatsService,\n  useFactory: (catsConnection: Connection) => {\n    return new CatsService(catsConnection);\n  },\n  inject: [getConnectionToken('cats')],\n}\n```\n\n#### Hooks (middleware)\n\nMiddleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins ([source](https://mongoosejs.com/docs/middleware.html)). Calling `pre()` or `post()` after compiling a model does not work in Mongoose. To register a hook **before** model registration, use the `forFeatureAsync()` method of the `MongooseModule` along with a factory provider (i.e., `useFactory`). With this technique, you can access a schema object, then use the `pre()` or `post()` method to register a hook on that schema. See example below:\n\n```typescript\n@Module({\n  imports: [\n    MongooseModule.forFeatureAsync([\n      {\n        name: Cat.name,\n        useFactory: () => {\n          const schema = CatsSchema;\n          schema.pre('save', function() { console.log('Hello from pre save') });\n          return schema;\n        },\n      },\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\nLike other [factory providers](https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory), our factory function can be `async` and can inject dependencies through `inject`.\n\n```typescript\n@Module({\n  imports: [\n    MongooseModule.forFeatureAsync([\n      {\n        name: Cat.name,\n        imports: [ConfigModule],\n        useFactory: (configService: ConfigService) => {\n          const schema = CatsSchema;\n          schema.pre('save', function() {\n            console.log(\n              `${configService.get('APP_NAME')}: Hello from pre save`,\n            ),\n          });\n          return schema;\n        },\n        inject: [ConfigService],\n      },\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\n#### Plugins\n\nTo register a [plugin](https://mongoosejs.com/docs/plugins.html) for a given schema, use the `forFeatureAsync()` method.\n\n```typescript\n@Module({\n  imports: [\n    MongooseModule.forFeatureAsync([\n      {\n        name: Cat.name,\n        useFactory: () => {\n          const schema = CatsSchema;\n          schema.plugin(require('mongoose-autopopulate'));\n          return schema;\n        },\n      },\n    ]),\n  ],\n})\nexport class AppModule {}\n```\n\nTo register a plugin for all schemas at once, call the `.plugin()` method of the `Connection` object. You should access the connection before models are created; to do this, use the `connectionFactory`:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({\n  imports: [\n    MongooseModule.forRoot('mongodb://localhost/test', {\n      connectionFactory: (connection) => {\n        connection.plugin(require('mongoose-autopopulate'));\n        return connection;\n      }\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n#### Discriminators\n\n[Discriminators](https://mongoosejs.com/docs/discriminators.html) are a schema inheritance mechanism. They enable you to have multiple models with overlapping schemas on top of the same underlying MongoDB collection.\n\nSuppose you wanted to track different types of events in a single collection. Every event will have a timestamp.\n\n```typescript\n@@filename(event.schema)\n@Schema({ discriminatorKey: 'kind' })\nexport class Event {\n  @Prop({\n    type: String,\n    required: true,\n    enum: [ClickedLinkEvent.name, SignUpEvent.name],\n  })\n  kind: string;\n\n  @Prop({ type: Date, required: true })\n  time: Date;\n}\n\nexport const EventSchema = SchemaFactory.createForClass(Event);\n```\n\n> info **Hint** The way mongoose tells the difference between the different discriminator models is by the \"discriminator key\", which is `__t` by default. Mongoose adds a String path called `__t` to your schemas that it uses to track which discriminator this document is an instance of.\n> You may also use the `discriminatorKey` option to define the path for discrimination.\n\n`SignedUpEvent` and `ClickedLinkEvent` instances will be stored in the same collection as generic events.\n\nNow, let's define the `ClickedLinkEvent` class, as follows:\n\n```typescript\n@@filename(click-link-event.schema)\n@Schema()\nexport class ClickedLinkEvent {\n  kind: string;\n  time: Date;\n\n  @Prop({ type: String, required: true })\n  url: string;\n}\n\nexport const ClickedLinkEventSchema = SchemaFactory.createForClass(ClickedLinkEvent);\n```\n\nAnd `SignUpEvent` class:\n\n```typescript\n@@filename(sign-up-event.schema)\n@Schema()\nexport class SignUpEvent {\n  kind: string;\n  time: Date;\n\n  @Prop({ type: String, required: true })\n  user: string;\n}\n\nexport const SignUpEventSchema = SchemaFactory.createForClass(SignUpEvent);\n```\n\nWith this in place, use the `discriminators` option to register a discriminator for a given schema. It works on both `MongooseModule.forFeature` and `MongooseModule.forFeatureAsync`:\n\n```typescript\n@@filename(event.module)\nimport { Module } from '@nestjs/common';\nimport { MongooseModule } from '@nestjs/mongoose';\n\n@Module({\n  imports: [\n    MongooseModule.forFeature([\n      {\n        name: Event.name,\n        schema: EventSchema,\n        discriminators: [\n          { name: ClickedLinkEvent.name, schema: ClickedLinkEventSchema },\n          { name: SignUpEvent.name, schema: SignUpEventSchema },\n        ],\n      },\n    ]),\n  ]\n})\nexport class EventsModule {}\n```\n\n#### Testing\n\nWhen unit testing an application, we usually want to avoid any database connection, making our test suites simpler to set up and faster to execute. But our classes might depend on models that are pulled from the connection instance. How do we resolve these classes? The solution is to create mock models.\n\nTo make this easier, the `@nestjs/mongoose` package exposes a `getModelToken()` function that returns a prepared [injection token](https://docs.nestjs.com/fundamentals/custom-providers#di-fundamentals) based on a token name. Using this token, you can easily provide a mock implementation using any of the standard [custom provider](/fundamentals/custom-providers) techniques, including `useClass`, `useValue`, and `useFactory`. For example:\n\n```typescript\n@Module({\n  providers: [\n    CatsService,\n    {\n      provide: getModelToken(Cat.name),\n      useValue: catModel,\n    },\n  ],\n})\nexport class CatsModule {}\n```\n\nIn this example, a hardcoded `catModel` (object instance) will be provided whenever any consumer injects a `Model<Cat>` using an `@InjectModel()` decorator.\n\n<app-banner-courses></app-banner-courses>\n\n#### Async configuration\n\nWhen you need to pass module options asynchronously instead of statically, use the `forRootAsync()` method. As with most dynamic modules, Nest provides several techniques to deal with async configuration.\n\nOne technique is to use a factory function:\n\n```typescript\nMongooseModule.forRootAsync({\n  useFactory: () => ({\n    uri: 'mongodb://localhost/nest',\n  }),\n});\n```\n\nLike other [factory providers](https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory), our factory function can be `async` and can inject dependencies through `inject`.\n\n```typescript\nMongooseModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    uri: configService.get<string>('MONGODB_URI'),\n  }),\n  inject: [ConfigService],\n});\n```\n\nAlternatively, you can configure the `MongooseModule` using a class instead of a factory, as shown below:\n\n```typescript\nMongooseModule.forRootAsync({\n  useClass: MongooseConfigService,\n});\n```\n\nThe construction above instantiates `MongooseConfigService` inside `MongooseModule`, using it to create the required options object. Note that in this example, the `MongooseConfigService` has to implement the `MongooseOptionsFactory` interface, as shown below. The `MongooseModule` will call the `createMongooseOptions()` method on the instantiated object of the supplied class.\n\n```typescript\n@Injectable()\nclass MongooseConfigService implements MongooseOptionsFactory {\n  createMongooseOptions(): MongooseModuleOptions {\n    return {\n      uri: 'mongodb://localhost/nest',\n    };\n  }\n}\n```\n\nIf you want to reuse an existing options provider instead of creating a private copy inside the `MongooseModule`, use the `useExisting` syntax.\n\n```typescript\nMongooseModule.forRootAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n});\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/06-mongoose).\n"
  },
  {
    "path": "content/techniques/mvc.md",
    "content": "### Model-View-Controller\n\nNest, by default, makes use of the [Express](https://github.com/expressjs/express) library under the hood. Hence, every technique for using the MVC (Model-View-Controller) pattern in Express applies to Nest as well.\n\nFirst, let's scaffold a simple Nest application using the [CLI](https://github.com/nestjs/nest-cli) tool:\n\n```bash\n$ npm i -g @nestjs/cli\n$ nest new project\n```\n\nIn order to create an MVC app, we also need a [template engine](https://expressjs.com/en/guide/using-template-engines.html) to render our HTML views:\n\n```bash\n$ npm install --save hbs\n```\n\nWe've used the `hbs` ([Handlebars](https://github.com/pillarjs/hbs#readme)) engine, though you can use whatever fits your requirements. Once the installation process is complete, we need to configure the express instance using the following code:\n\n```typescript\n@@filename(main)\nimport { NestFactory } from '@nestjs/core';\nimport { NestExpressApplication } from '@nestjs/platform-express';\nimport { join } from 'path';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestExpressApplication>(\n    AppModule,\n  );\n\n  app.useStaticAssets(join(__dirname, '..', 'public'));\n  app.setBaseViewsDir(join(__dirname, '..', 'views'));\n  app.setViewEngine('hbs');\n\n  await app.listen(3000);\n}\nbootstrap();\n@@switch\nimport { NestFactory } from '@nestjs/core';\nimport { join } from 'path';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(\n    AppModule,\n  );\n\n  app.useStaticAssets(join(__dirname, '..', 'public'));\n  app.setBaseViewsDir(join(__dirname, '..', 'views'));\n  app.setViewEngine('hbs');\n\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nWe told [Express](https://github.com/expressjs/express) that the `public` directory will be used for storing static assets, `views` will contain templates, and the `hbs` template engine should be used to render HTML output.\n\n#### Template rendering\n\nNow, let's create a `views` directory and `index.hbs` template inside it. In the template, we'll print a `message` passed from the controller:\n\n```html\n<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\" />\n    <title>App</title>\n  </head>\n  <body>\n    {{ \"{{ message }\\}\" }}\n  </body>\n</html>\n```\n\nNext, open the `app.controller` file and replace the `root()` method with the following code:\n\n```typescript\n@@filename(app.controller)\nimport { Get, Controller, Render } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  @Render('index')\n  root() {\n    return { message: 'Hello world!' };\n  }\n}\n```\n\nIn this code, we are specifying the template to use in the `@Render()` decorator, and the return value of the route handler method is passed to the template for rendering. Notice that the return value is an object with a property `message`, matching the `message` placeholder we created in the template.\n\nWhile the application is running, open your browser and navigate to `http://localhost:3000`. You should see the `Hello world!` message.\n\n#### Dynamic template rendering\n\nIf the application logic must dynamically decide which template to render, then we should use the `@Res()` decorator, and supply the view name in our route handler, rather than in the `@Render()` decorator:\n\n> info **Hint** When Nest detects the `@Res()` decorator, it injects the library-specific `response` object. We can use this object to dynamically render the template. Learn more about the `response` object API [here](https://expressjs.com/en/api.html).\n\n```typescript\n@@filename(app.controller)\nimport { Get, Controller, Res, Render } from '@nestjs/common';\nimport { Response } from 'express';\nimport { AppService } from './app.service';\n\n@Controller()\nexport class AppController {\n  constructor(private appService: AppService) {}\n\n  @Get()\n  root(@Res() res: Response) {\n    return res.render(\n      this.appService.getViewName(),\n      { message: 'Hello world!' },\n    );\n  }\n}\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/15-mvc).\n\n#### Fastify\n\nAs mentioned in this [chapter](/techniques/performance), we are able to use any compatible HTTP provider together with Nest. One such library is [Fastify](https://github.com/fastify/fastify). In order to create an MVC application with Fastify, we have to install the following packages:\n\n```bash\n$ npm i --save fastify-static point-of-view handlebars\n```\n\nThe next steps cover almost the same process used with Express, with minor differences specific to the platform. Once the installation process is complete, open the `main.ts` file and update its contents:\n\n```typescript\n@@filename(main)\nimport { NestFactory } from '@nestjs/core';\nimport { NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';\nimport { AppModule } from './app.module';\nimport { join } from 'path';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter(),\n  );\n  app.useStaticAssets({\n    root: join(__dirname, '..', 'public'),\n    prefix: '/public/',\n  });\n  app.setViewEngine({\n    engine: {\n      handlebars: require('handlebars'),\n    },\n    templates: join(__dirname, '..', 'views'),\n  });\n  await app.listen(3000);\n}\nbootstrap();\n@@switch\nimport { NestFactory } from '@nestjs/core';\nimport { FastifyAdapter } from '@nestjs/platform-fastify';\nimport { AppModule } from './app.module';\nimport { join } from 'path';\n\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule, new FastifyAdapter());\n  app.useStaticAssets({\n    root: join(__dirname, '..', 'public'),\n    prefix: '/public/',\n  });\n  app.setViewEngine({\n    engine: {\n      handlebars: require('handlebars'),\n    },\n    templates: join(__dirname, '..', 'views'),\n  });\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nThe Fastify API is slightly different but the end result of those methods calls remains the same. One difference to notice with Fastify is that the template name passed into the `@Render()` decorator must include a file extension.\n\n```typescript\n@@filename(app.controller)\nimport { Get, Controller, Render } from '@nestjs/common';\n\n@Controller()\nexport class AppController {\n  @Get()\n  @Render('index.hbs')\n  root() {\n    return { message: 'Hello world!' };\n  }\n}\n```\n\nWhile the application is running, open your browser and navigate to `http://localhost:3000`. You should see the `Hello world!` message.\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/17-mvc-fastify).\n"
  },
  {
    "path": "content/techniques/performance.md",
    "content": "### Performance (Fastify)\n\nBy default, Nest makes use of the [Express](https://expressjs.com/) framework. As mentioned earlier, Nest also provides compatibility with other libraries such as, for example, [Fastify](https://github.com/fastify/fastify). Nest achieves this framework independence by implementing a framework adapter whose primary function is to proxy middleware and handlers to appropriate library-specific implementations.\n\n> info **Hint** Note that in order for a framework adapter to be implemented, the target library has to provide similar request/response pipeline processing as found in Express.\n\n[Fastify](https://github.com/fastify/fastify) provides a good alternative framework for Nest because it solves design issues in a similar manner to Express. However, fastify is much **faster** than Express, achieving almost two times better benchmarks results. A fair question is why does Nest use Express as the default HTTP provider? The reason is that Express is widely-used, well-known, and has an enormous set of compatible middleware, which is available to Nest users out-of-the-box.\n\nBut since Nest provides framework-independence, you can easily migrate between them. Fastify can be a better choice when you place high value on very fast performance. To utilize Fastify, simply choose the built-in `FastifyAdapter` as shown in this chapter.\n\n#### Installation\n\nFirst, we need to install the required package:\n\n```bash\n$ npm i --save @nestjs/platform-fastify\n```\n> warning **Warning** When using `@nestjs/platform-fastify` version `>=7.5.0` and `apollo-server-fastify`, GraphQL playground may not work due to incompatibility with `fastify` version `^3.0.0`. You may want to use the unstable `apollo-server-fastify` version `^3.0.0-alpha.3` or temporarily choose express instead.\n\n#### Adapter\n\nOnce the Fastify platform is installed, we can use the `FastifyAdapter`.\n\n```typescript\n@@filename(main)\nimport { NestFactory } from '@nestjs/core';\nimport {\n  FastifyAdapter,\n  NestFastifyApplication,\n} from '@nestjs/platform-fastify';\nimport { AppModule } from './app.module';\n\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter()\n  );\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nBy default, Fastify listens only on the `localhost 127.0.0.1` interface ([read more](https://www.fastify.io/docs/latest/Getting-Started/#your-first-server)). If you want to accept connections on other hosts, you should specify `'0.0.0.0'` in the `listen()` call:\n\n```typescript\nasync function bootstrap() {\n  const app = await NestFactory.create<NestFastifyApplication>(\n    AppModule,\n    new FastifyAdapter()\n  );\n  await app.listen(3000, '0.0.0.0');\n}\n```\n\n#### Platform specific packages\n\nKeep in mind that when you use the `FastifyAdapter`, Nest uses Fastify as the **HTTP provider**. This means that each recipe that relies on Express may no longer work. You should, instead, use Fastify equivalent packages.\n\n#### Redirect response\n\nFastify handles redirect responses slightly differently than Express. To do a proper redirect with Fastify, return both the status code and the URL, as follows:\n\n```typescript\n@Get()\nindex(@Res() res) {\n  res.status(302).redirect('/login');\n}\n```\n\n#### Fastify options\n\nYou can pass options into the Fastify constructor through the `FastifyAdapter` constructor. For example:\n\n```typescript\nnew FastifyAdapter({ logger: true });\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/10-fastify).\n"
  },
  {
    "path": "content/techniques/queues.md",
    "content": "### 큐\n\n큐는 일반적인 어플리케이션 확장 및 성능 문제를 처리하는 데 도움이 되는 강력한 디자인 패턴입니다. 큐가 해결할 수 있는 문제는 다음과 같습니다:\n\n- 프로세스 피크를 완화할 수 있습니다. 예를 들어, 유저는 임의의 시간에 리소스 집약적인 작업을 시작할 수 있고 작업을 동기로 수행하는 대신 큐에 작업을 추가할 수 있습니다. 그러면 워커가 큐에서 작업을 꺼내 처리를 합니다. 어플리케이션이 확장됨에 따라 백엔드 작업 처리를 확장하기 위해 새 큐 컨슈머를 쉽게 추가할 수 있습니다.\n- Node.js의 이벤트 루프를 차단할 수 있는 모놀리틱 태스크를 분리합니다. 예를 들어, 사용자 요청이 오디오 트랜스코딩과 같은 CPU 집약적 작업이 필요한 경우, 이 작업을 다른 프로세스에 위임할 수 있습니다. 반응형 상태를 유지하기 위해 사용자 대면 프로세스를 확보합니다. \n- 다양한 서비스에 걸쳐 안정적인 커뮤니케이션 채널을 제공합니다. 예를 들어, 한 프로세스나 서비스에서 태스크(작업)을 큐에 넣고 다른 프로세스나 서비스에서 사용할 수 있습니다. 모든 프로세스 또는 서비스에서 잡의 수명주기 완료, 오류 또는 기타 상태 변경 시 상태 이벤를 수신해 알림을 받을 수 있습니다. 큐 프로듀서 또는 컨슈머가 실패하면, 상태는 유지되고 노드가 재시작할 때 태스크 핸들링이 자동으로 재개됩니다.\n\n네스트는 `@nestjs/bull` 패키지를 제공합니다. 이 패키지는 인기 많고 충분한 서포트를 받고 있는 고성능 Node.js 기반 대기열 시스템의 구현인 [불](https://github.com/OptimalBits/bull) 의 추상화/래퍼 입니다. 패키지를 사용하면 어플리케이션에 네스트 친화적인 방식으로 불 큐를 쉽게 통합할 수 있습니다.\n\n불은 작업 데이터를 유지하는데 [레디스](https://redis.io/) 사용하기 때문에 시스템에 레디스가 설치되어 있어야 합니다. 레디스를 백엔드로 사용하기 때문에, 큐 아키텍쳐는 완전히 분산되고 플랫폼에 독립적일 수 있습니다. 예를 들어, 몇개의 큐가 <a href=\"techniques/queues#producers\">프로듀서</a> 와 <a href=\"techniques/queues#consumers\">컨슈머</a> 그리고 <a href=\"techniques/queues#event-listeners\">리스너</a> 가 네스트의 한 (또는 여러개) 노드에서 실행중일 때, 다른 프로듀서, 컨슈머 그리고 리스너가 다른 Node.js 플랫폼 또는 다른 네트워크 노드에서 실행할 수 있습니다.\n\n이 챕터는 `@nestjs/bull` 패키지에 대해 설명합니다. 자세한 배경 및 구체적인 구현 세부 정보를 얻고 싶으면 [불 공식문서](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md) 를 권장합니다.\n\n#### 설치\n\n먼저 필요한 패키지를 설치합니다.\n\n```bash\n$ npm install --save @nestjs/bull bull\n$ npm install --save-dev @types/bull\n```\n\n설치가 완료되면, 루트 `AppModule` 에 `BullModule` 를 임포트 할 수 있습니다.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { BullModule } from '@nestjs/bull';\n\n@Module({\n  imports: [\n    BullModule.forRoot({\n      redis: {\n        host: 'localhost',\n        port: 6379,\n      },\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n`forRoot()` 메소드는 `bull` 패키지 구성 옵션을 등록하는데 사용하며, 특별한 명시가 없는 한 어플리케이션에 등록된 모든 큐에서 사용됩니다. 구성 객체는 다음 속성으로 구성됩니다:\n\n- `limiter: RateLimiter` - 대기열의 작업이 처리되는 속도를 제어하는 옵션입니다. 자세한 내용은 [RateLimiter](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queue) 참조하세요. 선택 옵션.\n- `redis: RedisOpts` - 레디스 연결을 구성하는 옵션. 자세한 내용은 [RedisOpts](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queue) 참조하세요. 선택 옵션.\n- `prefix: string` - 모든 큐 키의 프리픽스. 선택 옵션.\n- `defaultJobOptions: JobOpts` - 새 작업의 기본 설정을 제어하는 옵션. 자세한 내용은 [JobOpts](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queueadd) 참조하세요. 선택 옵션.\n- `settings: AdvancedSettings` - 고급 큐 구성 설정. 일반적으로는 이 설정을 변경하면 안됩니다. 자세한 내용은 [AdvancedSettings](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queue) 참조사헤요. 선택 옵션.\n\n모든 옵션은 선택 사항이며, 대기열 동작을 세부적으로 제어할 수 있습니다. 이 옵션들은 불 `Queue` 생성자에 직접 전달됩니다. 옵션들에 대애서는 [여기](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queue) 더 알아볼 수 있습니다.\n\n큐를 등록하려면, 아래와 같이 다이나믹 모듈에 `BullModule#registerQueue()` 임포트 합니다:\n\n```typescript\nBullModule.registerQueue({\n  name: 'audio',\n});\n```\n\n> 정보 **힌트** `registerQueue()` 메소드에 콤마로 구분된 여러개의 구성 객체를 전달해 여러개의 큐를 생성합니다. \n\n`registerQueue()` 메소드는 큐를 인스턴스화 하거나 등록하는 데 사용합니다. 큐는 동일한 크레덴셜을 사용해 레디스에 연결하는 모듈 및 프로세스 간에 공유됩니다. 각 큐는 이름 속성에 따라 고유합니다. 큐의 이름 주입 토큰(컨트롤러/프로바이더에 큐를 주입)과 컨슈머 클래스 그리고 리스너를 큐와 연결하는 데코레이터의 인수로 사용합니다.\n\n다음과 같이 특정 대기열에 대해 미리 구성된 일부 옵션을 오버라이드 할 수도 있습니다:\n\n```typescript\nBullModule.registerQueue({\n  name: 'audio',\n  redis: {\n    port: 6380,\n  },\n});\n```\n\n잡은 레디스에서 지속되기 때문에 특정 이름으로 명명된 큐가 인스턴스화 될 때 마다(예: 앱이 시작/재시작), 이전의 완료되지 않은 세션에 남이있을 수 있는 오래된 잡을 진행하려고 시도합니다.\n\n각 큐는 한개 또는 여러개의 프로듀서, 컨슈머를 가질 수 있습니다. 컨슈머는 큐에서 특정 순서로 잡을 갖고옵니다: FIFO (기본), LIFO, 또는 우선 순위. 큐의 작업 순서에 대해서는 <a href=\"techniques/queues#consumers\">여기</a>에서 더 알아볼 수 있습니다.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### 명명된 구성\n\n큐가 여러개의 각기 다른 레디스 인스턴스와 연결되어 있는 경우, **명명된 구성**이란 테크닉을 사용할 수 있습니다. 이 기능을 사용하면 지정된 키 아래에 여러 구성을 등록할 수 있으며, 큐 옵션에서 참조할 수 있습니다.\n\n예를 들어, 추가 레디스 인스턴스가 있다고 가정하고 (기본 인스턴스 제외) 어플리케이션에 등록된 몇 개의 큐가 사용하고 있다면, 아래와 같이 구성에 등록할 수 있습니다: \n\n```typescript\nBullModule.forRoot('alternative-config', {\n  redis: {\n    port: 6381,\n  },\n});\n```\n\n위의 에시에서, `'alternative-config'` 는 구성 키 입니다. (임의의 문자열일 수 있음).\n\n이제 `registerQueue()` 옵션 객체에서 이 구성을 가리킬 수 있습니다:\n\n```typescript\nBullModule.registerQueue({\n  configKey: 'alternative-queue'\n  name: 'video',\n});\n```\n\n#### 프로듀서\n\n잡 프로듀서는 큐에 잡을 추가합니다. 프로듀서는 일반적으로 어플리케이션 서비스입니다. (네스트 [프로바이더](/providers)). 큐에 잡을 추가하려면, 아래와 같이 서비스에 큐를 주입합니다:\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { Queue } from 'bull';\nimport { InjectQueue } from '@nestjs/bull';\n\n@Injectable()\nexport class AudioService {\n  constructor(@InjectQueue('audio') private audioQueue: Queue) {}\n}\n```\n\n> 정보 **힌트** `@InjectQueue()` 데코레이터는 `registerQueue()` 메소드 호출시 제공된 이름으로 큐를 식별합니다 (예., `'audio'`).\n\n큐의 `add()` 메소드를 호출해 잡을 추가하고, 유저가 정의한 잡 객체를 전달합니다. 잡은 직렬화 가능한 자바스크립트 객체입니다. (레디스에 저장되는 형태). 잡의 모양은 임의적이며, 잡 객체의 의미를 나타내는 데 사용합니다.\n\n```typescript\nconst job = await this.audioQueue.add({\n  foo: 'bar',\n});\n```\n\n#### 명명된 잡\n\n잡은 고유한 이름을 가질 수 있습니다. 이를 통해 지정된 이름의 작업만 처리하는 특수한 <a href=\"techniques/queues#consumers\">컨슈머</a> 를 만들 수 있습니다.\n\n```typescript\nconst job = await this.audioQueue.add('transcode', {\n  foo: 'bar',\n});\n```\n\n> 경고 **경고** 명명된 잡을 사용할 때는 큐에 추가된 각각의 고유한 이름을 위한 프로세스를 생성해야 합니다. 그렇지 않으면 큐에서는 주어진 잡을 위한 프로세스가 없다고 할 것입니다. <a href=\"techniques/queues#consumers\">여기</a> 에서 더 자세한 정보를 읽어보세요. \n\n#### 잡 옵션\n\n잡에는 옵션을 추가할 수 있습니다. `Queue.add()` 메소드에서 `job` 인수 뒤에 옵션 객체를 전달합니다. 잡 옵션 속성은 다음과 같습니다.\n\n- `priority`: `number` - 선택적 우선 순위 값. 범위는 1(가장 높은 우선 순위) 부터 MAX_INT(가장 낮은 우선 순위)까지 입니다. 우선 순위를 사용하면 성능에 약간 영향을 미치므로 사용할 때 주의해야 합니다. \n- `delay`: `number` - 이 작업을 처리할 수 있을 때 까지 대기하는 시간(밀리초) 입니다. 정확한 지연을 위해 서버와 클라이언트 모두 시게를 동기화해야 합니다.\n- `attempts`: `number` - 잡이 완료될 때 까지 시도할 총 시도 횟수입니다.\n- `repeat`: `RepeatOpts` - 크론의 사양에 따라 작업을 반복합니다. [RepeatOpts](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queueadd).\n- `backoff`: `number | BackoffOpts` - 잡이 실패할 경우 자동으로 재시도 하기 위한 백오프 설정입니다. [BackoffOpts](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queueadd).\n- `lifo`: `boolean` - true일 경우, 큐의 왼쪽 대신 오른쪽 끝에 잡을 추가합니다. (기본값은 false).\n- `timeout`: `number` - 시간 초과 오류와 함께 작업이 실패해야 하는 시간(밀리초) 입니다. \n- `jobId`: `number` | `string` - 잡 ID 오버라이드 - 기본적으로 잡 ID 는 고유합니다.\n   이 설정을 오버라이드 해서 integer를 사용할 수 있습니다. 이 옵션을 사용하고 싶으면, 잡 id가 고유해야 합니다. 이미 존재한느 id를 사용애 잡을 추가하려 시도하면 추가가 되지 않습니다. \n- `removeOnComplete`: `boolean | number` - true일 경우, 성공적으로 완료한 잡을 삭제합니다. 유지할 잡의 양을 숫자로 지정합니다. 기본 동작은 작업을 완료된 세트로 유지합니다.\n- `removeOnFail`: `boolean | number` - true일 경우, 시도 후에 실패한 작업을 제거합니다. 유지할 작업의 양을 숫자로 지정합니다. 기본 동작은 작업을 실패한 세트로 유지하는 것입니다. \n- `stackTraceLimit`: `number` - 스택트레이스에 기록할 스택트레이스 라인의 수를 제한합니다.\n\n다음은 잡 옵션을 사용자 지정하는 몇 가지 예제입니다.\n\n작업 시작을 지연하려면 `delay` 구성 속성을 사용합니다.\n\n```typescript\nconst job = await this.audioQueue.add(\n  {\n    foo: 'bar',\n  },\n  { delay: 3000 }, // 3 seconds delayed\n);\n```\n\n큐의 오른쪽 끝에 잡ㅇ르 추가하려면 (잡을 **LIFO** (후입선출)로 처리), 구성 객체의 `lifo` 속성을 `true`로 설정합니다.\n\n```typescript\nconst job = await this.audioQueue.add(\n  {\n    foo: 'bar',\n  },\n  { lifo: true },\n);\n```\n\n작업의 우선 순위를 지정하려면 `priority` 속성을 사용합니다.\n\n```typescript\nconst job = await this.audioQueue.add(\n  {\n    foo: 'bar',\n  },\n  { priority: 2 },\n);\n```\n\n#### 컨슈머\n\n컨슈머는 **클래스** 로 큐에 추가된 작업을 처리하는 메소드를 정의하거나, 큐에서 이벤트 수신을 대기하거나, 둘 다를 수행 합니다. 다음과 같이 `@Processor()` 데코레이터를 사용해서 컨슈머를 선언합니다:\n\n```typescript\nimport { Processor } from '@nestjs/bull';\n\n@Processor('audio')\nexport class AudioConsumer {}\n```\n\n> 정보 **힌트** 컨슈머는 `providers` 로 등록해야 `@nestjs/bull` 패키지가 사용할 수 있습니다.\n\n여기서 데코레이터의 문자열 인수 (예: `'audio'`) 는 클래스 메소드에 연결할 큐의 이름입니다.\n\n컨슈머 클래스 내부에서는 `@Process()` 데코레이터를 핸들러 메소드에 사용해 잡 핸들러를 선언할 수 있습니다.\n\n```typescript\nimport { Processor, Process } from '@nestjs/bull';\nimport { Job } from 'bull';\n\n@Processor('audio')\nexport class AudioConsumer {\n  @Process()\n  async transcode(job: Job<unknown>) {\n    let progress = 0;\n    for (i = 0; i < 100; i++) {\n      await doSomething(job.data);\n      progress += 10;\n      await job.progress(progress);\n    }\n    return {};\n  }\n}\n```\n\n데코레이터 메소드 (예: `transcode()`) 는 워커가 유휴상태이고 큐에 처리할 잡이 있을때 호출됩니다. 이 핸들러 메소드는 `job` 객체를 유일한 인수로 받습니다. 핸들러 메소드에서 반환한 값은 잡 객체에 저장되며, 나중에, 예를 들면 완료된 이벤트에 대한 리스너에서 접근할 수 있습니다.\n\n`Job` 객체는 상태와 상호작용 할 수 있게 하는 여러 메소드가 있습니다. 예를 들어, 위의 코드는 `progress()` 메소드를 사용해서 잡의 진행상태를 업데이트 합니다. [여기](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#job) 에서 `Job` 객체의 API 레퍼런스를 볼 수 있습니다.\n\n아래와 같이 `name` 을 `@Process()` 데코레이터에 전달해 잡 핸들러 메서드가 **오직** 특정 유형의 잡만 (특정 `name`의 잡)을 처리하도록 지정할 수 있습니다. 주어진 컨슈머 클래스에 각 잡 유형 (`name`)에 해당하는 여러 `@Process()` 핸들러를 가질 수 있습니다. 명명된 잡을 사용할 때, 각 이름에 해당하는 핸들러가 있어야 합니다.\n\n```typescript\n@Process('transcode')\nasync transcode(job: Job<unknown>) { ... }\n```\n\n#### 리퀘스트 스쿠프 컨슈머\n\n컨슈머가 리퀘스트 스푸크로 지정될 경우 (스쿠프 주입에 대해서 더 알아보려면 [여기](/fundamentals/injection-scopes#provider-scope)를 참조하세요), 클래스의 새 인스턴스는 각 잡에 독점적으로 생성됩니다. 인스턴스는 잡이 완료된 후 가비지 콜렉팅 됩니다.\n\n```typescript\n@Processor({\n  name: 'audio',\n  scope: Scope.REQUEST,\n})\n```\n\n리퀘스트 스코프 컨슈머 클래스는 동적으로 인스턴스화 되고, 단일 작업으로 범위가 지정되므로 표준 접근 방식을 사용해 생성자를 통해 `JOB_REF`를 주입할 수 있습니다.\n\n```typescript\nconstructor(@Inject(JOB_REF) jobRef: Job) {\n  console.log(jobRef);\n}\n```\n\n> 정보 **힌트** `JOB_REF` 토큰은 `@nestjs/bull` 패키지에서 임포트 합니다.\n\n#### 이벤트 리스너\n\n불은 큐 또는 작업 상태 변경이 발생할 때 유용한 이벤트 집합을 생성합니다. 네스트는 표준 이벤트의 핵심 세트를 구독할 수 있는 데코레이터 세트를 제공합니다. 이 모든 것은 `@nestjs/bull` 패키지에서 익스포트 합니다.\n\n이벤트 리스너는 반드시 <a href=\"techniques/queues#consumers\">컨슈머</a> 클래스 내부에 선언되어야 합니다. (예: `@Processor()` 데코레이더를 사용하는 클래스 내). 이벤트를 구독하려면, 아래 테이블에 있는 데코레이터 중 하나를 사용해 이벤트를 위한 핸들러를 선언합니다. 예를 들어, `audio` 큐에서 잡이 활성상태가 될 때 발생하는 이벤트를 수신하려면 다음과 같은 구성을 사용합니다:\n\n```typescript\nimport { Processor, Process } from '@nestjs/bull';\nimport { Job } from 'bull';\n\n@Processor('audio')\nexport class AudioConsumer {\n\n  @OnQueueActive()\n  onActive(job: Job) {\n    console.log(\n      `Processing job ${job.id} of type ${job.name} with data ${job.data}...`,\n    );\n  }\n  ...\n```\n\n불이 분산 (멀티 노드) 환경에서 작동하기 때문에, 이벤트에 로컬 개념을 정의합니다. 이 개념은 이벤트가 단일 프로세스 내에서만 트리거 되거나, 다른 프로세스의 공유된 큐에서 트리거 될 수 있음을 인식합니다. **로컬** 이벤트는 로컬 프로세스의 큐에서 작업 또는 상태 변경이 트리거 될 때 생성되는 것입니다. 즉, 이벤트 프로듀서와 컨슈머가 단일 프로세스 로컬인 경우 큐에서 발생하는 모든 이벤트는 로컬입니다. \n\n큐가 여러 프로세스에서 공유되면, **글로벌** 이벤트가 발생할 가능성이 있습니다. 한 프로세스의 리스너가 다른 프로세스에 의해 트리거된 이벤트 알림을 수신하려면 전역 이벤트로 등록해야 합니다.\n\n이벤트 핸들러는 해당 이벤트가 발생할 때마다 호출됩니다. 핸들러는 아래 테이블에 나와있는 시그니처로 호출 할 수 있으며, 이벤트와 관련된 정보에 접근할 수 있게 합니다. 아래에서 로컬 이벤트 핸들러 시그니처와 글로벌 이벤트 시그니처 간의 한가지 중요한 차이점에 대해 설명합니다. \n\n<table>\n  <tr>\n    <th>로컬 이벤트 리스터</th>\n    <th>글로벌 이벤트 리스너</th>\n    <th>핸들러 메소드 시그니처 / 호출될 때</th>\n  </tr>\n  <tr>\n    <td><code>@OnQueueError()</code></td><td><code>@OnGlobalQueueError()</code></td><td><code>handler(error: Error)</code> - 에러 발생. <code>error</code> 는 트리거 에러도 포함.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueWaiting()</code></td><td><code>@OnGlobalQueueWaiting()</code></td><td><code>handler(jobId: number | string)</code> - 워커가 유휴상태인 즉시 잡을 처리하기 위해 대기중. <code>jobId</code> 는 잡의 id와 상태를 담고있음.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueActive()</code></td><td><code>@OnGlobalQueueActive()</code></td><td><code>handler(job: Job)</code> - 잡 <code>job</code>이 시작됨. </td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueStalled()</code></td><td><code>@OnGlobalQueueStalled()</code></td><td><code>handler(job: Job)</code> - 잡 <code>job</code> 이 정지된 것으로 표시됨. 이벤트 루프가 충돌하거나 중단되어 잡 워커를 디버깅 할 때 유용함.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueProgress()</code></td><td><code>@OnGlobalQueueProgress()</code></td><td><code>handler(job: Job, progress: number)</code> - 잡 <code>job</code> 의 진행상황이 <code>progress</code> 값에 업데이트.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueCompleted()</code></td><td><code>@OnGlobalQueueCompleted()</code></td><td><code>handler(job: Job, result: any)</code> 잡 <code>job</code> 이 결과 <code>result</code>와 함께 성공적으로 작업 완료.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueFailed()</code></td><td><code>@OnGlobalQueueFailed()</code></td><td><code>handler(job: Job, err: Error)</code> 잡 <code>job</code> 이 <code>err</code> 를 이유로 실패.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueuePaused()</code></td><td><code>@OnGlobalQueuePaused()</code></td><td><code>handler()</code> 큐가 일시 중지됨.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueResumed()</code></td><td><code>@OnGlobalQueueResumed()</code></td><td><code>handler(job: Job)</code> 큐가 재개됨.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueCleaned()</code></td><td><code>@OnGlobalQueueCleaned()</code></td><td><code>handler(jobs: Job[], type: string)</code> 오래된 잡이 큐에서 제거됨. <code>jobs</code> 제거된 잡의 어레이 형태. <code>type</code> 은 제거된 잡의 타임.</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueDrained()</code></td><td><code>@OnGlobalQueueDrained()</code></td><td><code>handler()</code> 큐가 모든 대기 잡을 처리할 때 발생 (몇몇의 지연된 잡이 아직 처리되지 않았을 때도 발생).</td>\n  </tr>\n  <tr>\n    <td><code>@OnQueueRemoved()</code></td><td><code>@OnGlobalQueueRemoved()</code></td><td><code>handler(job: Job)</code> 잡 <code>job</code> 이 성공적으로 제거됨.</td>\n  </tr>\n</table>\n\n글로벌 이벤트를 구독할때는, 메소드 시그니처가 로컬과는 약간 다를 수 있습니다. 특히, 메소드 시그니처는 로컬 버전일 때 `job` 객체를 수신하지만 글로벌 버전일 때 `jobId` (`number`) 를 수신받습니다. 이러한 경우 실제 `job` 객체의 참조를 얻으려면, `Queue#getJob` 메소드를 사용합니다. 이 호출은 대기해야 하기 때문에 핸들러는 `async` 로 선언되어야 합니다. 예:\n\n```typescript\n@OnGlobalQueueCompleted()\nasync onGlobalCompleted(jobId: number, result: any) {\n  const job = await this.immediateQueue.getJob(jobId);\n  console.log('(Global) on completed: job ', job.id, ' -> result: ', result);\n}\n```\n\n> 정보 **힌트**  `Queue` 객체에 접근하려면 (`getJob()` 호출하려면), 당연히 주입해야 합니다. 또한 큐는 주입하려는 모듈에 등록되어 있어야 합니다.\n\n특정 이벤트 리스너 데코레이터 외에도, 제네릭 `@OnQueueEvent()` 데코레이터를 in combination with  `BullQueueEvents` 또는 `BullQueueGlobalEvents` 이넘과 함께 사용할 수 있습니다. 이벤트에 대한 자세한 내용은 [여기](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#events) 를 참조하세요.\n\n#### 큐 관리\n\n큐에는 일시 중지 및 재개, 다양한 상태의 잡 수 검색 등과 같이 관리 기능을 수행하는 API가 있습니다. 모든 큐 API [여기](https://github.com/OptimalBits/bull/blob/master/REFERENCE.md#queue) 에서 볼 수 있습니다. `Queue` 객체에서 이러한 메소드를 직접 호출해, 아래와 같이 일시 중지/재개를 할 수 있습니다. \n\n`pause()` 메소드를 호출해 큐를 일시 중지 합니다. 일시 중지된 큐는 재개되지 전에는 잡을 실행하지 않지만, 실행 중이던 잡은 해당 잡이 완료될 때 까지 실행합니다.\n\n```typescript\nawait audioQueue.pause();\n```\n\n일시 중지된 큐를 재개하려면, 아래와 같이 `resume()` 메소드를 사용합니다:\n\n```typescript\nawait audioQueue.resume();\n```\n\n#### 별도의 프로세스\n\n잡 핸들러는 별도의(포크)된 프로세스에서 실행될 수 있습니다. ([소스](https://github.com/OptimalBits/bull#separate-processes)). 이 방법에는 몇 가지 장점이 있습니다:\n\n- 프로세스가 샌드박스 처리되어, 충돌이 발생해도 워커에 영향을 미치지 않음. \n- 큐에 영향을 주지 않고 차단 코드를 실행 가능(작업이 중단되지 않음).\n- 더 높은h 멀티 코어 CPU 활용도.\n- 적은 레디스 연결.\n\n```ts\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { BullModule } from '@nestjs/bull';\nimport { join } from 'path';\n\n@Module({\n  imports: [\n    BullModule.registerQueue({\n      name: 'audio',\n      processors: [join(__dirname, 'processor.js')],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n펑션이 포크된 프로세스에서 실행되고 있기 때문에, 종속성 주입 Dependency Injection (그리고 IoC 컨테이너) 를 사용할 수 없습니다. 즉, 프로세서 기능은 필요한 외부 종속성의 모든 인스턴스를 포함(또는 생성) 해야 합니다.\n\n```ts\n@@filename(processor)\nimport { Job, DoneCallback } from 'bull';\n\nexport default function (job: Job, cb: DoneCallback) {\n  console.log(`[${process.pid}] ${JSON.stringify(job.data)}`);\n  cb(null, 'It works');\n}\n```\n\n#### 비동기 구성\n\n`bull` 옵션을 정적으로 전달하는 대신 비동기적으로 전달할 수 있습니다. 이런 경우, 비동기 구성을 처리하는 여러가지 방법을 제공하는 `forRootAsync()` 메소드를 사용합니다. 이와 비슷하게, `registerQueueAsync()` 메소드를 사용하면 큐에 옵션을 비동기로 전달할 수 있습니다.\n\n한 가지 접근 방식은 팩토리 펑션을 사용입니다:\n\n```typescript\nBullModule.forRootAsync({\n  useFactory: () => ({\n    redis: {\n      host: 'localhost',\n      port: 6379,\n    },\n  }),\n});\n```\n\n이 팩토리는 다른 [비동기 프로바이더](https://docs.nestjs.com/fundamentals/async-providers) (예: `async` 일 수 있고 `inject` 를 사용해 종속성을 주입할 수 있음.) 처럼 작동합니다.\n\n```typescript\nBullModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: async (configService: ConfigService) => ({\n    redis: {\n      host: configService.get('QUEUE_HOST'),\n      port: +configService.get('QUEUE_PORT'),\n    },\n  }),\n  inject: [ConfigService],\n});\n```\n\n또는 `useClass` 구문을 사용할 수 있습니다:\n\n```typescript\nBullModule.forRootAsync({\n  useClass: BullConfigService,\n});\n```\n\n위의 구성은 `BullConfigService` 내부에서 `BullModule` 를 인스턴스화 하고 `createSharedConfiguration()` 을 호출해 옵션 객체를 제공하는데 사용합니다. 아래와 같이 `BullConfigService` 가 `SharedBullConfigurationFactory` 인터페이스를 구현해야 함을 의미합니다:\n\n```typescript\n@Injectable()\nclass BullConfigService implements SharedBullConfigurationFactory {\n  createSharedConfiguration(): BullModuleOptions {\n    return {\n      redis: {\n        host: 'localhost',\n        port: 6379,\n      },\n    };\n  }\n}\n```\n\n`BullConfigService` 내부에서 `BullModule` 가 생성되는 걸 방지하고 다른 모듈에서 임포트한 프로바이더를 사용하려면 `useExisting` 구문을 사용합니다.\n\n```typescript\nBullModule.forRootAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n});\n```\n\n이 구성은 `useClass` 와 동일하게 작동하지만 단 한가지 큰 차이점이 있습니다. `BullModule` 는 새 객체를 생성하는 대신 기존의 `ConfigService` 객체를 재사용 하기 위해 객체를 조회합니다.\n\n#### 예제\n\n예시는 [여기](https://github.com/nestjs/nest/tree/master/sample/26-queues) 에서 볼 수 있습니다.\n"
  },
  {
    "path": "content/techniques/serialization.md",
    "content": "### Serialization\n\nSerialization is a process that happens before objects are returned in a network response. This is an appropriate place to provide rules for transforming and sanitizing the data to be returned to the client. For example, sensitive data like passwords should always be excluded from the response. Or, certain properties might require additional transformation, such as sending only a subset of properties of an entity. Performing these transformations manually can be tedious and error prone, and can leave you uncertain that all cases have been covered.\n\n#### Overview\n\nNest provides a built-in capability to help ensure that these operations can be performed in a straightforward way. The `ClassSerializerInterceptor` interceptor uses the powerful [class-transformer](https://github.com/typestack/class-transformer) package to provide a declarative and extensible way of transforming objects. The basic operation it performs is to take the value returned by a method handler and apply the `classToPlain()` function from [class-transformer](https://github.com/typestack/class-transformer). In doing so, it can apply rules expressed by `class-transformer` decorators on an entity/DTO class, as described below.\n\n#### Exclude properties\n\nLet's assume that we want to automatically exclude a `password` property from a user entity. We annotate the entity as follows:\n\n```typescript\nimport { Exclude } from 'class-transformer';\n\nexport class UserEntity {\n  id: number;\n  firstName: string;\n  lastName: string;\n\n  @Exclude()\n  password: string;\n\n  constructor(partial: Partial<UserEntity>) {\n    Object.assign(this, partial);\n  }\n}\n```\n\nNow consider a controller with a method handler that returns an instance of this class.\n\n```typescript\n@UseInterceptors(ClassSerializerInterceptor)\n@Get()\nfindOne(): UserEntity {\n  return new UserEntity({\n    id: 1,\n    firstName: 'Kamil',\n    lastName: 'Mysliwiec',\n    password: 'password',\n  });\n}\n```\n\n> **Warning** Note that we must return an instance of the class. If you return a plain JavaScript object, for example, `{{ '{' }} user: new UserEntity() {{ '}' }}`, the object won't be properly serialized.\n\n> info **Hint** The `ClassSerializerInterceptor` is imported from `@nestjs/common`.\n\nWhen this endpoint is requested, the client receives the following response:\n\n```json\n{\n  \"id\": 1,\n  \"firstName\": \"Kamil\",\n  \"lastName\": \"Mysliwiec\"\n}\n```\n\nNote that the interceptor can be applied application-wide (as covered [here](https://docs.nestjs.com/interceptors#binding-interceptors)). The combination of the interceptor and the entity class declaration ensures that **any** method that returns a `UserEntity` will be sure to remove the `password` property. This gives you a measure of centralized enforcement of this business rule.\n\n#### Expose properties\n\nYou can use the `@Expose()` decorator to provide alias names for properties, or to execute a function to calculate a property value (analogous to **getter** functions), as shown below.\n\n```typescript\n@Expose()\nget fullName(): string {\n  return `${this.firstName} ${this.lastName}`;\n}\n```\n\n#### Transform\n\nYou can perform additional data transformation using the `@Transform()` decorator. For example, the following construct returns the name property of the `RoleEntity` instead of returning the whole object.\n\n```typescript\n@Transform(({ value }) => value.name)\nrole: RoleEntity;\n```\n\n#### Pass options\n\nYou may want to modify the default behavior of the transformation functions. To override default settings, pass them in an `options` object with the `@SerializeOptions()` decorator.\n\n```typescript\n@SerializeOptions({\n  excludePrefixes: ['_'],\n})\n@Get()\nfindOne(): UserEntity {\n  return new UserEntity();\n}\n```\n\n> info **Hint** The `@SerializeOptions()` decorator is imported from `@nestjs/common`.\n\nOptions passed via `@SerializeOptions()` are passed as the second argument of the underlying `classToPlain()` function. In this example, we are automatically excluding all properties that begin with the `_` prefix.\n\n#### Example \n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/21-serializer).\n\n#### WebSockets and Microservices\n\nWhile this chapter shows examples using HTTP style applications (e.g., Express or Fastify), the `ClassSerializerInterceptor` works the same for WebSockets and Microservices, regardless of the transport method that is used.\n\n#### Learn more\n\nRead more about available decorators and options as provided by the `class-transformer` package [here](https://github.com/typestack/class-transformer).\n"
  },
  {
    "path": "content/techniques/server-sent-events.md",
    "content": "### Server-Sent Events\n\nServer-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via HTTP connection. Each notification is sent as a block of text terminated by a pair of newlines (learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events)).\n\n#### Usage\n\nTo enable Server-Sent events on a route (route registered within a **controller class**), annotate the method handler with the `@Sse()` decorator.\n\n```typescript\n@Sse('sse')\nsse(): Observable<MessageEvent> {\n  return interval(1000).pipe(map((_) => ({ data: { hello: 'world' } })));\n}\n```\n\n> info **Hint** The `@Sse()` decorator and `MessageEvent` interface are imported from the `@nestjs/common`, while `Observable`, `interval`, and `map` are imported from the `rxjs` package.\n\n> warning **Warning** Server-Sent Events routes must return an `Observable` stream.\n\nIn the example above, we defined a route named `sse` that will allow us to propagate real-time updates. These events can be listened to using the [EventSource API](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).\n\nThe `sse` method returns an `Observable` that emits multiple `MessageEvent` (in this example, it emits a new `MessageEvent` every second). The `MessageEvent` object should respect the following interface to match the specification:\n\n```typescript\nexport interface MessageEvent {\n  data: string | object;\n  id?: string;\n  type?: string;\n  retry?: number;\n}\n```\n\nWith this in place, we can now create an instance of the `EventSource` class in our client-side application, passing the `/sse` route (which matches the endpoint we have passed into the `@Sse()` decorator above) as a constructor argument.\n\n`EventSource` instance opens a persistent connection to an HTTP server, which sends events in `text/event-stream` format. The connection remains open until closed by calling `EventSource.close()`.\n\nOnce the connection is opened, incoming messages from the server are delivered to your code in the form of events. If there is an event field in the incoming message, the triggered event is the same as the event field value. If no event field is present, then a generic `message` event is fired ([source](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)).\n\n```javascript\nconst eventSource = new EventSource('/sse');\neventSource.onmessage = ({ data }) => {\n  console.log('New message', JSON.parse(data));\n};\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/28-sse).\n"
  },
  {
    "path": "content/techniques/sessions.md",
    "content": "### Session\n\n**HTTP sessions** provide a way to store information about the user across multiple requests, which is particularly useful for [MVC](/techniques/mvc) applications.\n\n#### Use with Express (default)\n\nFirst install the required package (and its types for TypeScript users):\n\n```shell\n$ npm i express-session\n$ npm i -D @types/express-session\n```\n\nOnce the installation is complete, apply the `express-session` middleware as global middleware (for example, in your `main.ts` file).\n\n```typescript\nimport * as session from 'express-session';\n// somewhere in your initialization file\napp.use(\n  session({\n    secret: 'my-secret',\n    resave: false,\n    saveUninitialized: false,\n  }),\n);\n```\n\n> warning **Notice** The default server-side session storage is purposely not designed for a production environment. It will leak memory under most conditions, does not scale past a single process, and is meant for debugging and developing. Read more in the [official repository](https://github.com/expressjs/session).\n\nThe `secret` is used to sign the session ID cookie. This can be either a string for a single secret, or an array of multiple secrets. If an array of secrets is provided, only the first element will be used to sign the session ID cookie, while all the elements will be considered when verifying the signature in requests. The secret itself should be not easily parsed by a human and would best be a random set of characters.\n\nEnabling the `resave` option forces the session to be saved back to the session store, even if the session was never modified during the request. The default value is `true`, but using the default has been deprecated, as the default will change in the future.\n\nLikewise, enabling the `saveUninitialized` option Forces a session that is \"uninitialized\" to be saved to the store. A session is uninitialized when it is new but not modified. Choosing `false` is useful for implementing login sessions, reducing server storage usage, or complying with laws that require permission before setting a cookie. Choosing `false` will also help with race conditions where a client makes multiple parallel requests without a session ([source](https://github.com/expressjs/session#saveuninitialized)).\n\nYou can pass several other options to the `session` middleware, read more about them in the [API documentation](https://github.com/expressjs/session#options).\n\n> info **Hint** Please note that `secure: true` is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set. If you have your node.js behind a proxy and are using `secure: true`, you need to set `\"trust proxy\"` in express.\n\nWith this in place, you can now set and read session values from within the route handlers, as follows:\n\n```typescript\n@Get()\nfindAll(@Req() request: Request) {\n  request.session.visits = request.session.visits ? request.session.visits + 1 : 1;\n}\n```\n\n> info **Hint** The `@Req()` decorator is imported from the `@nestjs/common`, while `Request` from the `express` package.\n\nAlternatively, you can use the `@Session()` decorator to extract a session object from the request, as follows:\n\n```typescript\n@Get()\nfindAll(@Session() session: Record<string, any>) {\n  session.visits = session.visits ? session.visits + 1 : 1;\n}\n```\n\n> info **Hint** The `@Session()` decorator is imported from the `@nestjs/common` package.\n\n#### Use with Fastify\n\nFirst install the required package:\n\n```shell\n$ npm i fastify-secure-session\n```\n\nOnce the installation is complete, register the `fastify-secure-session` plugin:\n\n```typescript\nimport secureSession from 'fastify-secure-session';\n\n// somewhere in your initialization file\nconst app = await NestFactory.create<NestFastifyApplication>(\n  AppModule,\n  new FastifyAdapter(),\n);\napp.register(secureSession, {\n  secret: 'averylogphrasebiggerthanthirtytwochars',\n  salt: 'mq9hDxBVDbspDR6n',\n});\n```\n\n> info **Hint** You can also pregenerate a key ([see instructions](https://github.com/fastify/fastify-secure-session)) or use [keys rotation](https://github.com/fastify/fastify-secure-session#using-keys-with-key-rotation).\n\nRead more about the available options in the [official repository](https://github.com/fastify/fastify-secure-session).\n\nWith this in place, you can now set and read session values from within the route handlers, as follows:\n\n```typescript\n@Get()\nfindAll(@Req() request: FastifyRequest) {\n  const visits = request.session.get('visits');\n  request.session.set('visits', visits ? visits + 1 : 1);\n}\n```\n\nAlternatively, you can use the `@Session()` decorator to extract a session object from the request, as follows:\n\n```typescript\n@Get()\nfindAll(@Session() session: secureSession.Session) {\n  const visits = session.get('visits');\n  session.set('visits', visits ? visits + 1 : 1);\n}\n```\n\n> info **Hint** The `@Session()` decorator is imported from the `@nestjs/common`, while `secureSession.Session` from the `fastify-secure-session` package (import statement: `import * as secureSession from 'fastify-secure-session'`).\n"
  },
  {
    "path": "content/techniques/sql.md",
    "content": "### Database\n\nNest is database agnostic, allowing you to easily integrate with any SQL or NoSQL database. You have a number of options available to you, depending on your preferences. At the most general level, connecting Nest to a database is simply a matter of loading an appropriate Node.js driver for the database, just as you would with [Express](https://expressjs.com/en/guide/database-integration.html) or Fastify.\n\nYou can also directly use any general purpose Node.js database integration **library** or ORM, such as [MikroORM](https://mikro-orm.io/) also check the [recipe here](/recipes/mikroorm),  [Sequelize](https://sequelize.org/) (navigate to the [Sequelize integration](/techniques/database#sequelize-integration) section), [Knex.js](https://knexjs.org/) ([tutorial](https://dev.to/nestjs/build-a-nestjs-module-for-knex-js-or-other-resource-based-libraries-in-5-minutes-12an)), [TypeORM](https://github.com/typeorm/typeorm), and [Prisma](https://www.github.com/prisma/prisma) ([recipe](/recipes/prisma)) , to operate at a higher level of abstraction.\n\nFor convenience, Nest provides tight integration with TypeORM and Sequelize out-of-the-box with the `@nestjs/typeorm` and `@nestjs/sequelize` packages respectively, which we'll cover in the current chapter, and Mongoose with `@nestjs/mongoose`, which is covered in [this chapter](/techniques/mongodb). These integrations provide additional NestJS-specific features, such as model/repository injection, testability, and asynchronous configuration to make accessing your chosen database even easier.\n\n### TypeORM Integration\n\nFor integrating with SQL and NoSQL databases, Nest provides the `@nestjs/typeorm` package. Nest uses [TypeORM](https://github.com/typeorm/typeorm) because it's the most mature Object Relational Mapper (ORM) available for TypeScript. Since it's written in TypeScript, it integrates well with the Nest framework.\n\nTo begin using it, we first install the required dependencies. In this chapter, we'll demonstrate using the popular [MySQL](https://www.mysql.com/) Relational DBMS, but TypeORM provides support for many relational databases, such as PostgreSQL, Oracle, Microsoft SQL Server, SQLite, and even NoSQL databases like MongoDB. The procedure we walk through in this chapter will be the same for any database supported by TypeORM. You'll simply need to install the associated client API libraries for your selected database.\n\n```bash\n$ npm install --save @nestjs/typeorm typeorm mysql2\n```\n\nOnce the installation process is complete, we can import the `TypeOrmModule` into the root `AppModule`.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      entities: [],\n      synchronize: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n> warning **Warning** Setting `synchronize: true` shouldn't be used in production - otherwise you can lose production data.\n\nThe `forRoot()` method supports all the configuration properties exposed by the `createConnection()` function from the [TypeORM](https://typeorm.io/#/connection-options) package. In addition, there are several extra configuration properties described below.\n\n<table>\n  <tr>\n    <td><code>retryAttempts</code></td>\n    <td>Number of attempts to connect to the database (default: <code>10</code>)</td>\n  </tr>\n  <tr>\n    <td><code>retryDelay</code></td>\n    <td>Delay between connection retry attempts (ms) (default: <code>3000</code>)</td>\n  </tr>\n  <tr>\n    <td><code>autoLoadEntities</code></td>\n    <td>If <code>true</code>, entities will be loaded automatically (default: <code>false</code>)</td>\n  </tr>\n  <tr>\n    <td><code>keepConnectionAlive</code></td>\n    <td>If <code>true</code>, connection will not be closed on application shutdown (default: <code>false</code>)</td>\n  </tr>\n</table>\n\n> info **Hint** Learn more about the connection options [here](https://typeorm.io/#/connection-options).\n\nAlternatively, rather than passing a configuration object to `forRoot()`, we can create an `ormconfig.json` file in the project root directory.\n\n```json\n{\n  \"type\": \"mysql\",\n  \"host\": \"localhost\",\n  \"port\": 3306,\n  \"username\": \"root\",\n  \"password\": \"root\",\n  \"database\": \"test\",\n  \"entities\": [\"dist/**/*.entity{.ts,.js}\"],\n  \"synchronize\": true\n}\n```\n\nThen, we can call `forRoot()` without any options:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [TypeOrmModule.forRoot()],\n})\nexport class AppModule {}\n```\n\n> warning **Warning** Static glob paths (e.g., `dist/**/*.entity{{ '{' }} .ts,.js{{ '}' }}`) won't work properly with [webpack](https://webpack.js.org/).\n\n> info **Hint** Note that the `ormconfig.json` file is loaded by the `typeorm` library. Thus, any of the extra properties described above (which are supported internally by way of the `forRoot()` method - for example, `autoLoadEntities` and `retryDelay`) won't be applied. Luckily, TypeORM provides the [`getConnectionOptions`](https://typeorm.io/#/using-ormconfig/overriding-options-defined-in-ormconfig) function that reads connection options from the `ormconfig` file or environment variables. With this, you can still use the configuration file and set Nest-specific options, as follows:\n>\n> ```typescript\n> TypeOrmModule.forRootAsync({\n>   useFactory: async () =>\n>     Object.assign(await getConnectionOptions(), {\n>       autoLoadEntities: true,\n>     }),\n> });\n> ```\n\nOnce this is done, the TypeORM `Connection` and `EntityManager` objects will be available to inject across the entire project (without needing to import any modules), for example:\n\n```typescript\n@@filename(app.module)\nimport { Connection } from 'typeorm';\n\n@Module({\n  imports: [TypeOrmModule.forRoot(), UsersModule],\n})\nexport class AppModule {\n  constructor(private connection: Connection) {}\n}\n@@switch\nimport { Connection } from 'typeorm';\n\n@Dependencies(Connection)\n@Module({\n  imports: [TypeOrmModule.forRoot(), UsersModule],\n})\nexport class AppModule {\n  constructor(connection) {\n    this.connection = connection;\n  }\n}\n```\n\n#### Repository pattern\n\n[TypeORM](https://github.com/typeorm/typeorm) supports the **repository design pattern**, so each entity has its own repository. These repositories can be obtained from the database connection.\n\nTo continue the example, we need at least one entity. Let's define the `User` entity.\n\n```typescript\n@@filename(user.entity)\nimport { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';\n\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstName: string;\n\n  @Column()\n  lastName: string;\n\n  @Column({ default: true })\n  isActive: boolean;\n}\n```\n\n> info **Hint** Learn more about entities in the [TypeORM documentation](https://typeorm.io/#/entities).\n\nThe `User` entity file sits in the `users` directory. This directory contains all files related to the `UsersModule`. You can decide where to keep your model files, however, we recommend creating them near their **domain**, in the corresponding module directory.\n\nTo begin using the `User` entity, we need to let TypeORM know about it by inserting it into the `entities` array in the module `forRoot()` method options (unless you use a static glob path):\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './users/user.entity';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      type: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      entities: [User],\n      synchronize: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nNext, let's look at the `UsersModule`:\n\n```typescript\n@@filename(users.module)\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\nimport { User } from './user.entity';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  providers: [UsersService],\n  controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\nThis module uses the `forFeature()` method to define which repositories are registered in the current scope. With that in place, we can inject the `UsersRepository` into the `UsersService` using the `@InjectRepository()` decorator:\n\n```typescript\n@@filename(users.service)\nimport { Injectable } from '@nestjs/common';\nimport { InjectRepository } from '@nestjs/typeorm';\nimport { Repository } from 'typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectRepository(User)\n    private usersRepository: Repository<User>,\n  ) {}\n\n  findAll(): Promise<User[]> {\n    return this.usersRepository.find();\n  }\n\n  findOne(id: string): Promise<User> {\n    return this.usersRepository.findOne(id);\n  }\n\n  async remove(id: string): Promise<void> {\n    await this.usersRepository.delete(id);\n  }\n}\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { getRepositoryToken } from '@nestjs/typeorm';\nimport { User } from './user.entity';\n\n@Injectable()\n@Dependencies(getRepositoryToken(User))\nexport class UsersService {\n  constructor(usersRepository) {\n    this.usersRepository = usersRepository;\n  }\n\n  findAll() {\n    return this.usersRepository.find();\n  }\n\n  findOne(id) {\n    return this.usersRepository.findOne(id);\n  }\n\n  async remove(id) {\n    await this.usersRepository.delete(id);\n  }\n}\n```\n\n> warning **Notice** Don't forget to import the `UsersModule` into the root `AppModule`.\n\nIf you want to use the repository outside of the module which imports `TypeOrmModule.forFeature`, you'll need to re-export the providers generated by it.\nYou can do this by exporting the whole module, like this:\n\n```typescript\n@@filename(users.module)\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './user.entity';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  exports: [TypeOrmModule]\n})\nexport class UsersModule {}\n```\n\nNow if we import `UsersModule` in `UserHttpModule`, we can use `@InjectRepository(User)` in the providers of the latter module.\n\n```typescript\n@@filename(users-http.module)\nimport { Module } from '@nestjs/common';\nimport { UsersModule } from './users.module';\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\n\n@Module({\n  imports: [UsersModule],\n  providers: [UsersService],\n  controllers: [UsersController]\n})\nexport class UserHttpModule {}\n```\n\n#### Relations\n\nRelations are associations established between two or more tables. Relations are based on common fields from each table, often involving primary and foreign keys.\n\nThere are three types of relations:\n\n<table>\n  <tr>\n    <td><code>One-to-one</code></td>\n    <td>Every row in the primary table has one and only one associated row in the foreign table.  Use the <code>@OneToOne()</code> decorator to define this type of relation.</td>\n  </tr>\n  <tr>\n    <td><code>One-to-many / Many-to-one</code></td>\n    <td>Every row in the primary table has one or more related rows in the foreign table. Use the <code>@OneToMany()</code> and <code>@ManyToOne()</code> decorators to define this type of relation.</td>\n  </tr>\n  <tr>\n    <td><code>Many-to-many</code></td>\n    <td>Every row in the primary table has many related rows in the foreign table, and every record in the foreign table has many related rows in the primary table. Use the <code>@ManyToMany()</code> decorator to define this type of relation.</td>\n  </tr>\n</table>\n\nTo define relations in entities, use the corresponding **decorators**. For example, to define that each `User` can have multiple photos, use the `@OneToMany()` decorator.\n\n```typescript\n@@filename(user.entity)\nimport { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';\nimport { Photo } from '../photos/photo.entity';\n\n@Entity()\nexport class User {\n  @PrimaryGeneratedColumn()\n  id: number;\n\n  @Column()\n  firstName: string;\n\n  @Column()\n  lastName: string;\n\n  @Column({ default: true })\n  isActive: boolean;\n\n  @OneToMany(type => Photo, photo => photo.user)\n  photos: Photo[];\n}\n```\n\n> info **Hint** To learn more about relations in TypeORM, visit the [TypeORM documentation](https://typeorm.io/#/relations).\n\n#### Auto-load entities\n\nManually adding entities to the `entities` array of the connection options can be tedious. In addition, referencing entities from the root module breaks application domain boundaries and causes leaking implementation details to other parts of the application. To solve this issue, static glob paths can be used (e.g., `dist/**/*.entity{{ '{' }} .ts,.js{{ '}' }}`).\n\nNote, however, that glob paths are not supported by webpack, so if you are building your application within a monorepo, you won't be able to use them. To address this issue, an alternative solution is provided. To automatically load entities, set the `autoLoadEntities` property of the configuration object (passed into the `forRoot()` method) to `true`, as shown below:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      ...\n      autoLoadEntities: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nWith that option specified, every entity registered through the `forFeature()` method will be automatically added to the `entities` array of the configuration object.\n\n> warning **Warning** Note that entities that aren't registered through the `forFeature()` method, but are only referenced from the entity (via a relationship), won't be included by way of the `autoLoadEntities` setting.\n\n#### Separating entity definition\n\nYou can define an entity and its columns right in the model, using decorators. But some people prefer to define entities and their columns inside separate files using the [\"entity schemas\"](https://typeorm.io/#/separating-entity-definition).\n\n```typescript\nimport { EntitySchema } from 'typeorm';\nimport { User } from './user.entity';\n\nexport const UserSchema = new EntitySchema<User>({\n  name: 'User',\n  target: User,\n  columns: {\n    id: {\n      type: Number,\n      primary: true,\n      generated: true,\n    },\n    firstName: {\n      type: String,\n    },\n    lastName: {\n      type: String,\n    },\n    isActive: {\n      type: Boolean,\n      default: true,\n    },\n  },\n  relations: {\n    photos: {\n      type: 'one-to-many',\n      target: 'Photo', // the name of the PhotoSchema\n    },\n  },\n});\n```\n\n> warning error **Warning** If you provide the `target` option, the `name` option value has to be the same as the name of the target class.\n> If you do not provide the `target` you can use any name.\n\nNest allows you to use an `EntitySchema` instance wherever an `Entity` is expected, for example:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { UserSchema } from './user.schema';\nimport { UsersController } from './users.controller';\nimport { UsersService } from './users.service';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([UserSchema])],\n  providers: [UsersService],\n  controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\n#### Transactions\n\nA database transaction symbolizes a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in a database ([learn more](https://en.wikipedia.org/wiki/Database_transaction)).\n\nThere are many different strategies to handle [TypeORM transactions](https://typeorm.io/#/transactions). We recommend using the `QueryRunner` class because it gives full control over the transaction.\n\nFirst, we need to inject the `Connection` object into a class in the normal way:\n\n```typescript\n@Injectable()\nexport class UsersService {\n  constructor(private connection: Connection) {}\n}\n```\n\n> info **Hint** The `Connection` class is imported from the `typeorm` package.\n\nNow, we can use this object to create a transaction.\n\n```typescript\nasync createMany(users: User[]) {\n  const queryRunner = this.connection.createQueryRunner();\n\n  await queryRunner.connect();\n  await queryRunner.startTransaction();\n  try {\n    await queryRunner.manager.save(users[0]);\n    await queryRunner.manager.save(users[1]);\n\n    await queryRunner.commitTransaction();\n  } catch (err) {\n    // since we have errors lets rollback the changes we made\n    await queryRunner.rollbackTransaction();\n  } finally {\n    // you need to release a queryRunner which was manually instantiated\n    await queryRunner.release();\n  }\n}\n```\n\n> info **Hint** Note that the `connection` is used only to create the `QueryRunner`. However, to test this class would require mocking the entire `Connection` object (which exposes several methods). Thus, we recommend using a helper factory class (e.g., `QueryRunnerFactory`) and defining an interface with a limited set of methods required to maintain transactions. This technique makes mocking these methods pretty straightforward.\n\nAlternatively, you can use the callback-style approach with the `transaction` method of the `Connection` object ([read more](https://typeorm.io/#/transactions/creating-and-using-transactions)).\n\n```typescript\nasync createMany(users: User[]) {\n  await this.connection.transaction(async manager => {\n    await manager.save(users[0]);\n    await manager.save(users[1]);\n  });\n}\n```\n\nUsing decorators to control the transaction (`@Transaction()` and `@TransactionManager()`) is not recommended.\n\n<app-banner-shop></app-banner-shop>\n\n#### Subscribers\n\nWith TypeORM [subscribers](https://typeorm.io/#/listeners-and-subscribers/what-is-a-subscriber), you can listen to specific entity events.\n\n```typescript\nimport {\n  Connection,\n  EntitySubscriberInterface,\n  EventSubscriber,\n  InsertEvent,\n} from 'typeorm';\nimport { User } from './user.entity';\n\n@EventSubscriber()\nexport class UserSubscriber implements EntitySubscriberInterface<User> {\n  constructor(connection: Connection) {\n    connection.subscribers.push(this);\n  }\n\n  listenTo() {\n    return User;\n  }\n\n  beforeInsert(event: InsertEvent<User>) {\n    console.log(`BEFORE USER INSERTED: `, event.entity);\n  }\n}\n```\n\n> error **Warning** Event subscribers can not be [request-scoped](/fundamentals/injection-scopes).\n\nNow, add the `UserSubscriber` class to the `providers` array:\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { TypeOrmModule } from '@nestjs/typeorm';\nimport { User } from './user.entity';\nimport { UsersController } from './users.controller';\nimport { UsersService } from './users.service';\nimport { UserSubscriber } from './user.subscriber';\n\n@Module({\n  imports: [TypeOrmModule.forFeature([User])],\n  providers: [UsersService, UserSubscriber],\n  controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\n> info **Hint** Learn more about entity subscribers [here](https://typeorm.io/#/listeners-and-subscribers/what-is-a-subscriber).\n\n#### Migrations\n\n[Migrations](https://typeorm.io/#/migrations) provide a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data in the database. To generate, run, and revert migrations, TypeORM provides a dedicated [CLI](https://typeorm.io/#/migrations/creating-a-new-migration).\n\nMigration classes are separate from the Nest application source code. Their lifecycle is maintained by the TypeORM CLI. Therefore, you are not able to leverage dependency injection and other Nest specific features with migrations. To learn more about migrations, follow the guide in the [TypeORM documentation](https://typeorm.io/#/migrations/creating-a-new-migration).\n\n#### Multiple databases\n\nSome projects require multiple database connections. This can also be achieved with this module. To work with multiple connections, first create the connections. In this case, connection naming becomes **mandatory**.\n\nSuppose you have an `Album` entity stored in its own database.\n\n```typescript\nconst defaultOptions = {\n  type: 'postgres',\n  port: 5432,\n  username: 'user',\n  password: 'password',\n  database: 'db',\n  synchronize: true,\n};\n\n@Module({\n  imports: [\n    TypeOrmModule.forRoot({\n      ...defaultOptions,\n      host: 'user_db_host',\n      entities: [User],\n    }),\n    TypeOrmModule.forRoot({\n      ...defaultOptions,\n      name: 'albumsConnection',\n      host: 'album_db_host',\n      entities: [Album],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n> warning **Notice** If you don't set the `name` for a connection, its name is set to `default`. Please note that you shouldn't have multiple connections without a name, or with the same name, otherwise they will get overridden.\n\nAt this point, you have `User` and `Album` entities registered with their own connection. With this setup, you have to tell the `TypeOrmModule.forFeature()` method and the `@InjectRepository()` decorator which connection should be used. If you do not pass any connection name, the `default` connection is used.\n\n```typescript\n@Module({\n  imports: [\n    TypeOrmModule.forFeature([User]),\n    TypeOrmModule.forFeature([Album], 'albumsConnection'),\n  ],\n})\nexport class AppModule {}\n```\n\nYou can also inject the `Connection` or `EntityManager` for a given connection:\n\n```typescript\n@Injectable()\nexport class AlbumsService {\n  constructor(\n    @InjectConnection('albumsConnection')\n    private connection: Connection,\n    @InjectEntityManager('albumsConnection')\n    private entityManager: EntityManager,\n  ) {}\n}\n```\n\nIt's also possible to inject any `Connection` to the providers:\n\n```typescript\n@Module({\n  providers: [\n    {\n      provide: AlbumsService,\n      useFactory: (albumsConnection: Connection) => {\n        return new AlbumsService(albumsConnection);\n      },\n      inject: [getConnectionToken('albumsConnection')],\n    },\n  ],\n})\nexport class AlbumsModule {}\n```\n\n#### Testing\n\nWhen it comes to unit testing an application, we usually want to avoid making a database connection, keeping our test suites independent and their execution process as fast as possible. But our classes might depend on repositories that are pulled from the connection instance. How do we handle that? The solution is to create mock repositories. In order to achieve that, we set up [custom providers](/fundamentals/custom-providers). Each registered repository is automatically represented by an `<EntityName>Repository` token, where `EntityName` is the name of your entity class.\n\nThe `@nestjs/typeorm` package exposes the `getRepositoryToken()` function which returns a prepared token based on a given entity.\n\n```typescript\n@Module({\n  providers: [\n    UsersService,\n    {\n      provide: getRepositoryToken(User),\n      useValue: mockRepository,\n    },\n  ],\n})\nexport class UsersModule {}\n```\n\nNow a substitute `mockRepository` will be used as the `UsersRepository`. Whenever any class asks for `UsersRepository` using an `@InjectRepository()` decorator, Nest will use the registered `mockRepository` object.\n\n#### Custom repository\n\nTypeORM provides a feature called **custom repositories**. Custom repositories allow you to extend a base repository class, and enrich it with several special methods. To learn more about this feature, visit [this page](https://typeorm.io/#/custom-repository). Be aware that custom repositories are outside of NestJS's Dependency Injection system, thus you can't inject any values into them.\n\nIn order to create your custom repository, use the `@EntityRepository()` decorator and extend the `Repository` class.\n\n```typescript\n@EntityRepository(Author)\nexport class AuthorRepository extends Repository<Author> {}\n```\n\n> info **Hint** Both `@EntityRepository()` and `Repository` are imported from the `typeorm` package.\n\nOnce the class is created, the next step is to delegate instantiation responsibility to Nest. For this, we have to pass the`AuthorRepository` class to the `TypeOrm.forFeature()` method.\n\n```typescript\n@Module({\n  imports: [TypeOrmModule.forFeature([AuthorRepository])],\n  controller: [AuthorController],\n  providers: [AuthorService],\n})\nexport class AuthorModule {}\n```\n\nAfterward, simply inject the repository using the following construction:\n\n```typescript\n@Injectable()\nexport class AuthorService {\n  constructor(private authorRepository: AuthorRepository) {}\n}\n```\n\n#### Async configuration\n\nYou may want to pass your repository module options asynchronously instead of statically. In this case, use the `forRootAsync()` method, which provides several ways to deal with async configuration.\n\nOne approach is to use a factory function:\n\n```typescript\nTypeOrmModule.forRootAsync({\n  useFactory: () => ({\n    type: 'mysql',\n    host: 'localhost',\n    port: 3306,\n    username: 'root',\n    password: 'root',\n    database: 'test',\n    entities: [__dirname + '/**/*.entity{.ts,.js}'],\n    synchronize: true,\n  }),\n});\n```\n\nOur factory behaves like any other [asynchronous provider](https://docs.nestjs.com/fundamentals/async-providers) (e.g., it can be `async` and it's able to inject dependencies through `inject`).\n\n```typescript\nTypeOrmModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: (configService: ConfigService) => ({\n    type: 'mysql',\n    host: configService.get('HOST'),\n    port: +configService.get<number>('PORT'),\n    username: configService.get('USERNAME'),\n    password: configService.get('PASSWORD'),\n    database: configService.get('DATABASE'),\n    entities: [__dirname + '/**/*.entity{.ts,.js}'],\n    synchronize: true,\n  }),\n  inject: [ConfigService],\n});\n```\n\nAlternatively, you can use the `useClass` syntax:\n\n```typescript\nTypeOrmModule.forRootAsync({\n  useClass: TypeOrmConfigService,\n});\n```\n\nThe construction above will instantiate `TypeOrmConfigService` inside `TypeOrmModule` and use it to provide an options object by calling `createTypeOrmOptions()`. Note that this means that the `TypeOrmConfigService` has to implement the `TypeOrmOptionsFactory` interface, as shown below:\n\n```typescript\n@Injectable()\nclass TypeOrmConfigService implements TypeOrmOptionsFactory {\n  createTypeOrmOptions(): TypeOrmModuleOptions {\n    return {\n      type: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      entities: [__dirname + '/**/*.entity{.ts,.js}'],\n      synchronize: true,\n    };\n  }\n}\n```\n\nIn order to prevent the creation of `TypeOrmConfigService` inside `TypeOrmModule` and use a provider imported from a different module, you can use the `useExisting` syntax.\n\n```typescript\nTypeOrmModule.forRootAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n});\n```\n\nThis construction works the same as `useClass` with one critical difference - `TypeOrmModule` will lookup imported modules to reuse an existing `ConfigService` instead of instantiating a new one.\n\n> info **Hint** Make sure that the `name` property is defined at the same level as the `useFactory`, `useClass`, or `useValue` property. This will allow Nest to properly register the connection under the appropriate injection token.\n\n#### Custom Connection Factory\n\nIn conjunction with async configuration using `useFactory`, `useClass`, or `useExisting`, you can optionally specify a `connectionFactory` function which will allow you to provide your own TypeORM connection rather than allowing `TypeOrmModule` to create the connection.\n\n`connectionFactory` receives the TypeORM `ConnectionOptions` configured during async configuration using `useFactory`, `useClass`, or `useExisting` and returns a `Promise` that resolves a TypeORM `Connection`.\n\n```typescript\nTypeOrmModule.forRootAsync({\n  imports: [ConfigModule],\n  inject: [ConfigService],\n  // Use useFactory, useClass, or useExisting\n  // to configure the ConnectionOptions.\n  useFactory: (configService: ConfigService) => ({\n    type: 'mysql',\n    host: configService.get('HOST'),\n    port: +configService.get<number>('PORT'),\n    username: configService.get('USERNAME'),\n    password: configService.get('PASSWORD'),\n    database: configService.get('DATABASE'),\n    entities: [__dirname + '/**/*.entity{.ts,.js}'],\n    synchronize: true,\n  }),\n  // connectionFactory receives the configured ConnectionOptions\n  // and returns a Promise<Connection>.\n  connectionFactory: async (options) => {\n    const connection = await createConnection(options);\n    return connection;\n  },\n});\n```\n\n> info **Hint** The `createConnection` function is imported from the `typeorm` package.\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/05-sql-typeorm).\n\n<app-banner-enterprise></app-banner-enterprise>\n\n### Sequelize Integration\n\nAn alternative to using TypeORM is to use the [Sequelize](https://sequelize.org/) ORM with the `@nestjs/sequelize` package. In addition, we leverage the [sequelize-typescript](https://github.com/RobinBuschmann/sequelize-typescript) package which provides a set of additional decorators to declaratively define entities.\n\nTo begin using it, we first install the required dependencies. In this chapter, we'll demonstrate using the popular [MySQL](https://www.mysql.com/) Relational DBMS, but Sequelize provides support for many relational databases, such as PostgreSQL, MySQL, Microsoft SQL Server, SQLite, and MariaDB. The procedure we walk through in this chapter will be the same for any database supported by Sequelize. You'll simply need to install the associated client API libraries for your selected database.\n\n```bash\n$ npm install --save @nestjs/sequelize sequelize sequelize-typescript mysql2\n$ npm install --save-dev @types/sequelize\n```\n\nOnce the installation process is complete, we can import the `SequelizeModule` into the root `AppModule`.\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { SequelizeModule } from '@nestjs/sequelize';\n\n@Module({\n  imports: [\n    SequelizeModule.forRoot({\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      models: [],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nThe `forRoot()` method supports all the configuration properties exposed by the Sequelize constructor ([read more](https://sequelize.org/v5/manual/getting-started.html#setting-up-a-connection)). In addition, there are several extra configuration properties described below.\n\n<table>\n  <tr>\n    <td><code>retryAttempts</code></td>\n    <td>Number of attempts to connect to the database (default: <code>10</code>)</td>\n  </tr>\n  <tr>\n    <td><code>retryDelay</code></td>\n    <td>Delay between connection retry attempts (ms) (default: <code>3000</code>)</td>\n  </tr>\n  <tr>\n    <td><code>autoLoadModels</code></td>\n    <td>If <code>true</code>, models will be loaded automatically (default: <code>false</code>)</td>\n  </tr>\n  <tr>\n    <td><code>keepConnectionAlive</code></td>\n    <td>If <code>true</code>, connection will not be closed on the application shutdown (default: <code>false</code>)</td>\n  </tr>\n  <tr>\n    <td><code>synchronize</code></td>\n    <td>If <code>true</code>, automatically loaded models will be synchronized (default: <code>true</code>)</td>\n  </tr>\n</table>\n\nOnce this is done, the `Sequelize` object will be available to inject across the entire project (without needing to import any modules), for example:\n\n```typescript\n@@filename(app.service)\nimport { Injectable } from '@nestjs/common';\nimport { Sequelize } from 'sequelize-typescript';\n\n@Injectable()\nexport class AppService {\n  constructor(private sequelize: Sequelize) {}\n}\n@@switch\nimport { Injectable } from '@nestjs/common';\nimport { Sequelize } from 'sequelize-typescript';\n\n@Dependencies(Sequelize)\n@Injectable()\nexport class AppService {\n  constructor(sequelize) {\n    this.sequelize = sequelize;\n  }\n}\n```\n\n#### Models\n\nSequelize implements the Active Record pattern. With this pattern, you use model classes directly to interact with the database. To continue the example, we need at least one model. Let's define the `User` model.\n\n```typescript\n@@filename(user.model)\nimport { Column, Model, Table } from 'sequelize-typescript';\n\n@Table\nexport class User extends Model {\n  @Column\n  firstName: string;\n\n  @Column\n  lastName: string;\n\n  @Column({ defaultValue: true })\n  isActive: boolean;\n}\n```\n\n> info **Hint** Learn more about the available decorators [here](https://github.com/RobinBuschmann/sequelize-typescript#column).\n\nThe `User` model file sits in the `users` directory. This directory contains all files related to the `UsersModule`. You can decide where to keep your model files, however, we recommend creating them near their **domain**, in the corresponding module directory.\n\nTo begin using the `User` model, we need to let Sequelize know about it by inserting it into the `models` array in the module `forRoot()` method options:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { SequelizeModule } from '@nestjs/sequelize';\nimport { User } from './users/user.model';\n\n@Module({\n  imports: [\n    SequelizeModule.forRoot({\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      models: [User],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nNext, let's look at the `UsersModule`:\n\n```typescript\n@@filename(users.module)\nimport { Module } from '@nestjs/common';\nimport { SequelizeModule } from '@nestjs/sequelize';\nimport { User } from './user.model';\nimport { UsersController } from './users.controller';\nimport { UsersService } from './users.service';\n\n@Module({\n  imports: [SequelizeModule.forFeature([User])],\n  providers: [UsersService],\n  controllers: [UsersController],\n})\nexport class UsersModule {}\n```\n\nThis module uses the `forFeature()` method to define which models are registered in the current scope. With that in place, we can inject the `UserModel` into the `UsersService` using the `@InjectModel()` decorator:\n\n```typescript\n@@filename(users.service)\nimport { Injectable } from '@nestjs/common';\nimport { InjectModel } from '@nestjs/sequelize';\nimport { User } from './user.model';\n\n@Injectable()\nexport class UsersService {\n  constructor(\n    @InjectModel(User)\n    private userModel: typeof User,\n  ) {}\n\n  async findAll(): Promise<User[]> {\n    return this.userModel.findAll();\n  }\n\n  findOne(id: string): Promise<User> {\n    return this.userModel.findOne({\n      where: {\n        id,\n      },\n    });\n  }\n\n  async remove(id: string): Promise<void> {\n    const user = await this.findOne(id);\n    await user.destroy();\n  }\n}\n@@switch\nimport { Injectable, Dependencies } from '@nestjs/common';\nimport { getModelToken } from '@nestjs/sequelize';\nimport { User } from './user.model';\n\n@Injectable()\n@Dependencies(getModelToken(User))\nexport class UsersService {\n  constructor(usersRepository) {\n    this.usersRepository = usersRepository;\n  }\n\n  async findAll() {\n    return this.userModel.findAll();\n  }\n\n  findOne(id) {\n    return this.userModel.findOne({\n      where: {\n        id,\n      },\n    });\n  }\n\n  async remove(id) {\n    const user = await this.findOne(id);\n    await user.destroy();\n  }\n}\n```\n\n> warning **Notice** Don't forget to import the `UsersModule` into the root `AppModule`.\n\nIf you want to use the repository outside of the module which imports `SequelizeModule.forFeature`, you'll need to re-export the providers generated by it.\nYou can do this by exporting the whole module, like this:\n\n```typescript\n@@filename(users.module)\nimport { Module } from '@nestjs/common';\nimport { SequelizeModule } from '@nestjs/sequelize';\nimport { User } from './user.entity';\n\n@Module({\n  imports: [SequelizeModule.forFeature([User])],\n  exports: [SequelizeModule]\n})\nexport class UsersModule {}\n```\n\nNow if we import `UsersModule` in `UserHttpModule`, we can use `@InjectModel(User)` in the providers of the latter module.\n\n```typescript\n@@filename(users-http.module)\nimport { Module } from '@nestjs/common';\nimport { UsersModule } from './users.module';\nimport { UsersService } from './users.service';\nimport { UsersController } from './users.controller';\n\n@Module({\n  imports: [UsersModule],\n  providers: [UsersService],\n  controllers: [UsersController]\n})\nexport class UserHttpModule {}\n```\n\n#### Relations\n\nRelations are associations established between two or more tables. Relations are based on common fields from each table, often involving primary and foreign keys.\n\nThere are three types of relations:\n\n<table>\n  <tr>\n    <td><code>One-to-one</code></td>\n    <td>Every row in the primary table has one and only one associated row in the foreign table</td>\n  </tr>\n  <tr>\n    <td><code>One-to-many / Many-to-one</code></td>\n    <td>Every row in the primary table has one or more related rows in the foreign table</td>\n  </tr>\n  <tr>\n    <td><code>Many-to-many</code></td>\n    <td>Every row in the primary table has many related rows in the foreign table, and every record in the foreign table has many related rows in the primary table</td>\n  </tr>\n</table>\n\nTo define relations in entities, use the corresponding **decorators**. For example, to define that each `User` can have multiple photos, use the `@HasMany()` decorator.\n\n```typescript\n@@filename(user.entity)\nimport { Column, Model, Table, HasMany } from 'sequelize-typescript';\nimport { Photo } from '../photos/photo.model';\n\n@Table\nexport class User extends Model {\n  @Column\n  firstName: string;\n\n  @Column\n  lastName: string;\n\n  @Column({ defaultValue: true })\n  isActive: boolean;\n\n  @HasMany(() => Photo)\n  photos: Photo[];\n}\n```\n\n> info **Hint** To learn more about associations in Sequelize, read [this](https://github.com/RobinBuschmann/sequelize-typescript#model-association) chapter.\n\n#### Auto-load models\n\nManually adding models to the `models` array of the connection options can be tedious. In addition, referencing models from the root module breaks application domain boundaries and causes leaking implementation details to other parts of the application. To solve this issue, automatically load models by setting both `autoLoadModels` and `synchronize` properties of the configuration object (passed into the `forRoot()` method) to `true`, as shown below:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { SequelizeModule } from '@nestjs/sequelize';\n\n@Module({\n  imports: [\n    SequelizeModule.forRoot({\n      ...\n      autoLoadModels: true,\n      synchronize: true,\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\nWith that option specified, every model registered through the `forFeature()` method will be automatically added to the `models` array of the configuration object.\n\n> warning **Warning** Note that models that aren't registered through the `forFeature()` method, but are only referenced from the model (via an association), won't be included.\n\n#### Transactions\n\nA database transaction symbolizes a unit of work performed within a database management system against a database, and treated in a coherent and reliable way independent of other transactions. A transaction generally represents any change in a database ([learn more](https://en.wikipedia.org/wiki/Database_transaction)).\n\nThere are many different strategies to handle [Sequelize transactions](https://sequelize.org/v5/manual/transactions.html). Below is a sample implementation of a managed transaction (auto-callback).\n\nFirst, we need to inject the `Sequelize` object into a class in the normal way:\n\n```typescript\n@Injectable()\nexport class UsersService {\n  constructor(private sequelize: Sequelize) {}\n}\n```\n\n> info **Hint** The `Sequelize` class is imported from the `sequelize-typescript` package.\n\nNow, we can use this object to create a transaction.\n\n```typescript\nasync createMany() {\n  try {\n    await this.sequelize.transaction(async t => {\n      const transactionHost = { transaction: t };\n\n      await this.userModel.create(\n          { firstName: 'Abraham', lastName: 'Lincoln' },\n          transactionHost,\n      );\n      await this.userModel.create(\n          { firstName: 'John', lastName: 'Boothe' },\n          transactionHost,\n      );\n    });\n  } catch (err) {\n    // Transaction has been rolled back\n    // err is whatever rejected the promise chain returned to the transaction callback\n  }\n}\n```\n\n> info **Hint** Note that the `Sequelize` instance is used only to start the transaction. However, to test this class would require mocking the entire `Sequelize` object (which exposes several methods). Thus, we recommend using a helper factory class (e.g., `TransactionRunner`) and defining an interface with a limited set of methods required to maintain transactions. This technique makes mocking these methods pretty straightforward.\n\n#### Migrations\n\n[Migrations](https://sequelize.org/v5/manual/migrations.html) provide a way to incrementally update the database schema to keep it in sync with the application's data model while preserving existing data in the database. To generate, run, and revert migrations, Sequelize provides a dedicated [CLI](https://sequelize.org/v5/manual/migrations.html#the-cli).\n\nMigration classes are separate from the Nest application source code. Their lifecycle is maintained by the Sequelize CLI. Therefore, you are not able to leverage dependency injection and other Nest specific features with migrations. To learn more about migrations, follow the guide in the [Sequelize documentation](https://sequelize.org/v5/manual/migrations.html#the-cli).\n\n<app-banner-courses></app-banner-courses>\n\n#### Multiple databases\n\nSome projects require multiple database connections. This can also be achieved with this module. To work with multiple connections, first create the connections. In this case, connection naming becomes **mandatory**.\n\nSuppose you have an `Album` entity stored in its own database.\n\n```typescript\nconst defaultOptions = {\n  dialect: 'postgres',\n  port: 5432,\n  username: 'user',\n  password: 'password',\n  database: 'db',\n  synchronize: true,\n};\n\n@Module({\n  imports: [\n    SequelizeModule.forRoot({\n      ...defaultOptions,\n      host: 'user_db_host',\n      models: [User],\n    }),\n    SequelizeModule.forRoot({\n      ...defaultOptions,\n      name: 'albumsConnection',\n      host: 'album_db_host',\n      models: [Album],\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n> warning **Notice** If you don't set the `name` for a connection, its name is set to `default`. Please note that you shouldn't have multiple connections without a name, or with the same name, otherwise they will get overridden.\n\nAt this point, you have `User` and `Album` models registered with their own connection. With this setup, you have to tell the `SequelizeModule.forFeature()` method and the `@InjectModel()` decorator which connection should be used. If you do not pass any connection name, the `default` connection is used.\n\n```typescript\n@Module({\n  imports: [\n    SequelizeModule.forFeature([User]),\n    SequelizeModule.forFeature([Album], 'albumsConnection'),\n  ],\n})\nexport class AppModule {}\n```\n\nYou can also inject the `Sequelize` instance for a given connection:\n\n```typescript\n@Injectable()\nexport class AlbumsService {\n  constructor(\n    @InjectConnection('albumsConnection')\n    private sequelize: Sequelize,\n  ) {}\n}\n```\n\nIt's also possible to inject any `Sequelize` instance to the providers:\n\n```typescript\n@Module({\n  providers: [\n    {\n      provide: AlbumsService,\n      useFactory: (albumsSequelize: Sequelize) => {\n        return new AlbumsService(albumsSequelize);\n      },\n      inject: [getConnectionToken('albumsConnection')],\n    },\n  ],\n})\nexport class AlbumsModule {}\n```\n\n#### Testing\n\nWhen it comes to unit testing an application, we usually want to avoid making a database connection, keeping our test suites independent and their execution process as fast as possible. But our classes might depend on models that are pulled from the connection instance. How do we handle that? The solution is to create mock models. In order to achieve that, we set up [custom providers](/fundamentals/custom-providers). Each registered model is automatically represented by a `<ModelName>Model` token, where `ModelName` is the name of your model class.\n\nThe `@nestjs/sequelize` package exposes the `getModelToken()` function which returns a prepared token based on a given model.\n\n```typescript\n@Module({\n  providers: [\n    UsersService,\n    {\n      provide: getModelToken(User),\n      useValue: mockModel,\n    },\n  ],\n})\nexport class UsersModule {}\n```\n\nNow a substitute `mockModel` will be used as the `UserModel`. Whenever any class asks for `UserModel` using an `@InjectModel()` decorator, Nest will use the registered `mockModel` object.\n\n#### Async configuration\n\nYou may want to pass your `SequelizeModule` options asynchronously instead of statically. In this case, use the `forRootAsync()` method, which provides several ways to deal with async configuration.\n\nOne approach is to use a factory function:\n\n```typescript\nSequelizeModule.forRootAsync({\n  useFactory: () => ({\n    dialect: 'mysql',\n    host: 'localhost',\n    port: 3306,\n    username: 'root',\n    password: 'root',\n    database: 'test',\n    models: [],\n  }),\n});\n```\n\nOur factory behaves like any other [asynchronous provider](https://docs.nestjs.com/fundamentals/async-providers) (e.g., it can be `async` and it's able to inject dependencies through `inject`).\n\n```typescript\nSequelizeModule.forRootAsync({\n  imports: [ConfigModule],\n  useFactory: (configService: ConfigService) => ({\n    dialect: 'mysql',\n    host: configService.get('HOST'),\n    port: +configService.get('PORT'),\n    username: configService.get('USERNAME'),\n    password: configService.get('PASSWORD'),\n    database: configService.get('DATABASE'),\n    models: [],\n  }),\n  inject: [ConfigService],\n});\n```\n\nAlternatively, you can use the `useClass` syntax:\n\n```typescript\nSequelizeModule.forRootAsync({\n  useClass: SequelizeConfigService,\n});\n```\n\nThe construction above will instantiate `SequelizeConfigService` inside `SequelizeModule` and use it to provide an options object by calling `createSequelizeOptions()`. Note that this means that the `SequelizeConfigService` has to implement the `SequelizeOptionsFactory` interface, as shown below:\n\n```typescript\n@Injectable()\nclass SequelizeConfigService implements SequelizeOptionsFactory {\n  createSequelizeOptions(): SequelizeModuleOptions {\n    return {\n      dialect: 'mysql',\n      host: 'localhost',\n      port: 3306,\n      username: 'root',\n      password: 'root',\n      database: 'test',\n      models: [],\n    };\n  }\n}\n```\n\nIn order to prevent the creation of `SequelizeConfigService` inside `SequelizeModule` and use a provider imported from a different module, you can use the `useExisting` syntax.\n\n```typescript\nSequelizeModule.forRootAsync({\n  imports: [ConfigModule],\n  useExisting: ConfigService,\n});\n```\n\nThis construction works the same as `useClass` with one critical difference - `SequelizeModule` will lookup imported modules to reuse an existing `ConfigService` instead of instantiating a new one.\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/07-sequelize).\n"
  },
  {
    "path": "content/techniques/streaming-files.md",
    "content": "### Streaming files\n\n> info **Note** This chapter shows how you can stream files from your **HTTP application**. The examples presented below do not apply to GraphQL or Microservice applications.\n\nThere may be times where you would like to send back a file from your REST API to the client. To do this with Nest, normally you'd do the following:\n\n```ts\n@Controller('file')\nexport class FileController {\n  @Get()\n  getFile(@Res() res: Response) {\n    const file = createReadStream(join(process.cwd(), 'package.json'));\n    file.pipe(res);\n  }\n}\n```\n\nBut in doing so you end up losing access to your post-controller interceptor logic. To handle this, you can return a `StreamableFile` instance and under the hood, the framework will take care of piping the response.\n\n#### Streamable File class\n\nA `StreamableFile` is a class that holds onto the stream that is to be returned. To create a new `StreamableFile`, you can pass either a `Buffer` or a `Stream` to the `StreamableFile` constructor.\n\n> info **hint** The `StreamableFile` class can be imported from `@nestjs/common`.\n\n#### Cross-platform support\n\nFastify, by default, can support sending files without needing to call `stream.pipe(res)`, so you don't need to use the `StreamableFile` class at all. However, Nest supports the use of `StreamableFile` in both platform types, so if you end up switching between Express and Fastify there's no need to worry about compatibility between the two engines.\n\n#### Example\n\nYou can find a simple example of returning the `package.json` as a file instead of a JSON below, but the idea extends out naturally to images, documents, and any other file type.\n\n```ts\nimport { Controller, Get, StreamableFile } from '@nestjs/common';\nimport { createReadStream } from 'fs';\nimport { join } from 'path';\n\n@Controller('file')\nexport class FileController {\n  @Get()\n  getFile(): StreamableFile {\n    const file = createReadStream(join(process.cwd(), 'package.json'));\n    return new StreamableFile(file);\n  }\n}\n```\n\nThe default content type is `application/octet-stream`, if you need to customize the response you can use the `res.set` method.\n\n\n```ts\nimport { Controller, Get, StreamableFile, Response } from '@nestjs/common';\nimport { createReadStream } from 'fs';\nimport { join } from 'path';\n\n@Controller('file')\nexport class FileController {\n  @Get()\n  getFile(@Response({ passthrough: true }) res): StreamableFile {\n    const file = createReadStream(join(process.cwd(), 'package.json'));\n    res.set({\n      'Content-Type': 'application/json',\n      'Content-Disposition': 'attachment; filename=\"package.json\"',\n    });\n    return new StreamableFile(file);\n  }\n}\n```"
  },
  {
    "path": "content/techniques/task-scheduling.md",
    "content": "### Task Scheduling\n\nTask scheduling allows you to schedule arbitrary code (methods/functions) to execute at a fixed date/time, at recurring intervals, or once after a specified interval. In the Linux world, this is often handled by packages like [cron](https://en.wikipedia.org/wiki/Cron) at the OS level. For Node.js apps, there are several packages that emulate cron-like functionality. Nest provides the `@nestjs/schedule` package, which integrates with the popular Node.js [node-cron](https://github.com/kelektiv/node-cron) package. We'll cover this package in the current chapter.\n\n#### Installation\n\nTo begin using it, we first install the required dependencies.\n\n```bash\n$ npm install --save @nestjs/schedule\n$ npm install --save-dev @types/cron\n```\n\nTo activate job scheduling, import the `ScheduleModule` into the root `AppModule` and run the `forRoot()` static method as shown below:\n\n```typescript\n@@filename(app.module)\nimport { Module } from '@nestjs/common';\nimport { ScheduleModule } from '@nestjs/schedule';\n\n@Module({\n  imports: [\n    ScheduleModule.forRoot()\n  ],\n})\nexport class AppModule {}\n```\n\nThe `.forRoot()` call initializes the scheduler and registers any declarative <a href=\"techniques/task-scheduling#declarative-cron-jobs\">cron jobs</a>, <a href=\"techniques/task-scheduling#declarative-timeouts\">timeouts</a> and <a href=\"techniques/task-scheduling#declarative-intervals\">intervals</a> that exist within your app. Registration occurs when the `onApplicationBootstrap` lifecycle hook occurs, ensuring that all modules have loaded and declared any scheduled jobs.\n\n#### Declarative cron jobs\n\nA cron job schedules an arbitrary function (method call) to run automatically. Cron jobs can run:\n\n- Once, at a specified date/time.\n- On a recurring basis; recurring jobs can run at a specified instant within a specified interval (for example, once per hour, once per week, once every 5 minutes)\n\nDeclare a cron job with the `@Cron()` decorator preceding the method definition containing the code to be executed, as follows:\n\n```typescript\nimport { Injectable, Logger } from '@nestjs/common';\nimport { Cron } from '@nestjs/schedule';\n\n@Injectable()\nexport class TasksService {\n  private readonly logger = new Logger(TasksService.name);\n\n  @Cron('45 * * * * *')\n  handleCron() {\n    this.logger.debug('Called when the current second is 45');\n  }\n}\n```\n\nIn this example, the `handleCron()` method will be called each time the current second is `45`. In other words, the method will be run once per minute, at the 45 second mark.\n\nThe `@Cron()` decorator supports all standard [cron patterns](http://crontab.org/):\n\n- Asterisk (e.g. `*`)\n- Ranges (e.g. `1-3,5`)\n- Steps (e.g. `*/2`)\n\nIn the example above, we passed `45 * * * * *` to the decorator. The following key shows how each position in the cron pattern string is interpreted:\n\n<pre class=\"language-javascript\"><code class=\"language-javascript\">\n* * * * * *\n| | | | | |\n| | | | | day of week\n| | | | month\n| | | day of month\n| | hour\n| minute\nsecond (optional)\n</code></pre>\n\nSome sample cron patterns are:\n\n<table>\n  <tbody>\n    <tr>\n      <td><code>* * * * * *</code></td>\n      <td>every second</td>\n    </tr>\n    <tr>\n      <td><code>45 * * * * *</code></td>\n      <td>every minute, on the 45th second</td>\n    </tr>\n    <tr>\n      <td><code>0 10 * * * *</code></td>\n      <td>every hour, at the start of the 10th minute</td>\n    </tr>\n    <tr>\n      <td><code>0 */30 9-17 * * *</code></td>\n      <td>every 30 minutes between 9am and 5pm</td>\n    </tr>\n   <tr>\n      <td><code>0 30 11 * * 1-5</code></td>\n      <td>Monday to Friday at 11:30am</td>\n    </tr>\n  </tbody>\n</table>\n\nThe `@nestjs/schedule` package provides a convenience enum with commonly used cron patterns. You can use this enum as follows:\n\n```typescript\nimport { Injectable, Logger } from '@nestjs/common';\nimport { Cron, CronExpression } from '@nestjs/schedule';\n\n@Injectable()\nexport class TasksService {\n  private readonly logger = new Logger(TasksService.name);\n\n  @Cron(CronExpression.EVERY_30_SECONDS)\n  handleCron() {\n    this.logger.debug('Called every 30 seconds');\n  }\n}\n```\n\nIn this example, the `handleCron()` method will be called every `30` seconds.\n\nAlternatively, you can supply a JavaScript `Date` object to the `@Cron()` decorator. Doing so causes the job to execute exactly once, at the specified date.\n\n> info **Hint** Use JavaScript date arithmetic to schedule jobs relative to the current date. For example, `@Cron(new Date(Date.now() + 10 * 1000))` to schedule a job to run 10 seconds after the app starts.\n\nAlso, you can supply additional options as the second parameter to the `@Cron()` decorator.\n\n<table>\n  <tbody>\n    <tr>\n      <td><code>name</code></td>\n      <td>\n        Useful to access and control a cron job after it's been declared.\n      </td>\n    </tr>\n    <tr>\n      <td><code>timeZone</code></td>\n      <td>\n        Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at <a href=\"http://momentjs.com/timezone/\">Moment Timezone</a> website.\n      </td>\n    </tr>\n    <tr>\n      <td><code>utcOffset</code></td>\n      <td>\n        This allows you to specify the offset of your timezone rather than using the <code>timeZone</code> param.\n      </td>\n    </tr>\n  </tbody>\n</table>\n\n```typescript\nimport { Injectable } from '@nestjs/common';\nimport { Cron, CronExpression } from '@nestjs/schedule';\n\n@Injectable()\nexport class NotificationService {\n  @Cron('* * 0 * * *', {\n    name: 'notifications',\n    timeZone: 'Europe/Paris',\n  })\n  triggerNotifications() {}\n}\n```\n\nYou can access and control a cron job after it's been declared, or dynamically create a cron job (where its cron pattern is defined at runtime) with the <a href=\"/techniques/task-scheduling#dynamic-schedule-module-api\">Dynamic API</a>. To access a declarative cron job via the API, you must associate the job with a name by passing the `name` property in an optional options object as the second argument of the decorator.\n\n#### Declarative intervals\n\nTo declare that a method should run at a (recurring) specified interval, prefix the method definition with the `@Interval()` decorator. Pass the interval value, as a number in milliseconds, to the decorator as shown below:\n\n```typescript\n@Interval(10000)\nhandleInterval() {\n  this.logger.debug('Called every 10 seconds');\n}\n```\n\n> info **Hint** This mechanism uses the JavaScript `setInterval()` function under the hood. You can also utilize a cron job to schedule recurring jobs.\n\nIf you want to control your declarative interval from outside the declaring class via the <a href=\"/techniques/task-scheduling#dynamic-schedule-module-api\">Dynamic API</a>, associate the interval with a name using the following construction:\n\n```typescript\n@Interval('notifications', 2500)\nhandleInterval() {}\n```\n\nThe <a href=\"techniques/task-scheduling#dynamic-intervals\">Dynamic API</a> also enables **creating** dynamic intervals, where the interval's properties are defined at runtime, and **listing and deleting** them.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Declarative timeouts\n\nTo declare that a method should run (once) at a specified timeout, prefix the method definition with the `@Timeout()` decorator. Pass the relative time offset (in milliseconds), from application startup, to the decorator as shown below:\n\n```typescript\n@Timeout(5000)\nhandleTimeout() {\n  this.logger.debug('Called once after 5 seconds');\n}\n```\n\n> info **Hint** This mechanism uses the JavaScript `setTimeout()` function under the hood.\n\nIf you want to control your declarative timeout from outside the declaring class via the <a href=\"/techniques/task-scheduling#dynamic-schedule-module-api\">Dynamic API</a>, associate the timeout with a name using the following construction:\n\n```typescript\n@Timeout('notifications', 2500)\nhandleTimeout() {}\n```\n\nThe <a href=\"techniques/task-scheduling#dynamic-timeouts\">Dynamic API</a> also enables **creating** dynamic timeouts, where the timeout's properties are defined at runtime, and **listing and deleting** them.\n\n#### Dynamic schedule module API\n\nThe `@nestjs/schedule` module provides a dynamic API that enables managing declarative <a href=\"techniques/task-scheduling#declarative-cron-jobs\">cron jobs</a>, <a href=\"techniques/task-scheduling#declarative-timeouts\">timeouts</a> and <a href=\"techniques/task-scheduling#declarative-intervals\">intervals</a>. The API also enables creating and managing **dynamic** cron jobs, timeouts and intervals, where the properties are defined at runtime.\n\n#### Dynamic cron jobs\n\nObtain a reference to a `CronJob` instance by name from anywhere in your code using the `SchedulerRegistry` API. First, inject `SchedulerRegistry` using standard constructor injection:\n\n```typescript\nconstructor(private schedulerRegistry: SchedulerRegistry) {}\n```\n\n> info **Hint** Import the `SchedulerRegistry` from the `@nestjs/schedule` package.\n\nThen use it in a class as follows. Assume a cron job was created with the following declaration:\n\n```typescript\n@Cron('* * 8 * * *', {\n  name: 'notifications',\n})\ntriggerNotifications() {}\n```\n\nAccess this job using the following:\n\n```typescript\nconst job = this.schedulerRegistry.getCronJob('notifications');\n\njob.stop();\nconsole.log(job.lastDate());\n```\n\nThe `getCronJob()` method returns the named cron job. The returned `CronJob` object has the following methods:\n\n- `stop()` - stops a job that is scheduled to run.\n- `start()` - restarts a job that has been stopped.\n- `setTime(time: CronTime)` - stops a job, sets a new time for it, and then starts it\n- `lastDate()` - returns a string representation of the last date a job executed\n- `nextDates(count: number)` - returns an array (size `count`) of `moment` objects representing upcoming job execution dates.\n\n> info **Hint** Use `toDate()` on `moment` objects to render them in human readable form.\n\n**Create** a new cron job dynamically using the `SchedulerRegistry.addCronJob()` method, as follows:\n\n```typescript\naddCronJob(name: string, seconds: string) {\n  const job = new CronJob(`${seconds} * * * * *`, () => {\n    this.logger.warn(`time (${seconds}) for job ${name} to run!`);\n  });\n\n  this.schedulerRegistry.addCronJob(name, job);\n  job.start();\n\n  this.logger.warn(\n    `job ${name} added for each minute at ${seconds} seconds!`,\n  );\n}\n```\n\nIn this code, we use the `CronJob` object from the `cron` package to create the cron job. The `CronJob` constructor takes a cron pattern (just like the `@Cron()` <a href=\"techniques/task-scheduling#declarative-cron-jobs\">decorator</a>) as its first argument, and a callback to be executed when the cron timer fires as its second argument. The `SchedulerRegistry.addCronJob()` method takes two arguments: a name for the `CronJob`, and the `CronJob` object itself.\n\n> warning **Warning** Remember to inject the `SchedulerRegistry` before accessing it. Import `CronJob` from the `cron` package.\n\n**Delete** a named cron job using the `SchedulerRegistry.deleteCronJob()` method, as follows:\n\n```typescript\ndeleteCron(name: string) {\n  this.schedulerRegistry.deleteCronJob(name);\n  this.logger.warn(`job ${name} deleted!`);\n}\n```\n\n**List** all cron jobs using the `SchedulerRegistry.getCronJobs()` method as follows:\n\n```typescript\ngetCrons() {\n  const jobs = this.schedulerRegistry.getCronJobs();\n  jobs.forEach((value, key, map) => {\n    let next;\n    try {\n      next = value.nextDates().toDate();\n    } catch (e) {\n      next = 'error: next fire date is in the past!';\n    }\n    this.logger.log(`job: ${key} -> next: ${next}`);\n  });\n}\n```\n\nThe `getCronJobs()` method returns a `map`. In this code, we iterate over the map and attempt to access the `nextDates()` method of each `CronJob`. In the `CronJob` API, if a job has already fired and has no future firing dates, it throws an exception.\n\n#### Dynamic intervals\n\nObtain a reference to an interval with the `SchedulerRegistry.getInterval()` method. As above, inject `SchedulerRegistry` using standard constructor injection:\n\n```typescript\nconstructor(private schedulerRegistry: SchedulerRegistry) {}\n```\n\nAnd use it as follows:\n\n```typescript\nconst interval = this.schedulerRegistry.getInterval('notifications');\nclearInterval(interval);\n```\n\n**Create** a new interval dynamically using the `SchedulerRegistry.addInterval()` method, as follows:\n\n```typescript\naddInterval(name: string, milliseconds: number) {\n  const callback = () => {\n    this.logger.warn(`Interval ${name} executing at time (${milliseconds})!`);\n  };\n\n  const interval = setInterval(callback, milliseconds);\n  this.schedulerRegistry.addInterval(name, interval);\n}\n```\n\nIn this code, we create a standard JavaScript interval, then pass it to the `ScheduleRegistry.addInterval()` method.\nThat method takes two arguments: a name for the interval, and the interval itself.\n\n**Delete** a named interval using the `SchedulerRegistry.deleteInterval()` method, as follows:\n\n```typescript\ndeleteInterval(name: string) {\n  this.schedulerRegistry.deleteInterval(name);\n  this.logger.warn(`Interval ${name} deleted!`);\n}\n```\n\n**List** all intervals using the `SchedulerRegistry.getIntervals()` method as follows:\n\n```typescript\ngetIntervals() {\n  const intervals = this.schedulerRegistry.getIntervals();\n  intervals.forEach(key => this.logger.log(`Interval: ${key}`));\n}\n```\n\n#### Dynamic timeouts\n\nObtain a reference to a timeout with the `SchedulerRegistry.getTimeout()` method. As above, inject `SchedulerRegistry` using standard constructor injection:\n\n```typescript\nconstructor(private schedulerRegistry: SchedulerRegistry) {}\n```\n\nAnd use it as follows:\n\n```typescript\nconst timeout = this.schedulerRegistry.getTimeout('notifications');\nclearTimeout(timeout);\n```\n\n**Create** a new timeout dynamically using the `SchedulerRegistry.addTimeout()` method, as follows:\n\n```typescript\naddTimeout(name: string, milliseconds: number) {\n  const callback = () => {\n    this.logger.warn(`Timeout ${name} executing after (${milliseconds})!`);\n  };\n\n  const timeout = setTimeout(callback, milliseconds);\n  this.schedulerRegistry.addTimeout(name, timeout);\n}\n```\n\nIn this code, we create a standard JavaScript timeout, then pass it to the `ScheduleRegistry.addTimeout()` method.\nThat method takes two arguments: a name for the timeout, and the timeout itself.\n\n**Delete** a named timeout using the `SchedulerRegistry.deleteTimeout()` method, as follows:\n\n```typescript\ndeleteTimeout(name: string) {\n  this.schedulerRegistry.deleteTimeout(name);\n  this.logger.warn(`Timeout ${name} deleted!`);\n}\n```\n\n**List** all timeouts using the `SchedulerRegistry.getTimeouts()` method as follows:\n\n```typescript\ngetTimeouts() {\n  const timeouts = this.schedulerRegistry.getTimeouts();\n  timeouts.forEach(key => this.logger.log(`Timeout: ${key}`));\n}\n```\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/27-scheduling).\n"
  },
  {
    "path": "content/techniques/validation.md",
    "content": "### Validation\n\nIt is best practice to validate the correctness of any data sent into a web application. To automatically validate incoming requests, Nest provides several pipes available right out-of-the-box:\n\n- `ValidationPipe`\n- `ParseIntPipe`\n- `ParseBoolPipe`\n- `ParseArrayPipe`\n- `ParseUUIDPipe`\n\nThe `ValidationPipe` makes use of the powerful [class-validator](https://github.com/typestack/class-validator) package and its declarative validation decorators. The `ValidationPipe` provides a convenient approach to enforce validation rules for all incoming client payloads, where the specific rules are declared with simple annotations in local class/DTO declarations in each module.\n\n#### Overview\n\nIn the [Pipes](/pipes) chapter, we went through the process of building simple pipes and binding them to controllers, methods or to the global app to demonstrate how the process works. Be sure to review that chapter to best understand the topics of this chapter. Here, we'll focus on various **real world** use cases of the `ValidationPipe`, and show how to use some of its advanced customization features.\n\n#### Using the built-in ValidationPipe\n\nTo begin using it, we first install the required dependency.\n\n```bash\n$ npm i --save class-validator class-transformer\n```\n\n> info **Hint** The `ValidationPipe` is exported from the `@nestjs/common` package.\n\nBecause this pipe uses the `class-validator` and `class-transformer` libraries, there are many options available. You configure these settings via a configuration object passed to the pipe. Following are the built-in options:\n\n```typescript\nexport interface ValidationPipeOptions extends ValidatorOptions {\n  transform?: boolean;\n  disableErrorMessages?: boolean;\n  exceptionFactory?: (errors: ValidationError[]) => any;\n}\n```\n\nIn addition to these, all `class-validator` options (inherited from the `ValidatorOptions` interface) are available:\n\n<table>\n  <tr>\n    <th>Option</th>\n    <th>Type</th>\n    <th>Description</th>\n  </tr>\n  <tr>\n    <td><code>enableDebugMessages</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, validator will print extra warning messages to the console when something is not right.</td>\n  </tr>\n  <tr>\n    <td><code>skipUndefinedProperties</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, validator will skip validation of all properties that are null in the validating object.</td>\n  </tr>\n  <tr>\n    <td><code>skipNullProperties</code></td>\n    <td><code>boolean</code></td>\n    <td> If set to true, validator will skip validation of all properties that are null or undefined in the validating object.</td>\n  </tr>\n  <tr>\n    <td><code>skipMissingProperties</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, validator will skip validation of all properties that are missing in the validating object.</td>\n  </tr>\n  <tr>\n    <td><code>whitelist</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, validator will strip validated (returned) object of any properties that do not use any validation decorators.</td>\n  </tr>\n  <tr>\n    <td><code>forbidNonWhitelisted</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, instead of stripping non-whitelisted properties validator will throw an exception.</td>\n  </tr>\n  <tr>\n    <td><code>forbidUnknownValues</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, attempts to validate unknown objects fail immediately.</td>\n  </tr>\n  <tr>\n    <td><code>disableErrorMessages</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, validation errors will not be returned to the client.</td>\n  </tr>\n  <tr>\n    <td><code>errorHttpStatusCode</code></td>\n    <td><code>number</code></td>\n    <td>This setting allows you to specify which exception type will be used in case of an error. By default it throws <code>BadRequestException</code>.</td>\n  </tr>\n  <tr>\n    <td><code>exceptionFactory</code></td>\n    <td><code>Function</code></td>\n    <td>Takes an array of the validation errors and returns an exception object to be thrown.</td>\n  </tr>\n  <tr>\n    <td><code>groups</code></td>\n    <td><code>string[]</code></td>\n    <td>Groups to be used during validation of the object.</td>\n  </tr>\n  <tr>\n    <td><code>always</code></td>\n    <td><code>boolean</code></td>\n    <td>Set default for <code>always</code> option of decorators. Default can be overridden in decorator options</td>\n  </tr>\n\n  <tr>\n    <td><code>strictGroups</code></td>\n    <td><code>boolean</code></td>\n    <td>If <code>groups</code> is not given or is empty, ignore decorators with at least one group.</td>\n  </tr>\n  <tr>\n    <td><code>dismissDefaultMessages</code></td>\n    <td><code>boolean</code></td>\n    <td>If set to true, the validation will not use default messages. Error message always will be <code>undefined</code>        if\n      its not explicitly set.</td>\n  </tr>\n  <tr>\n    <td><code>validationError.target</code></td>\n    <td><code>boolean</code></td>\n    <td>Indicates if target should be exposed in <code>ValidationError</code>.</td>\n  </tr>\n  <tr>\n    <td><code>validationError.value</code></td>\n    <td><code>boolean</code></td>\n    <td>Indicates if validated value should be exposed in <code>ValidationError</code>.</td>\n  </tr>\n  <tr>\n    <td><code>stopAtFirstError</code></td>\n    <td><code>boolean</code></td>\n    <td>When set to true, validation of the given property will stop after encountering the first error. Defaults to false.</td>\n  </tr>\n</table>\n\n> info **Notice** Find more information about the `class-validator` package in its [repository](https://github.com/typestack/class-validator).\n\n#### Auto-validation\n\nWe'll start by binding `ValidationPipe` at the application level, thus ensuring all endpoints are protected from receiving incorrect data.\n\n```typescript\nasync function bootstrap() {\n  const app = await NestFactory.create(AppModule);\n  app.useGlobalPipes(new ValidationPipe());\n  await app.listen(3000);\n}\nbootstrap();\n```\n\nTo test our pipe, let's create a basic endpoint.\n\n```typescript\n@Post()\ncreate(@Body() createUserDto: CreateUserDto) {\n  return 'This action adds a new user';\n}\n```\n\n> info **Hint** Since TypeScript does not store metadata about **generics or interfaces**, when you use them in your DTOs, `ValidationPipe` may not be able to properly validate incoming data.  For this reason, consider using concrete classes in your DTOs.\n\n> info **Hint** When importing your DTOs, you can't use a type-only import as that would be erased at runtime, i.e. remember to `import {{ '{' }} CreateUserDto {{ '}' }}` instead of `import type {{ '{' }} CreateUserDto {{ '}' }}`.\n\nNow we can add a few validation rules in our `CreateUserDto`. We do this using decorators provided by the `class-validator` package, described in detail [here](https://github.com/typestack/class-validator#validation-decorators). In this fashion, any route that uses the `CreateUserDto` will automatically enforce these validation rules.\n\n```typescript\nimport { IsEmail, IsNotEmpty } from 'class-validator';\n\nexport class CreateUserDto {\n  @IsEmail()\n  email: string;\n\n  @IsNotEmpty()\n  password: string;\n}\n```\n\nWith these rules in place, if a request hits our endpoint with an invalid `email` property in the request body, the application will automatically respond with a `400 Bad Request` code, along with the following response body:\n\n```json\n{\n  \"statusCode\": 400,\n  \"error\": \"Bad Request\",\n  \"message\": [\"email must be an email\"]\n}\n```\n\nIn addition to validating request bodies, the `ValidationPipe` can be used with other request object properties as well. Imagine that we would like to accept `:id` in the endpoint path. To ensure that only numbers are accepted for this request parameter, we can use the following construct:\n\n```typescript\n@Get(':id')\nfindOne(@Param() params: FindOneParams) {\n  return 'This action returns a user';\n}\n```\n\n`FindOneParams`, like a DTO, is simply a class that defines validation rules using `class-validator`. It would look like this:\n\n```typescript\nimport { IsNumberString } from 'class-validator';\n\nexport class FindOneParams {\n  @IsNumberString()\n  id: number;\n}\n```\n\n#### Disable detailed errors\n\nError messages can be helpful to explain what was incorrect in a request. However, some production environments prefer to disable detailed errors. Do this by passing an options object to the `ValidationPipe`:\n\n```typescript\napp.useGlobalPipes(\n  new ValidationPipe({\n    disableErrorMessages: true,\n  }),\n);\n```\n\nAs a result, detailed error messages won't be displayed in the response body.\n\n#### Stripping properties\n\nOur `ValidationPipe` can also filter out properties that should not be received by the method handler. In this case, we can **whitelist** the acceptable properties, and any property not included in the whitelist is automatically stripped from the resulting object. For example, if our handler expects `email` and `password` properties, but a request also includes an `age` property, this property can be automatically removed from the resulting DTO. To enable such behavior, set `whitelist` to `true`.\n\n```typescript\napp.useGlobalPipes(\n  new ValidationPipe({\n    whitelist: true,\n  }),\n);\n```\n\nWhen set to true, this will automatically remove non-whitelisted properties (those without any decorator in the validation class).\n\nAlternatively, you can stop the request from processing when non-whitelisted properties are present, and return an error response to the user. To enable this, set the `forbidNonWhitelisted` option property to `true`, in combination with setting `whitelist` to `true`.\n\n<app-banner-courses></app-banner-courses>\n\n#### Transform payload objects\n\nPayloads coming in over the network are plain JavaScript objects. The `ValidationPipe` can automatically transform payloads to be objects typed according to their DTO classes. To enable auto-transformation, set `transform` to `true`.  This can be done at a method level:\n\n```typescript\n@@filename(cats.controller)\n@Post()\n@UsePipes(new ValidationPipe({ transform: true }))\nasync create(@Body() createCatDto: CreateCatDto) {\n  this.catsService.create(createCatDto);\n}\n```\n\nTo enable this behavior globally, set the option on a global pipe:\n\n```typescript\napp.useGlobalPipes(\n  new ValidationPipe({\n    transform: true,\n  }),\n);\n```\n\nWith the auto-transformation option enabled, the `ValidationPipe` will also perform conversion of primitive types. In the following example, the `findOne()` method takes one argument which represents an extracted `id` path parameter:\n\n```typescript\n@Get(':id')\nfindOne(@Param('id') id: number) {\n  console.log(typeof id === 'number'); // true\n  return 'This action returns a user';\n}\n```\n\nBy default, every path parameter and query parameter comes over the network as a `string`. In the above example, we specified the `id` type as a `number` (in the method signature). Therefore, the `ValidationPipe` will try to automatically convert a string identifier to a number.\n\n#### Explicit conversion\n\nIn the above section, we showed how the `ValidationPipe` can implicitly transform query and path parameters based on the expected type. However, this feature requires having auto-transformation enabled.\n\nAlternatively (with auto-transformation disabled), you can explicitly cast values using the `ParseIntPipe` or `ParseBoolPipe` (note that `ParseStringPipe` is not needed because, as mentioned earlier, every path parameter and query parameter comes over the network as a `string` by default).\n\n```typescript\n@Get(':id')\nfindOne(\n  @Param('id', ParseIntPipe) id: number,\n  @Query('sort', ParseBoolPipe) sort: boolean,\n) {\n  console.log(typeof id === 'number'); // true\n  console.log(typeof sort === 'boolean'); // true\n  return 'This action returns a user';\n}\n```\n\n> info **Hint** The `ParseIntPipe` and `ParseBoolPipe` are exported from the `@nestjs/common` package.\n\n#### Mapped types\n\nAs you build out features like **CRUD** (Create/Read/Update/Delete) it's often useful to construct variants on a base entity type. Nest provides several utility functions that perform type transformations to make this task more convenient.\n\n> **Warning** If your application uses the `@nestjs/swagger` package, see [this chapter](/openapi/mapped-types) for more information about Mapped Types. Likewise, if you use the `@nestjs/graphql` package see [this chapter](/graphql/mapped-types). Both packages heavily rely on types and so they require a different import to be used. Therefore, if you used `@nestjs/mapped-types` (instead of an appropriate one, either `@nestjs/swagger` or `@nestjs/graphql` depending on the type of your app), you may face various, undocumented side-effects.\n\nWhen building input validation types (also called DTOs), it's often useful to build **create** and **update** variations on the same type. For example, the **create** variant may require all fields, while the **update** variant may make all fields optional.\n\nNest provides the `PartialType()` utility function to make this task easier and minimize boilerplate.\n\nThe `PartialType()` function returns a type (class) with all the properties of the input type set to optional. For example, suppose we have a **create** type as follows:\n\n```typescript\nexport class CreateCatDto {\n  name: string;\n  age: number;\n  breed: string;\n}\n```\n\nBy default, all of these fields are required. To create a type with the same fields, but with each one optional, use `PartialType()` passing the class reference (`CreateCatDto`) as an argument:\n\n```typescript\nexport class UpdateCatDto extends PartialType(CreateCatDto) {}\n```\n\n> info **Hint** The `PartialType()` function is imported from the `@nestjs/mapped-types` package.\n\nThe `PickType()` function constructs a new type (class) by picking a set of properties from an input type. For example, suppose we start with a type like:\n\n```typescript\nexport class CreateCatDto {\n  name: string;\n  age: number;\n  breed: string;\n}\n```\n\nWe can pick a set of properties from this class using the `PickType()` utility function:\n\n```typescript\nexport class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}\n```\n\n> info **Hint** The `PickType()` function is imported from the `@nestjs/mapped-types` package.\n\nThe `OmitType()` function constructs a type by picking all properties from an input type and then removing a particular set of keys. For example, suppose we start with a type like:\n\n```typescript\nexport class CreateCatDto {\n  name: string;\n  age: number;\n  breed: string;\n}\n```\n\nWe can generate a derived type that has every property **except** `name` as shown below. In this construct, the second argument to `OmitType` is an array of property names.\n\n```typescript\nexport class UpdateCatDto extends OmitType(CreateCatDto, ['name'] as const) {}\n```\n\n> info **Hint** The `OmitType()` function is imported from the `@nestjs/mapped-types` package.\n\nThe `IntersectionType()` function combines two types into one new type (class). For example, suppose we start with two types like:\n\n```typescript\nexport class CreateCatDto {\n  name: string;\n  breed: string;\n}\n\nexport class AdditionalCatInfo {\n  color: string;\n}\n```\n\nWe can generate a new type that combines all properties in both types.\n\n```typescript\nexport class UpdateCatDto extends IntersectionType(\n  CreateCatDto,\n  AdditionalCatInfo,\n) {}\n```\n\n> info **Hint** The `IntersectionType()` function is imported from the `@nestjs/mapped-types` package.\n\nThe type mapping utility functions are composable. For example, the following will produce a type (class) that has all of the properties of the `CreateCatDto` type except for `name`, and those properties will be set to optional:\n\n```typescript\nexport class UpdateCatDto extends PartialType(\n  OmitType(CreateCatDto, ['name'] as const),\n) {}\n```\n\n#### Parsing and validating arrays\n\nTypeScript does not store metadata about generics or interfaces, so when you use them in your DTOs, `ValidationPipe` may not be able to properly validate incoming data. For instance, in the following code, `createUserDtos` won't be correctly validated:\n\n```typescript\n@Post()\ncreateBulk(@Body() createUserDtos: CreateUserDto[]) {\n  return 'This action adds new users';\n}\n```\n\nTo validate the array, create a dedicated class which contains a property that wraps the array, or use the `ParseArrayPipe`.\n\n```typescript\n@Post()\ncreateBulk(\n  @Body(new ParseArrayPipe({ items: CreateUserDto }))\n  createUserDtos: CreateUserDto[],\n) {\n  return 'This action adds new users';\n}\n```\n\nIn addition, the `ParseArrayPipe` may come in handy when parsing query parameters. Let's consider a `findByIds()` method that returns users based on identifiers passed as query parameters.\n\n```typescript\n@Get()\nfindByIds(\n  @Query('ids', new ParseArrayPipe({ items: Number, separator: ',' }))\n  ids: number[],\n) {\n  return 'This action returns users by ids';\n}\n```\n\nThis construction validates the incoming query parameters from an HTTP `GET` request like the following:\n\n```bash\nGET /?ids=1,2,3\n```\n\n#### WebSockets and Microservices\n\nWhile this chapter shows examples using HTTP style applications (e.g., Express or Fastify), the `ValidationPipe` works the same for WebSockets and microservices, regardless of the transport method that is used.\n\n#### Learn more\n\nRead more about custom validators, error messages, and available decorators as provided by the `class-validator` package [here](https://github.com/typestack/class-validator).\n"
  },
  {
    "path": "content/techniques/versioning.md",
    "content": "### Versioning\n\n> info **Hint** This chapter is only relevant to HTTP-based applications.\n\nVersioning allows you to have **different versions** of your controllers or individual routes running within the same application. Applications change very often and it is not unusual that there are breaking changes that you need to make while still needing to support the previous version of the application.\n\nThere are 3 types of versioning that are supported:\n\n<table>\n  <tr>\n    <td><a href='techniques/versioning#uri-versioning-type'><code>URI Versioning</code></a></td>\n    <td>The version will be passed within the URI of the request (default)</td>\n  </tr>\n  <tr>\n    <td><a href='techniques/versioning#header-versioning-type'><code>Header Versioning</code></a></td>\n    <td>A custom request header will specify the version</td>\n  </tr>\n  <tr>\n    <td><a href='techniques/versioning#media-type-versioning-type'><code>Media Type Versioning</code></a></td>\n    <td>The <code>Accept</code> header of the request will specify the version</td>\n  </tr>\n</table>\n\n#### URI Versioning Type\n\nURI Versioning uses the version passed within the URI of the request, such as `https://example.com/v1/route` and `https://example.com/v2/route`.\n\n> warning **Notice** With URI Versioning the version will be automatically added to the URI after the <a href=\"faq/global-prefix\">global path prefix</a> (if one exists), and before any controller or route paths.\n\nTo enable URI Versioning for your application, do the following:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.create(AppModule);\n// or \"app.enableVersioning()\"\napp.enableVersioning({\n  type: VersioningType.URI,\n});\nawait app.listen(3000);\n```\n\n> warning **Notice** The version in the URI will be automatically prefixed with `v` by default, however the prefix value can be configured by setting the `prefix` key to your desired prefix or `false` if you wish to disable it.\n\n> info **Hint** The `VersioningType` enum is available to use for the `type` property and is imported from the `@nestjs/common` package.\n\n#### Header Versioning Type\n\nHeader Versioning uses a custom, user specified, request header to specify the version where the value of the header will be the version to use for the request.\n\nExample HTTP Requests for Header Versioning:\n\nTo enable **Header Versioning** for your application, do the following:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.create(AppModule);\napp.enableVersioning({\n  type: VersioningType.HEADER,\n  header: 'Custom-Header',\n});\nawait app.listen(3000);\n```\n\nThe `header` property should be the name of the header that will contain the version of the request.\n\n> info **Hint** The `VersioningType` enum is available to use for the `type` property and is imported from the `@nestjs/common` package.\n\n#### Media Type Versioning Type\n\nMedia Type Versioning uses the `Accept` header of the request to specify the version.\n\nWithin the `Accept` header, the version will be separated from the media type with a semi-colon, `;`. It should then contain a key-value pair that represents the version to use for the request, such as `Accept: application/json;v=2`. They key is treated more as a prefix when determining the version will to be configured to include the key and separator.\n\nTo enable **Media Type Versioning** for your application, do the following:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.create(AppModule);\napp.enableVersioning({\n  type: VersioningType.MEDIA_TYPE,\n  key: 'v=',\n});\nawait app.listen(3000);\n```\n\nThe `key` property should be the key and separator of the key-value pair that contains the version. For the example `Accept: application/json;v=2`, the `key` property would be set to `v=`.\n\n> info **Hint** The `VersioningType` enum is available to use for the `type` property and is imported from the `@nestjs/common` package.\n\n#### Usage\n\nVersioning allows you to version controllers, individual routes, and also provides a way for certain resources to opt-out of versioning. The usage of versioning is the same regardless of the Versioning Type your application uses.\n\n> warning **Notice** If versioning is enabled for the application but the controller or route does not specify the version, any requests to that controller/route will be returned a `404` response status. Similarly, if a request is received containing a version that does not have a corresponding controller or route, it will also be returned a `404` response status.\n\n#### Controller versions\n\nA version can be applied to a controller, setting the version for all routes within the controller.\n\nTo add a version to a controller do the following:\n\n```typescript\n@@filename(cats.controller)\n@Controller({\n  version: '1',\n})\nexport class CatsControllerV1 {\n  @Get('cats')\n  findAll(): string {\n    return 'This action returns all cats for version 1';\n  }\n}\n@@switch\n@Controller({\n  version: '1',\n})\nexport class CatsControllerV1 {\n  @Get('cats')\n  findAll() {\n    return 'This action returns all cats for version 1';\n  }\n}\n```\n\n#### Route versions\n\nA version can be applied to an individual route. This version will override any other version that would effect the route, such as the Controller Version.\n\nTo add a version to an individual route do the following:\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get, Version } from '@nestjs/common';\n\n@Controller()\nexport class CatsController {\n  @Version('1')\n  @Get('cats')\n  findAllV1(): string {\n    return 'This action returns all cats for version 1';\n  }\n\n  @Version('2')\n  @Get('cats')\n  findAllV2(): string {\n    return 'This action returns all cats for version 2';\n  }\n}\n@@switch\nimport { Controller, Get, Version } from '@nestjs/common';\n\n@Controller()\nexport class CatsController {\n  @Version('1')\n  @Get('cats')\n  findAllV1() {\n    return 'This action returns all cats for version 1';\n  }\n\n  @Version('2')\n  @Get('cats')\n  findAllV2() {\n    return 'This action returns all cats for version 2';\n  }\n}\n```\n\n#### Multiple versions\n\nMultiple versions can be applied to a controller or route. To use multiple versions, you would set the version to be an Array.\n\nTo add multiple versions do the following:\n\n```typescript\n@@filename(cats.controller)\n@Controller({\n  version: ['1', '2'],\n})\nexport class CatsController {\n  @Get('cats')\n  findAll(): string {\n    return 'This action returns all cats for version 1 or 2';\n  }\n}\n@@switch\n@Controller({\n  version: ['1', '2'],\n})\nexport class CatsController {\n  @Get('cats')\n  findAll() {\n    return 'This action returns all cats for version 1 or 2';\n  }\n}\n```\n\n#### Version \"Neutral\"\n\nSome controllers or routes may not care about the version and would have the same functionality regardless of the version. To accommodate this, the version can be set to `VERSION_NEUTRAL` symbol.\n\nAn incoming request will be mapped to a `VERSION_NEUTRAL` controller or route regardless of the version sent in the request in addition to if the request does not contain a version at all.\n\n> warning **Notice** For URI Versioning, a `VERSION_NEUTRAL` resource would not have the version present in the URI.\n\nTo add a version neutral controller or route do the following:\n\n```typescript\n@@filename(cats.controller)\nimport { Controller, Get, VERSION_NEUTRAL } from '@nestjs/common';\n\n@Controller({\n  version: VERSION_NEUTRAL,\n})\nexport class CatsController {\n  @Get('cats')\n  findAll(): string {\n    return 'This action returns all cats regardless of version';\n  }\n}\n@@switch\nimport { Controller, Get, VERSION_NEUTRAL } from '@nestjs/common';\n\n@Controller({\n  version: VERSION_NEUTRAL,\n})\nexport class CatsController {\n  @Get('cats')\n  findAll() {\n    return 'This action returns all cats regardless of version';\n  }\n}\n```\n\n#### Global default version\n\nIf you do not want to provide a version for each controller/or individual routes, or if you want to have a specific version set as the default version for every controller/route that don't have the version specified, you could set the `defaultVersion` as follows:\n\n```typescript\n@@filename(main)\napp.enableVersioning({\n  // ...\n  defaultVersion: '1'\n  // or\n  defaultVersion: ['1', '2']\n  // or\n  defaultVersion: VERSION_NEUTRAL\n});\n```\n"
  },
  {
    "path": "content/websockets/adapter.md",
    "content": "### Adapters\n\nThe WebSockets module is platform-agnostic, hence, you can bring your own library (or even a native implementation) by making use of `WebSocketAdapter` interface. This interface forces to implement few methods described in the following table:\n\n<table>\n  <tr>\n    <td><code>create</code></td>\n    <td>Creates a socket instance based on passed arguments</td>\n  </tr>\n  <tr>\n    <td><code>bindClientConnect</code></td>\n    <td>Binds the client connection event</td>\n  </tr>\n  <tr>\n    <td><code>bindClientDisconnect</code></td>\n    <td>Binds the client disconnection event (optional*)</td>\n  </tr>\n  <tr>\n    <td><code>bindMessageHandlers</code></td>\n    <td>Binds the incoming message to the corresponding message handler</td>\n  </tr>\n  <tr>\n    <td><code>close</code></td>\n    <td>Terminates a server instance</td>\n  </tr>\n</table>\n\n#### Extend socket.io\n\nThe [socket.io](https://github.com/socketio/socket.io) package is wrapped in an `IoAdapter` class. What if you would like to enhance the basic functionality of the adapter? For instance, your technical requirements require a capability to broadcast events across multiple load-balanced instances of your web service. For this, you can extend `IoAdapter` and override a single method which responsibility is to instantiate new socket.io servers. But first of all, let's install the required package.\n\n```bash\n$ npm i --save socket.io-redis\n```\n\nOnce the package is installed, we can create a `RedisIoAdapter` class.\n\n```typescript\nimport { IoAdapter } from '@nestjs/platform-socket.io';\nimport { RedisClient } from 'redis';\nimport { ServerOptions } from 'socket.io';\nimport { createAdapter } from 'socket.io-redis';\n\nconst pubClient = new RedisClient({ host: 'localhost', port: 6379 });\nconst subClient = pubClient.duplicate();\nconst redisAdapter = createAdapter({ pubClient, subClient });\n\nexport class RedisIoAdapter extends IoAdapter {\n  createIOServer(port: number, options?: ServerOptions): any {\n    const server = super.createIOServer(port, options);\n    server.adapter(redisAdapter);\n    return server;\n  }\n}\n```\n\nAfterward, simply switch to your newly created Redis adapter.\n\n```typescript\nconst app = await NestFactory.create(AppModule);\napp.useWebSocketAdapter(new RedisIoAdapter(app));\n```\n\n#### Ws library\n\nAnother available adapter is a `WsAdapter` which in turn acts like a proxy between the framework and integrate blazing fast and thoroughly tested [ws](https://github.com/websockets/ws) library. This adapter is fully compatible with native browser WebSockets and is far faster than socket.io package. Unluckily, it has significantly fewer functionalities available out-of-the-box. In some cases, you may just don't necessarily need them though.\n\n> info **Hint** `ws` library does not support namespaces (communication channels popularised by `socket.io`). However, to somehow mimic this feature, you can mount multiple `ws` servers on different paths (example: `@WebSocketGateway({{ '{' }} path: '/users' {{ '}' }})`).\n\nIn order to use `ws`, we firstly have to install the required package:\n\n```bash\n$ npm i --save @nestjs/platform-ws\n```\n\nOnce the package is installed, we can switch an adapter:\n\n```typescript\nconst app = await NestFactory.create(AppModule);\napp.useWebSocketAdapter(new WsAdapter(app));\n```\n\n> info **Hint** The `WsAdapter` is imported from `@nestjs/platform-ws`.\n\n#### Advanced (custom adapter)\n\nFor demonstration purposes, we are going to integrate the [ws](https://github.com/websockets/ws) library manually. As mentioned, the adapter for this library is already created and is exposed from the `@nestjs/platform-ws` package as a `WsAdapter` class. Here is how the simplified implementation could potentially look like:\n\n```typescript\n@@filename(ws-adapter)\nimport * as WebSocket from 'ws';\nimport { WebSocketAdapter, INestApplicationContext } from '@nestjs/common';\nimport { MessageMappingProperties } from '@nestjs/websockets';\nimport { Observable, fromEvent, EMPTY } from 'rxjs';\nimport { mergeMap, filter } from 'rxjs/operators';\n\nexport class WsAdapter implements WebSocketAdapter {\n  constructor(private app: INestApplicationContext) {}\n\n  create(port: number, options: any = {}): any {\n    return new WebSocket.Server({ port, ...options });\n  }\n\n  bindClientConnect(server, callback: Function) {\n    server.on('connection', callback);\n  }\n\n  bindMessageHandlers(\n    client: WebSocket,\n    handlers: MessageMappingProperties[],\n    process: (data: any) => Observable<any>,\n  ) {\n    fromEvent(client, 'message')\n      .pipe(\n        mergeMap(data => this.bindMessageHandler(data, handlers, process)),\n        filter(result => result),\n      )\n      .subscribe(response => client.send(JSON.stringify(response)));\n  }\n\n  bindMessageHandler(\n    buffer,\n    handlers: MessageMappingProperties[],\n    process: (data: any) => Observable<any>,\n  ): Observable<any> {\n    const message = JSON.parse(buffer.data);\n    const messageHandler = handlers.find(\n      handler => handler.message === message.event,\n    );\n    if (!messageHandler) {\n      return EMPTY;\n    }\n    return process(messageHandler.callback(message.data));\n  }\n\n  close(server) {\n    server.close();\n  }\n}\n```\n\n> info **Hint** When you want to take advantage of [ws](https://github.com/websockets/ws) library, use built-in `WsAdapter` instead of creating your own one.\n\nThen, we can set up a custom adapter using `useWebSocketAdapter()` method:\n\n```typescript\n@@filename(main)\nconst app = await NestFactory.create(AppModule);\napp.useWebSocketAdapter(new WsAdapter(app));\n```\n\n#### Example\n\nA working example that uses `WsAdapter` is available [here](https://github.com/nestjs/nest/tree/master/sample/16-gateways-ws).\n"
  },
  {
    "path": "content/websockets/exception-filters.md",
    "content": "### Exception filters\n\nThe only difference between the HTTP [exception filter](/exception-filters) layer and the corresponding web sockets layer is that instead of throwing `HttpException`, you should use `WsException`.\n\n```typescript\nthrow new WsException('Invalid credentials.');\n```\n\n> info **Hint** The `WsException` class is imported from the `@nestjs/websockets` package.\n\nWith the sample above, Nest will handle the thrown exception and emit the `exception` message with the following structure:\n\n```typescript\n{\n  status: 'error',\n  message: 'Invalid credentials.'\n}\n```\n\n#### Filters\n\nWeb sockets exception filters behave equivalently to HTTP exception filters. The following example uses a manually instantiated method-scoped filter. Just as with HTTP based applications, you can also use gateway-scoped filters (i.e., prefix the gateway class with a `@UseFilters()` decorator).\n\n```typescript\n@UseFilters(new WsExceptionFilter())\n@SubscribeMessage('events')\nonEvent(client, data: any): WsResponse<any> {\n  const event = 'events';\n  return { event, data };\n}\n```\n\n#### Inheritance\n\nTypically, you'll create fully customized exception filters crafted to fulfill your application requirements. However, there might be use-cases when you would like to simply extend the **core exception filter**, and override the behavior based on certain factors.\n\nIn order to delegate exception processing to the base filter, you need to extend `BaseWsExceptionFilter` and call the inherited `catch()` method.\n\n```typescript\n@@filename()\nimport { Catch, ArgumentsHost } from '@nestjs/common';\nimport { BaseWsExceptionFilter } from '@nestjs/websockets';\n\n@Catch()\nexport class AllExceptionsFilter extends BaseWsExceptionFilter {\n  catch(exception: unknown, host: ArgumentsHost) {\n    super.catch(exception, host);\n  }\n}\n@@switch\nimport { Catch } from '@nestjs/common';\nimport { BaseWsExceptionFilter } from '@nestjs/websockets';\n\n@Catch()\nexport class AllExceptionsFilter extends BaseWsExceptionFilter {\n  catch(exception, host) {\n    super.catch(exception, host);\n  }\n}\n```\n\nThe above implementation is just a shell demonstrating the approach. Your implementation of the extended exception filter would include your tailored **business logic** (e.g., handling various conditions).\n"
  },
  {
    "path": "content/websockets/gateways.md",
    "content": "### Gateways\n\nMost of the concepts discussed elsewhere in this documentation, such as dependency injection, decorators, exception filters, pipes, guards and interceptors, apply equally to gateways. Wherever possible, Nest abstracts implementation details so that the same components can run across HTTP-based platforms, WebSockets, and Microservices. This section covers the aspects of Nest that are specific to WebSockets.\n\nIn Nest, a gateway is simply a class annotated with `@WebSocketGateway()` decorator. Technically, gateways are platform-agnostic which makes them compatible with any WebSockets library once an adapter is created. There are two WS platforms supported out-of-the-box: [socket.io](https://github.com/socketio/socket.io) and [ws](https://github.com/websockets/ws). You can choose the one that best suits your needs. Also, you can build your own adapter by following this [guide](/websockets/adapter).\n\n<figure><img src=\"/assets/Gateways_1.png\" /></figure>\n\n> info **Hint** Gateways can be treated as [providers](/providers); this means they can inject dependencies through the class constructor. Also, gateways can be injected by other classes (providers and controllers) as well.\n\n#### Installation\n\nTo start building WebSockets-based applications, first install the required package:\n\n```bash\n@@filename()\n$ npm i --save @nestjs/websockets @nestjs/platform-socket.io\n@@switch\n$ npm i --save @nestjs/websockets @nestjs/platform-socket.io\n```\n\n#### Overview\n\nIn general, each gateway is listening on the same port as the **HTTP server**, unless your app is not a web application, or you have changed the port manually. This default behavior can be modified by passing an argument to the `@WebSocketGateway(80)` decorator where `80` is a chosen port number. You can also set a [namespace](https://socket.io/docs/v4/namespaces/) used by the gateway using the following construction:\n\n```typescript\n@WebSocketGateway(80, { namespace: 'events' })\n```\n\n> warning **Warning** Gateways are not instantiated until they are referenced in the providers array of an existing module.\n\nYou can pass any supported [option](https://socket.io/docs/v4/server-options/) to the socket constructor with the second argument to the `@WebSocketGateway()` decorator, as shown below:\n\n```typescript\n@WebSocketGateway(81, { transports: ['websocket'] })\n```\n\nThe gateway is now listening, but we have not yet subscribed to any incoming messages. Let's create a handler that will subscribe to the `events` messages and respond to the user with the exact same data.\n\n```typescript\n@@filename(events.gateway)\n@SubscribeMessage('events')\nhandleEvent(@MessageBody() data: string): string {\n  return data;\n}\n@@switch\n@Bind(MessageBody())\n@SubscribeMessage('events')\nhandleEvent(data) {\n  return data;\n}\n```\n\n> info **Hint** `@SubscribeMessage()` and `@MessageBody()` decorators are imported from `@nestjs/websockets` package.\n\nOnce the gateway is created, we can register it in our module.\n\n```typescript\nimport { Module } from '@nestjs/common';\nimport { EventsGateway } from './events.gateway';\n\n@@filename(events.module)\n@Module({\n  providers: [EventsGateway]\n})\nexport class EventsModule {}\n```\n\nYou can also pass in a property key to the decorator to extract it from the incoming message body:\n\n```typescript\n@@filename(events.gateway)\n@SubscribeMessage('events')\nhandleEvent(@MessageBody('id') id: number): number {\n  // id === messageBody.id\n  return id;\n}\n@@switch\n@Bind(MessageBody('id'))\n@SubscribeMessage('events')\nhandleEvent(id) {\n  // id === messageBody.id\n  return id;\n}\n```\n\nIf you would prefer not to use decorators, the following code is functionally equivalent:\n\n```typescript\n@@filename(events.gateway)\n@SubscribeMessage('events')\nhandleEvent(client: Socket, data: string): string {\n  return data;\n}\n@@switch\n@SubscribeMessage('events')\nhandleEvent(client, data) {\n  return data;\n}\n```\n\nIn the example above, the `handleEvent()` function takes two arguments. The first one is a platform-specific [socket instance](https://socket.io/docs/v4/server-api/#socket), while the second one is the data received from the client. This approach is not recommended though, because it requires mocking the `socket` instance in each unit test.\n\nOnce the `events` message is received, the handler sends an acknowledgment with the same data that was sent over the network. In addition, it's possible to emit messages using a library-specific approach, for example, by making use of `client.emit()` method. In order to access a connected socket instance, use `@ConnectedSocket()` decorator.\n\n```typescript\n@@filename(events.gateway)\n@SubscribeMessage('events')\nhandleEvent(\n  @MessageBody() data: string,\n  @ConnectedSocket() client: Socket,\n): string {\n  return data;\n}\n@@switch\n@Bind(MessageBody(), ConnectedSocket())\n@SubscribeMessage('events')\nhandleEvent(data, client) {\n  return data;\n}\n```\n\n> info **Hint** `@ConnectedSocket()` decorator is imported from `@nestjs/websockets` package.\n\nHowever, in this case, you won't be able to leverage interceptors. If you don't want to respond to the user, you can simple skip the `return` statement (or explicitly return \"falsy\" value, e.g. `undefined`).\n\nNow when a client emits the message as follows:\n\n```typescript\nsocket.emit('events', { name: 'Nest' });\n```\n\nThe `handleEvent()` method will be executed. In order to listen for messages emitted from within the above handler, the client has to attach a corresponding acknowledgment listener:\n\n```typescript\nsocket.emit('events', { name: 'Nest' }, (data) => console.log(data));\n```\n\n#### Multiple responses\n\nThe acknowledgment is dispatched only once. Furthermore, it is not supported by native WebSockets implementation. To solve this limitation, you may return an object which consist of two properties. The `event` which is a name of the emitted event and the `data` that has to be forwarded to the client.\n\n```typescript\n@@filename(events.gateway)\n@SubscribeMessage('events')\nhandleEvent(@MessageBody() data: unknown): WsResponse<unknown> {\n  const event = 'events';\n  return { event, data };\n}\n@@switch\n@Bind(MessageBody())\n@SubscribeMessage('events')\nhandleEvent(data) {\n  const event = 'events';\n  return { event, data };\n}\n```\n\n> info **Hint** The `WsResponse` interface is imported from `@nestjs/websockets` package.\n\n> warning **Warning** You should return a class instance that implements `WsResponse` if your `data` field relies on `ClassSerializerInterceptor`, as it ignores plain JavaScript objects responses.\n\nIn order to listen for the incoming response(s), the client has to apply another event listener.\n\n```typescript\nsocket.on('events', (data) => console.log(data));\n```\n\n#### Asynchronous responses\n\nMessage handlers are able to respond either synchronously or **asynchronously**. Hence, `async` methods are supported. A message handler is also able to return an `Observable`, in which case the result values will be emitted until the stream is completed.\n\n```typescript\n@@filename(events.gateway)\n@SubscribeMessage('events')\nonEvent(@MessageBody() data: unknown): Observable<WsResponse<number>> {\n  const event = 'events';\n  const response = [1, 2, 3];\n\n  return from(response).pipe(\n    map(data => ({ event, data })),\n  );\n}\n@@switch\n@Bind(MessageBody())\n@SubscribeMessage('events')\nonEvent(data) {\n  const event = 'events';\n  const response = [1, 2, 3];\n\n  return from(response).pipe(\n    map(data => ({ event, data })),\n  );\n}\n```\n\nIn the example above, the message handler will respond **3 times** (with each item from the array).\n\n#### Lifecycle hooks\n\nThere are 3 useful lifecycle hooks available. All of them have corresponding interfaces and are described in the following table:\n\n<table>\n  <tr>\n    <td>\n      <code>OnGatewayInit</code>\n    </td>\n    <td>\n      Forces to implement the <code>afterInit()</code> method. Takes library-specific server instance as an argument (and\n      spreads the rest if required).\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>OnGatewayConnection</code>\n    </td>\n    <td>\n      Forces to implement the <code>handleConnection()</code> method. Takes library-specific client socket instance as\n      an argument.\n    </td>\n  </tr>\n  <tr>\n    <td>\n      <code>OnGatewayDisconnect</code>\n    </td>\n    <td>\n      Forces to implement the <code>handleDisconnect()</code> method. Takes library-specific client socket instance as\n      an argument.\n    </td>\n  </tr>\n</table>\n\n> info **Hint** Each lifecycle interface is exposed from `@nestjs/websockets` package.\n\n#### Server\n\nOccasionally, you may want to have a direct access to the native, **platform-specific** server instance. The reference to this object is passed as an argument to the `afterInit()` method (`OnGatewayInit` interface). Another option is to use the `@WebSocketServer()` decorator.\n\n```typescript\n@WebSocketServer()\nserver: Server;\n```\n\n> warning **Notice** The `@WebSocketServer()` decorator is imported from the `@nestjs/websockets` package.\n\nNest will automatically assign the server instance to this property once it is ready to use.\n\n<app-banner-enterprise></app-banner-enterprise>\n\n#### Example\n\nA working example is available [here](https://github.com/nestjs/nest/tree/master/sample/02-gateways).\n"
  },
  {
    "path": "content/websockets/guards.md",
    "content": "### Guards\n\nThere is no fundamental difference between web sockets guards and [regular HTTP application guards](/guards). The only difference is that instead of throwing `HttpException`, you should use `WsException`.\n\n> info **Hint** The `WsException` class is exposed from `@nestjs/websockets` package.\n\n#### Binding guards\n\nThe following example uses a method-scoped guard. Just as with HTTP based applications, you can also use gateway-scoped guards (i.e., prefix the gateway class with a `@UseGuards()` decorator).\n\n```typescript\n@@filename()\n@UseGuards(AuthGuard)\n@SubscribeMessage('events')\nhandleEvent(client: Client, data: unknown): WsResponse<unknown> {\n  const event = 'events';\n  return { event, data };\n}\n@@switch\n@UseGuards(AuthGuard)\n@SubscribeMessage('events')\nhandleEvent(client, data) {\n  const event = 'events';\n  return { event, data };\n}\n```\n"
  },
  {
    "path": "content/websockets/interceptors.md",
    "content": "### Interceptors\n\nThere is no difference between [regular interceptors](/interceptors) and web sockets interceptors. The following example uses a manually instantiated method-scoped interceptor. Just as with HTTP based applications, you can also use gateway-scoped interceptors (i.e., prefix the gateway class with a `@UseInterceptors()` decorator).\n\n```typescript\n@@filename()\n@UseInterceptors(new TransformInterceptor())\n@SubscribeMessage('events')\nhandleEvent(client: Client, data: unknown): WsResponse<unknown> {\n  const event = 'events';\n  return { event, data };\n}\n@@switch\n@UseInterceptors(new TransformInterceptor())\n@SubscribeMessage('events')\nhandleEvent(client, data) {\n  const event = 'events';\n  return { event, data };\n}\n```\n"
  },
  {
    "path": "content/websockets/pipes.md",
    "content": "### Pipes\n\nThere is no fundamental difference between [regular pipes](/pipes) and web sockets pipes. The only difference is that instead of throwing `HttpException`, you should use `WsException`. In addition, all pipes will be only applied to the `data` parameter (because validating or transforming `client` instance is useless).\n\n> info **Hint** The `WsException` class is exposed from `@nestjs/websockets` package.\n\n#### Binding pipes\n\nThe following example uses a manually instantiated method-scoped pipe. Just as with HTTP based applications, you can also use gateway-scoped pipes (i.e., prefix the gateway class with a `@UsePipes()` decorator).\n\n```typescript\n@@filename()\n@UsePipes(new ValidationPipe())\n@SubscribeMessage('events')\nhandleEvent(client: Client, data: unknown): WsResponse<unknown> {\n  const event = 'events';\n  return { event, data };\n}\n@@switch\n@UsePipes(new ValidationPipe())\n@SubscribeMessage('events')\nhandleEvent(client, data) {\n  const event = 'events';\n  return { event, data };\n}\n```\n"
  }
]