midway-dto-prisma
Version:
根据 prisma 模型自动生成MidwayJS DTO 类和 Swagger 参数信息
369 lines (283 loc) • 8.47 kB
Markdown
# Midway DTO Prisma Generator
这是一个为 MidwayJS 项目生成 DTO(数据传输对象)的 Prisma 生成器。它可以根据 Prisma schema 自动生成符合 MidwayJS 参数校验规范的 DTO 类,支持多种操作类型和自定义装饰器。
## 功能特性
- 🚀 自动从 Prisma schema 生成完整的 DTO 类体系
- ✅ 自动生成 Swagger 参数信息(可选)
- 📝 支持字段注释自动转换为描述信息
- 🔄 支持所有 Prisma 数据类型和枚举类型
- 🎯 支持关联字段的嵌套校验
- 📦 支持批量操作 DTO(创建、更新、删除)
- 🎨 支持自定义装饰器(创建时、更新时、通用)
- 🔧 支持字段忽略和自定义导入
## 安装
```bash
npm install --save-dev midway-dto-prisma
```
## 配置
在你的 `schema.prisma` 文件中添加生成器配置:
```prisma
generator client {
provider = "prisma-client-js"
}
generator dto {
provider = "midway-dto-prisma"
output = "../src/dto"
}
```
## 使用方法
### 1. 定义 Prisma Schema
```prisma
model User {
id Int
/// 用户邮箱地址
/// @ApiProperty({ description: "用户邮箱", example: "user@example.com" })
/// @Create(@Rule(RuleType.string().email().required()))
/// @Update(@Rule(RuleType.string().email().optional()))
email String
name String?
age Int?
role UserRole
posts Post[]
}
enum UserRole {
USER
ADMIN
MODERATOR
}
```
### 2. 生成 DTO
运行 Prisma 生成命令:
```bash
npx prisma generate
```
### 3. 生成的 DTO 文件
每个模型会自动生成以下 7 种 DTO 类:
#### CreateUserDTO - 创建用户
```typescript
export class CreateUserDTO {
/** 用户邮箱地址 */
email: string
name: string
age: number
role: UserRole
}
```
#### UpdateUserDTO - 更新用户
```typescript
export class UpdateUserDTO {
/** 用户邮箱地址 */
email?: string
name?: string
age?: number
role?: UserRole
}
```
#### BatchCreateUserDTO - 批量创建用户
```typescript
export class BatchCreateUserDTO {
items: CreateUserDTO[]
}
```
#### BatchUpdateUserDTO - 批量更新用户
```typescript
export class BatchUpdateUserDTO {
items: UpdateUserDTO[]
}
```
#### GetUserByIdDTO - 根据 ID 获取用户
```typescript
export class GetUserByIdDTO {
id: number
}
```
#### DeleteUserDTO - 删除用户
```typescript
export class DeleteUserDTO {
id: number
}
```
#### BatchDeleteUserDTO - 批量删除用户
```typescript
export class BatchDeleteUserDTO {
ids: number[]
}
```
#### UserSchema - 用户模型完整结构
```typescript
export class UserSchema {
id: number
/** 用户邮箱地址 */
email: string
name?: string
age?: number
role: UserRole
}
```
### 4. 在控制器中使用
```typescript
import { Controller, Post, Put, Delete, Get, Body, Param } from '@midwayjs/core'
import {
CreateUserDTO,
UpdateUserDTO,
BatchCreateUserDTO,
BatchUpdateUserDTO,
BatchDeleteUserDTO,
} from '../dto/UserDTO'
export class UserController {
async createUser( user: CreateUserDTO) {
// 自动进行参数校验
return user
}
async batchCreateUsers( users: BatchCreateUserDTO) {
// 批量创建用户
return users
}
async updateUser( id: number, user: UpdateUserDTO) {
// 更新用户
return { id, ...user }
}
async batchUpdateUsers( users: BatchUpdateUserDTO) {
// 批量更新用户
return users
}
async batchDeleteUsers( ids: BatchDeleteUserDTO) {
// 批量删除用户
return ids
}
}
```
## 自定义装饰器
### 字段注释装饰器语法
在 Prisma schema 的字段注释中,你可以使用以下装饰器:
#### 通用装饰器
```prisma
/// @ApiProperty({ description: "字段描述", example: "示例值" })
/// @Rule(RuleType.string().min(3).max(50))
```
#### 创建时专用装饰器
```prisma
/// @Create(@ApiProperty({ description: "仅创建DTO生效", example: "示例值" }))
/// @Create(@Rule(RuleType.string().required()))
```
#### 更新时专用装饰器
```prisma
/// @Update(@ApiProperty({ description: "仅更新DTO生效", example: "示例值" }))
/// @Update(@Rule(RuleType.string().optional()))
```
### 装饰器优先级
1. 如果字段有 `` 或 ``,则使用对应的装饰器
2. 如果没有特定装饰器,则使用通用装饰器
3. 自动生成的 `` 和 `` 会补充缺失的装饰器
## 支持的数据类型
| Prisma 类型 | TypeScript 类型 | 校验规则 | 说明 |
| ----------- | --------------- | ---------------------------- | ------------ |
| String | string | RuleType.string() | 字符串类型 |
| Boolean | boolean | RuleType.boolean() | 布尔类型 |
| Int | number | RuleType.number() | 整数类型 |
| BigInt | number | RuleType.number() | 大整数类型 |
| Float | number | RuleType.number() | 浮点数类型 |
| Decimal | number | RuleType.number() | 十进制类型 |
| DateTime | Date | RuleType.date() | 日期时间类型 |
| Json | any | RuleType.any() | JSON 类型 |
| Bytes | Buffer | RuleType.binary() | 二进制类型 |
| Enum | enum | RuleType.string().valid(...) | 枚举类型 |
| Object | object | RuleType.object().schema() | 关联字段类型 |
## 配置选项
### 基础配置
```prisma
generator dto {
provider = "midway-dto-prisma"
output = "../src/dto"
}
```
### 高级配置
```prisma
generator dto {
provider = "midway-dto-prisma"
output = "../src/dto"
// 忽略特定字段
ignoreFields = ["createdAt", "updatedAt"]
// 启用 Swagger 支持
enableSwagger = true
// 自定义导入语句
customImports = [
"import { CustomDecorator } from './custom';",
"import { ValidationRule } from './validation';"
]
}
```
## 高级特性
### 字段过滤
- 支持忽略特定字段
- 创建 DTO 自动排除 ID 字段
- 更新 DTO 所有字段都是可选的
### 关联字段支持
- 自动生成嵌套对象的校验规则
- 支持一对多和多对多关系
- 生成 `ResponseDTO` 类型的关联字段
### 批量操作
- 自动生成批量创建、更新、删除的 DTO
- 支持数组校验和对象嵌套校验
- 统一的批量操作接口
### 自定义导入
- 支持完全自定义导入语句
- 可以覆盖默认的 MidwayJS 导入
- 支持添加自定义装饰器和工具
## 开发
### 构建项目
```bash
npm run build
```