oauth_nest_demo/database-flow.md

63 lines
3.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# NestJS & TypeORM 数据写入流程图
这是一个描述在您的项目中,从 NestJS 应用启动到通过 TypeOrm 将用户数据写入数据库的完整流程图。
```mermaid
graph TD
subgraph "1. 应用启动 (Application Bootstrap)"
A[NestJS App Starts] --> B[加载根模块 AppModule];
B --> C{"配置全局数据库连接"};
D[.env 文件] --> E[ConfigService];
E -- 提供配置 --> C;
C --> F["创建全局数据库连接池<br/>(Global DB Connection Pool)"];
end
subgraph "2. 模块和依赖加载 (Module & Dependency Loading)"
B -- 导入 --> G[加载功能模块 UserModule];
G --> H{"为 User 实体注册 Repository"};
F -- 从连接池获取 --> H;
H --> I["在 UserModule 作用域内<br/>注册 User Repository"];
end
subgraph "3. HTTP 请求处理 (HTTP Request Handling)"
J["HTTP Request<br/>(e.g., POST /users)"] --> K[UserController];
K -- 调用方法 --> L[UserService];
I -- 依赖注入 (Inject) --> L["UserService<br/>(constructor receives userRepository)"];
end
subgraph "4. 数据库操作 (Database Operation)"
L -- 1. 调用 --> M["userService.createUser(...)"];
M -- 2. 执行 --> N["this.userRepository.create(data)<br/>(在内存中创建实体)"];
N -- 3. 传递实体 --> O["this.userRepository.save(entity)<br/>(生成 INSERT SQL 语句)"];
O -- 4. 通过连接池发送 SQL --> P[(MySQL 数据库)];
P -- 5. 成功写入 --> Q[user 表];
end
%% Styling
style F fill:#f9f,stroke:#333,stroke-width:2px
style I fill:#ccf,stroke:#333,stroke-width:2px
style P fill:#bbf,stroke:#333,stroke-width:2px
style Q fill:#9f9,stroke:#333,stroke-width:2px
```
### 流程图解读
1. **应用启动**:
* NestJS 应用启动时,首先加载根模块 `AppModule`
* `AppModule` 中的 `TypeOrmModule.forRootAsync` 会利用 `ConfigService` 读取 `.env` 文件中的数据库配置信息。
* 基于这些配置TypeORM 创建一个全局的、可供整个应用使用的数据库连接池。
2. **模块和依赖加载**:
* `AppModule` 加载 `UserModule`
* `UserModule` 中的 `TypeOrmModule.forFeature([User])` 指令会从全局连接池中为 `User` 这个实体获取一个 Repository可以理解为数据表的操作句柄
* 这个 `User` Repository 被注册在 `UserModule` 的依赖注入容器中,等待被使用。
3. **HTTP 请求处理**:
* 当一个外部 HTTP 请求到达 `UserController` 的某个路由时,该路由会调用 `UserService` 中对应的服务方法。
* NestJS 的依赖注入系统会自动将第 2 步注册的 `User` Repository 实例注入到 `UserService` 的构造函数中。
4. **数据库操作**:
* `UserService` 中的方法(如 `createUser`)被执行。
* 代码首先调用 `userRepository.create()` 在内存中创建一个与数据表结构对应的实体对象。
* 紧接着,`userRepository.save()` 方法被调用TypeORM 将这个内存中的对象转换成一条 SQL `INSERT` 语句。
* 这条 SQL 语句通过全局连接池被发送到 MySQL 数据库执行,最终将数据写入 `user` 表中。