笔记
约 3554 字大约 12 分钟
2025-11-09
请求的流转过程
[请求 Request] --> [DTO 数据传输对象] --> [Controller 控制器(Handler)] --> [Service 服务层] --> [Repository / 数据层]在 Nest 应用中,一个典型的请求会按照如下步骤进行:
客户端发送请求 请求会被路由匹配到对应的控制器(Controller)方法。
DTO(Data Transfer Object)接收参数 控制器方法在接收参数时,会使用定义好的 DTO 类 来描述和验证请求体结构。 DTO 通常配合
class-validator与class-transformer实现参数校验与类型转换。Controller(控制器)处理请求 控制器中的每个方法称为 handler(处理器)。 它负责:
- 解析请求参数(通过装饰器如
@Body(),@Param(),@Query()等) - 调用对应的业务逻辑(Service)
- 返回响应结果
可以理解为 Controller 是路由与业务逻辑之间的中间层。
- 解析请求参数(通过装饰器如
依赖注入(IoC 容器)
Nest 采用 IoC(控制反转) 与 依赖注入(DI) 模式来管理模块和类之间的依赖关系。
框架会自动从 IoC 容器 中查找依赖实例并注入到需要的地方。
注入方式有两种:
构造器注入(推荐)
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
}依赖通过构造函数参数注入。
注入时机在实例化类时完成。
优点:清晰、类型安全、方便测试。
属性注入
@Controller('users')
export class UserController {
@Inject(UserService)
private readonly userService: UserService;
}通过 @Inject() 装饰器显式注入依赖。
一般在特殊场景下使用(如循环依赖)。
两种方式的效果一致,但构造器注入是官方推荐的写法。
模块化结构(Module)
每个 Nest 模块通常包含以下部分:
| 组成部分 | 作用 |
|---|---|
| Controller | 负责接收请求、解析参数、返回响应 |
| Service | 负责业务逻辑处理(如数据库操作、第三方接口调用) |
| DTO | 定义请求/响应的数据结构与类型验证 |
| Entities | 定义数据库表对应的实体类 |
| Module | 将相关的 controller、service、entity 等组织在一起,形成可复用模块 |
模块文件示例:
@Module({
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}应用启动流程
Nest 应用启动后会经历以下过程:
- 从
AppModule开始作为根模块; - 初始化 IoC 容器;
- 加载所有模块(包括其 controller、service 等);
- 注册所有路由;
- 启动 HTTP 服务器,开始监听请求。
bootstrap() --> 初始化 IoC 容器 --> 注册模块与控制器 --> 启动服务MVC 模式在 Nest 中的体现
Nest 框架的整体思想与经典的 MVC(Model-View-Controller) 架构一致:
| 层级 | 在 Nest 中的对应 | 主要职责 |
|---|---|---|
| Model(模型层) | Entity + Repository + Service | 处理业务逻辑和数据存取 |
| View(视图层) | 通常是 JSON 响应(也可使用模板引擎) | 展示结果 |
| Controller(控制层) | Controller | 接收请求、调用 Service、返回响应 |
Client --> Controller(接收参数) --> Service(业务逻辑) --> Repository(数据库操作)
--> Service(返回结果) --> Controller(响应客户端)CLI 配置文件
完整的配置文件
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://json.schemastore.org/nest-cli.json",
"$comment": "https://docs.nestjs.com/cli/monorepo#cli-properties",
"definitions": {
"CompilerOptions": {
"$comment": "https://docs.nestjs.com/cli/monorepo#global-compiler-options",
"type": "object",
"description": "A map with keys specifying compiler options and values specifying the option setting. See https://docs.nestjs.com/cli/monorepo#global-compiler-options for details",
"default": {},
"properties": {
"tsConfigPath": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/lib/compiler/defaults/webpac-defaults.ts",
"default": "tsconfig.build.json",
"type": "string",
"description": "(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). 'nest build' will not work as expected without this file."
},
"builder": {
"anyOf": [
{
"$comment": "https://github.com/nestjs/nest-cli/blob/master/commands/build.command.ts",
"default": "tsc",
"type": "string",
"enum": ["tsc", "webpack", "swc"],
"description": "Builder to be used (tsc, webpack, swc). For details on how to configure `SWC` see https://docs.nestjs.com/recipes/swc#getting-started"
},
{
"type": "object",
"properties": {
"type": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/commands/build.command.ts",
"default": "tsc",
"type": "string",
"enum": ["tsc", "webpack", "swc"],
"description": "Builder to be used (tsc, webpack, swc). For details on how to configure `SWC` see https://docs.nestjs.com/recipes/swc#getting-started"
},
"options": {
"type": "object",
"properties": {
"outDir": {
"type": "string",
"description": "The directory to output files."
},
"filenames": {
"type": "array",
"items": {
"type": "string"
},
"description": "Array of filenames to be included."
},
"sync": {
"type": "boolean",
"description": "Whether to synchronize files or not."
},
"extensions": {
"type": "array",
"items": {
"type": "string"
},
"description": "Array of file extensions to be considered."
},
"copyFiles": {
"type": "boolean",
"description": "Whether to copy files or not."
},
"includeDotfiles": {
"type": "boolean",
"description": "Whether to include dotfiles or not."
},
"quiet": {
"type": "boolean",
"description": "Whether to suppress logs or not."
},
"watch": {
"type": "boolean",
"description": "Whether to watch files for changes or not."
},
"swcrcPath": {
"type": "string",
"description": "Path to SWC config file to use."
}
}
}
}
}
]
},
"typeCheck": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/commands/build.command.ts",
"default": false,
"type": "boolean",
"description": "If true, enable type checking (when SWC is used). See https://docs.nestjs.com/recipes/swc#type-checking for details."
},
"webpack": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/commands/build.command.ts",
"default": false,
"type": "boolean",
"description": "If true, use webpack compiler (deprecated option, use `builder` instead). 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 https://docs.nestjs.com/cli/monorepo#cli-properties for details."
},
"webpackConfigPath": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/commands/build.command.ts",
"default": "webpack.config.js",
"type": "string",
"description": "Points at a webpack options file. If not specified, Nest looks for the file webpack.config.js."
},
"plugins": {
"$comment": "https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/PluginItems"
}
},
"assets": {
"$comment": "https://docs.nestjs.com/cli/monorepo#assets",
"default": [],
"type": "array",
"items": {
"$ref": "#/definitions/AssetsOptions"
},
"description": "Enables automatically distributing non-TypeScript assets whenever a compilation step begins (asset distribution does not happen on incremental compiles in --watch mode). Accept glob-like string and object. See https://docs.nestjs.com/cli/monorepo#assets for details."
},
"watchAssets": {
"default": false,
"type": "boolean",
"description": "If true, run in watch-mode, watching all non-TypeScript assets. Setting watchAssets in a top-level compilerOptions property overrides any watchAssets settings within the assets property."
},
"deleteOutDir": {
"type": "boolean",
"default": false,
"description": "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)."
},
"manualRestart": {
"type": "boolean",
"default": false,
"description": "If true, enables the shortcut `rs` to manually restart the server."
}
},
"additionalProperties": false
},
"AssetsOptions": {
"$comment": "https://docs.nestjs.com/cli/monorepo#assets",
"type": ["string", "object"],
"description": "For finer control, the element can be object.",
"properties": {
"include": {
"type": "string",
"description": "Glob-like file specifications for the assets to be distributed."
},
"exclude": {
"type": "string",
"description": "Glob-like file specifications for the assets to be excluded from the include list."
},
"outDir": {
"type": "string",
"description": "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."
},
"watchAssets": {
"type": "boolean",
"description": "If true, run in watch mode watching specified assets. Setting watchAssets in a top-level compilerOptions property overrides any watchAssets settings within the assets property."
}
},
"additionalProperties": false
},
"GenerateOptions": {
"$comment": "https://docs.nestjs.com/cli/monorepo#global-generate-options",
"type": "object",
"description": "A map with keys specifying global generate options and values specifying the option setting. See https://docs.nestjs.com/cli/monorepo#global-generate-options for details",
"properties": {
"spec": {
"$ref": "#/definitions/GenerateSpecOptions"
},
"flat": {
"$ref": "#/definitions/GenerateFlatOptions"
},
"baseDir": {
"$ref": "#/definitions/GenerateBaseDirOptions"
}
},
"default": {},
"additionalProperties": false
},
"GenerateFlatOptions": {
"$comment": "https://docs.nestjs.com/cli/monorepo#global-generate-options",
"type": "boolean",
"default": false,
"description": "If true, all generate commands will generate a flat structure"
},
"GenerateSpecOptions": {
"$comment": "https://docs.nestjs.com/cli/monorepo#global-generate-options",
"type": ["boolean", "object"],
"description": "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. See https://docs.nestjs.com/cli/monorepo#global-generate-options for details.",
"properties": {
"application": {
"type": "boolean",
"description": "Generate spec file for application schematics or not."
},
"class": {
"type": "boolean",
"description": "Disable spec file generation for class schematics."
},
"cl": {
"type": "boolean",
"description": "Alias for class"
},
"configuration": {
"type": "boolean",
"description": "Generate spec file for configuration schematics or not."
},
"config": {
"type": "boolean",
"description": "Alias for configuration"
},
"controller": {
"type": "boolean",
"description": "Generate spec file for controller schematics or not."
},
"co": {
"type": "boolean",
"description": "Alias for controller"
},
"decorator": {
"type": "boolean",
"description": "Generate spec file for decorator schematics or not."
},
"d": {
"type": "boolean",
"description": "Alias for decorator"
},
"filter": {
"type": "boolean",
"description": "Generate spec file for filter schematics or not."
},
"f": {
"type": "boolean",
"description": "Alias for filter"
},
"gateway": {
"type": "boolean",
"description": "Generate spec file for gateway schematics or not."
},
"ga": {
"type": "boolean",
"description": "Alias for gateway"
},
"guard": {
"type": "boolean",
"description": "Generate spec file for guard schematics or not."
},
"gu": {
"type": "boolean",
"description": "Alias for guard"
},
"interceptor": {
"type": "boolean",
"description": "Generate spec file for interceptor schematics or not."
},
"in": {
"type": "boolean",
"description": "Alias for interceptor"
},
"interface": {
"type": "boolean",
"description": "Generate spec file for interface schematics or not."
},
"middleware": {
"type": "boolean",
"description": "Generate spec file for middleware schematics or not."
},
"mi": {
"type": "boolean",
"description": "Alias for middleware"
},
"module": {
"type": "boolean",
"description": "Generate spec file for module schematics or not."
},
"mo": {
"type": "boolean",
"description": "Alias for module"
},
"pipe": {
"type": "boolean",
"description": "Generate spec file for pipe schematics or not."
},
"pi": {
"type": "boolean",
"description": "Alias for pipe"
},
"provider": {
"type": "boolean",
"description": "Generate spec file for provider schematics or not."
},
"pr": {
"type": "boolean",
"description": "Alias for provider"
},
"resolver": {
"type": "boolean",
"description": "Generate spec file for resolver schematics or not."
},
"r": {
"type": "boolean",
"description": "Alias for resolver"
},
"service": {
"type": "boolean",
"description": "Generate spec file for service schematics or not."
},
"s": {
"type": "boolean",
"description": "Alias for resolver"
},
"library": {
"type": "boolean",
"description": "Generate spec file for library schematics or not."
},
"lib": {
"type": "boolean",
"description": "Alias for library"
},
"sub-app": {
"type": "boolean",
"description": "Generate spec file for sub-app schematics or not."
},
"app": {
"type": "boolean",
"description": "Alias for sub-app"
},
"resource": {
"type": "boolean",
"description": "Generate spec file for resource schematics or not."
},
"res": {
"type": "boolean",
"description": "Alias for resource"
}
},
"additionalProperties": false
},
"GenerateBaseDirOptions": {
"type": "string",
"default": "",
"description": "Base directory"
},
"ProjectConfiguration": {
"type": "object",
"properties": {
"type": {
"type": "string"
},
"root": {
"type": "string"
},
"entryFile": {
"type": "string"
},
"sourceRoot": {
"type": "string"
},
"compilerOptions": {
"$ref": "#/definitions/CompilerOptions"
},
"generateOptions": {
"$ref": "#/definitions/GenerateOptions"
}
},
"additionalProperties": false
},
"PluginItems": {
"$comment": "https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin",
"type": ["string", "object"],
"properties": {
"name": {
"type": "string",
"description": "The npm package name of the cli plugin, eg @nestjs/swagger."
},
"options": {
"anyOf": [
{
"$ref": "#/definitions/PluginOptions"
},
{
"$ref": "#/definitions/GraphQLPluginOptions"
},
{
"$ref": "#/definitions/SwaggerPluginOptions"
}
]
}
}
},
"PluginOptions": {
"type": "object",
"properties": {
"introspectComments": {
"type": "boolean",
"default": true,
"description": "If set to true, plugin will generate descriptions and example values for properties based on comments."
}
}
},
"GraphQLPluginOptions": {
"$comment": "https://docs.nestjs.com/graphql/cli-plugin#using-the-cli-plugin",
"type": "object",
"properties": {
"typeFileNameSuffix": {
"type": "array",
"default": [".input.ts", ".args.ts", ".entity.ts", ".model.ts"],
"description": "(GraphQL Only) GraphQL types files suffix. Default value: ['.input.ts', '.args.ts', '.entity.ts', '.model.ts']. See https://docs.nestjs.com/graphql/cli-plugin#using-the-cli-plugin for details."
}
}
},
"SwaggerPluginOptions": {
"$comment": "https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin",
"type": "object",
"properties": {
"dtoFileNameSuffix": {
"type": "array",
"items": {
"type": "string"
},
"default": [".dto.ts", ".entity.ts"],
"description": "(Swagger Only) DTO (Data Transfer Object) files suffix. Default value: ['.dto.ts', '.entity.ts']. See https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin for details"
},
"controllerFileNameSuffix": {
"type": "string",
"default": ".controller.ts",
"description": "(Swagger Only) Controller files suffix. See https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin for details"
},
"classValidatorShim": {
"type": "boolean",
"default": true,
"description": "(Swagger Only) If set to true, the module will reuse class-validator validation decorators (e.g. @Max(10) will add max: 10 to schema definition). See https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin for details"
},
"dtoKeyOfComment": {
"type": "string",
"default": "description",
"description": "(Swagger Only) The property key to set the comment text to on ApiProperty. See https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin for details"
},
"controllerKeyOfComment": {
"type": "string",
"default": "description",
"description": "(Swagger Only) The property key to set the comment text to on ApiOperation. See https://docs.nestjs.com/openapi/cli-plugin#using-the-cli-plugin for details"
}
}
}
},
"properties": {
"language": {
"type": "string",
"default": "ts"
},
"collection": {
"type": "string",
"default": "@nestjs/schematics",
"description": "Points at the collection of schematics used to generate components. you generally should not change this value."
},
"sourceRoot": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/actions/add.action.ts",
"type": "string",
"default": "src",
"description": "Points at the root of the source code for the single project in standard mode structures, or the default project in monorepo mode structures."
},
"entryFile": {
"$comment": "https://github.com/nestjs/nest-cli/blob/master/actions/start.action.ts",
"type": "string",
"default": "main",
"description": "The entry file where 'nest start' work with. Default to 'main'."
},
"monorepo": {
"type": "boolean",
"description": "(monorepo only) For a monorepo mode structure, this value is always true.",
"default": false
},
"root": {
"type": "string",
"description": "(monorepo only) Points at the project root of the default project.",
"default": ""
},
"compilerOptions": {
"$ref": "#/definitions/CompilerOptions"
},
"generateOptions": {
"$ref": "#/definitions/GenerateOptions"
},
"projects": {
"type": "object",
"additionalProperties": {
"$ref": "#/definitions/ProjectConfiguration"
},
"default": {}
},
"defaultLibraryPrefix": {
"type": "string",
"description": "Default import prefix for newly generated libraries.",
"default": "@app"
}
},
"title": "Nest CLI configuration",
"type": "object"
}中文版
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://json.schemastore.org/nest-cli.json",
"$comment": "https://docs.nestjs.com/cli/monorepo#cli-properties(备注:NestJS CLI monorepo 模式下属性说明)",
"definitions": {
"CompilerOptions": {
"$comment": "https://docs.nestjs.com/cli/monorepo#global-compiler-options(全局编译选项)",
"type": "object",
"description": "一个映射对象,其键指定编译器选项,值指定该选项的设置。详细说明见 NestJS 文档。",
"default": {},
"properties": {
"tsConfigPath": {
"$comment": "tsconfig.json 文件路径(monorepo 专用)",
"default": "tsconfig.build.json",
"type": "string",
"description": "指向包含 tsconfig.json 设置的文件,当 nest build 或 nest start 在未指定 project 选项时将使用该文件。"
},
"builder": {
"anyOf": [
{
"$comment": "构建器类型(字符串形式)",
"default": "tsc",
"type": "string",
"enum": ["tsc", "webpack", "swc"],
"description": "要使用的构建器类型(tsc、webpack、swc)。有关 SWC 配置,请参考官方文档。"
},
{
"type": "object",
"properties": {
"type": {
"$comment": "构建器类型(对象形式)",
"default": "tsc",
"type": "string",
"enum": ["tsc", "webpack", "swc"],
"description": "指定构建器类型(tsc、webpack、swc)。"
},
"options": {
"type": "object",
"properties": {
"outDir": {"type": "string","description": "输出目录。"},
"filenames": {"type": "array","items": {"type": "string"},"description": "包含的文件名数组。"},
"sync": {"type": "boolean","description": "是否同步文件。"},
"extensions": {"type": "array","items": {"type": "string"},"description": "要考虑的文件扩展名。"},
"copyFiles": {"type": "boolean","description": "是否复制文件。"},
"includeDotfiles": {"type": "boolean","description": "是否包含隐藏文件(点文件)。"},
"quiet": {"type": "boolean","description": "是否静默输出日志。"},
"watch": {"type": "boolean","description": "是否启用文件监控模式。"},
"swcrcPath": {"type": "string","description": "SWC 配置文件路径。"}
}
}
}
}
]
},
"typeCheck": {"$comment":"类型检查","default": false,"type": "boolean","description": "如果为 true,则启用类型检查(仅 SWC 构建器有效)。"},
"webpack": {"$comment":"Webpack 选项(已废弃)","default": false,"type": "boolean","description": "如果为 true,则使用 webpack 编译器(已废弃,建议使用 builder)。"},
"webpackConfigPath": {"$comment":"Webpack 配置路径","default": "webpack.config.js","type": "string","description": "Webpack 配置文件路径,如果未指定,则默认查找 webpack.config.js。"},
"plugins": {"$comment":"CLI 插件配置","default": [],"type": "array","items": {"$ref": "#/definitions/PluginItems"}},
"assets": {"$comment":"非 TypeScript 资源配置","default": [],"type": "array","items": {"$ref": "#/definitions/AssetsOptions"},"description": "启用在每次编译开始时自动分发非 TypeScript 资源,可使用 glob 字符串或对象。"},
"watchAssets": {"default": false,"type": "boolean","description": "如果为 true,则监控所有非 TypeScript 资源。"},
"deleteOutDir": {"type": "boolean","default": false,"description": "如果为 true,则每次编译前删除输出目录。"},
"manualRestart": {"type": "boolean","default": false,"description": "如果为 true,则启用 rs 命令手动重启服务器。"}
},
"additionalProperties": false
},
"AssetsOptions": {
"$comment": "资源选项配置(可为字符串或对象)",
"type": ["string","object"],
"description": "指定要分发的资源文件,可为字符串或对象。",
"properties": {
"include": {"type": "string","description": "匹配要分发的资源文件的 glob 模式。"},
"exclude": {"type": "string","description": "排除的资源文件 glob 模式。"},
"outDir": {"type": "string","description": "分发目标目录(相对于根目录),默认同编译输出目录。"},
"watchAssets": {"type": "boolean","description": "如果为 true,则监控指定资源文件。"}
},
"additionalProperties": false
},
"GenerateOptions": {
"$comment": "生成命令全局选项",
"type": "object",
"description": "全局 generate 命令选项映射。",
"properties": {
"spec": {"$ref": "#/definitions/GenerateSpecOptions"},
"flat": {"$ref": "#/definitions/GenerateFlatOptions"},
"baseDir": {"$ref": "#/definitions/GenerateBaseDirOptions"}
},
"default": {},
"additionalProperties": false
}
},
"properties": {
"language": {"type": "string","default": "ts"},
"collection": {"type": "string","default": "@nestjs/schematics","description": "指定用于生成组件的 schematics 集合,通常无需更改。"},
"sourceRoot": {"type": "string","default": "src","description": "源代码根目录,标准模式为单项目根,monorepo 模式为默认项目根。"},
"entryFile": {"type": "string","default": "main","description": "入口文件,nest start 将从此文件启动应用。"},
"monorepo": {"type": "boolean","default": false,"description": "仅 monorepo 模式使用,值为 true。"},
"root": {"type": "string","default": "","description": "默认项目根目录(monorepo 模式)。"},
"compilerOptions": {"$ref": "#/definitions/CompilerOptions"},
"generateOptions": {"$ref": "#/definitions/GenerateOptions"},
"projects": {"type": "object","additionalProperties": {"$ref": "#/definitions/ProjectConfiguration"},"default": {}},
"defaultLibraryPrefix": {"type": "string","default": "@app","description": "新生成库默认 import 前缀。"}
},
"title": "Nest CLI 配置(中文翻译)",
"type": "object"
}打包为单个文件
pkg 可以把 Node.js 项目连同 Node 运行时一起打包成一个 exe / bin 文件,支持 Windows / Linux / macOS。
注意:
- pkg 不支持动态
require(),Nest 的一些模块(例如动态加载模块、外部 JSON 配置)可能需要调整。 - 一些本地依赖文件可能需要手动指定
assets打包。
@vercel/ncc 可以把 Node.js 项目打包成单个文件。
步骤
安装 ncc:
npm i -D @vercel/ncc编译 Nest 项目:
nest build用 ncc 打包:
ncc build dist/main.js -o dist-bundle运行:
node dist-bundle/index.js特点:
- 支持大多数 Node.js 模块
- 会把依赖打包进一个 JS 文件
- 可结合 PM2 或 Docker 部署
Node 本身对模块是按需加载的,所以一般不需要把 node_modules 全部打包。
打包成单个 JS 文件(比如用 ncc)的主要好处是 提升启动性能,因为不再有大量的文件 I/O 去加载各个模块,而是直接加载一个捆绑好的文件。
对于 Nest 应用来说,单文件打包对部署也更方便(少文件拷贝),而且依赖管理仍然可以通过 package.json 来维护。
生成的 dist-bundle/index.js 就是 独立启动的单文件
依赖按需内联,提高启动速度,同时仍保留 Node 的模块解析优势