npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

midway-dto-prisma

v0.0.3

Published

根据 prisma 模型自动生成MidwayJS DTO 类和 Swagger 参数信息

Readme

Midway DTO Prisma Generator

这是一个为 MidwayJS 项目生成 DTO(数据传输对象)的 Prisma 生成器。它可以根据 Prisma schema 自动生成符合 MidwayJS 参数校验规范的 DTO 类,支持多种操作类型和自定义装饰器。

功能特性

  • 🚀 自动从 Prisma schema 生成完整的 DTO 类体系
  • ✅ 自动生成 Swagger 参数信息(可选)
  • 📝 支持字段注释自动转换为描述信息
  • 🔄 支持所有 Prisma 数据类型和枚举类型
  • 🎯 支持关联字段的嵌套校验
  • 📦 支持批量操作 DTO(创建、更新、删除)
  • 🎨 支持自定义装饰器(创建时、更新时、通用)
  • 🔧 支持字段忽略和自定义导入

安装

npm install --save-dev midway-dto-prisma

配置

在你的 schema.prisma 文件中添加生成器配置:

generator client {
  provider = "prisma-client-js"
}

generator dto {
  provider = "midway-dto-prisma"
  output   = "../src/dto"
}

使用方法

1. 定义 Prisma Schema

model User {
  id        Int      @id @default(autoincrement())
  /// 用户邮箱地址
  /// @ApiProperty({ description: "用户邮箱", example: "[email protected]" })
  /// @Create(@Rule(RuleType.string().email().required()))
  /// @Update(@Rule(RuleType.string().email().optional()))
  email     String   @unique
  name      String?
  age       Int?
  role      UserRole @default(USER)
  posts     Post[]


}

enum UserRole {
  USER
  ADMIN
  MODERATOR
}

2. 生成 DTO

运行 Prisma 生成命令:

npx prisma generate

3. 生成的 DTO 文件

每个模型会自动生成以下 7 种 DTO 类:

CreateUserDTO - 创建用户

export class CreateUserDTO {
  /** 用户邮箱地址 */
  @ApiProperty({
    description: '用户邮箱',
    example: '[email protected]',
    required: true,
  })
  @Rule(RuleType.string().email().required())
  email: string

  @ApiProperty({ required: false })
  @Rule(RuleType.string().optional())
  name: string

  @ApiProperty({ required: false })
  @Rule(RuleType.number().optional())
  age: number

  @ApiProperty({ required: true })
  @Rule(
    RuleType.string()
      .valid(...Object.values(UserRole))
      .required(),
  )
  role: UserRole
}

UpdateUserDTO - 更新用户

export class UpdateUserDTO {
  /** 用户邮箱地址 */
  @ApiProperty({
    description: '用户邮箱',
    example: '[email protected]',
    required: false,
  })
  @Rule(RuleType.string().email().optional())
  email?: string

  @ApiProperty({ required: false })
  @Rule(RuleType.string().optional())
  name?: string

  @ApiProperty({ required: false })
  @Rule(RuleType.number().optional())
  age?: number

  @ApiProperty({ required: false })
  @Rule(
    RuleType.string()
      .valid(...Object.values(UserRole))
      .optional(),
  )
  role?: UserRole
}

BatchCreateUserDTO - 批量创建用户

export class BatchCreateUserDTO {
  @ApiProperty({ description: 'User创建数据列表' })
  @Rule(RuleType.array().items(RuleType.object().required()))
  items: CreateUserDTO[]
}

BatchUpdateUserDTO - 批量更新用户

export class BatchUpdateUserDTO {
  @ApiProperty({ description: 'User更新数据列表' })
  @Rule(RuleType.array().items(RuleType.object().required()))
  items: UpdateUserDTO[]
}

GetUserByIdDTO - 根据 ID 获取用户

export class GetUserByIdDTO {
  @ApiProperty({ description: 'UserID', required: true })
  @Rule(RuleType.number().required())
  id: number
}

DeleteUserDTO - 删除用户

export class DeleteUserDTO {
  @ApiProperty({ description: 'UserID', required: true })
  @Rule(RuleType.number().required())
  id: number
}

BatchDeleteUserDTO - 批量删除用户

export class BatchDeleteUserDTO {
  @ApiProperty({ description: 'UserID列表' })
  @Rule(RuleType.array().items(RuleType.number().required()))
  ids: number[]
}

UserSchema - 用户模型完整结构

export class UserSchema {
  @ApiProperty()
  id: number
  /** 用户邮箱地址 */
  @ApiProperty({ description: '用户邮箱', example: '[email protected]' })
  email: string

  @ApiProperty()
  name?: string

  @ApiProperty()
  age?: number

  @ApiProperty()
  role: UserRole
}

4. 在控制器中使用

import { Controller, Post, Put, Delete, Get, Body, Param } from '@midwayjs/core'
import {
  CreateUserDTO,
  UpdateUserDTO,
  BatchCreateUserDTO,
  BatchUpdateUserDTO,
  BatchDeleteUserDTO,
} from '../dto/UserDTO'

@Controller('/api/user')
export class UserController {
  @Post('/')
  async createUser(@Body() user: CreateUserDTO) {
    // 自动进行参数校验
    return user
  }

  @Post('/batch')
  async batchCreateUsers(@Body() users: BatchCreateUserDTO) {
    // 批量创建用户
    return users
  }

  @Put('/:id')
  async updateUser(@Param('id') id: number, @Body() user: UpdateUserDTO) {
    // 更新用户
    return { id, ...user }
  }

  @Put('/batch')
  async batchUpdateUsers(@Body() users: BatchUpdateUserDTO) {
    // 批量更新用户
    return users
  }

  @Delete('/batch')
  async batchDeleteUsers(@Body() ids: BatchDeleteUserDTO) {
    // 批量删除用户
    return ids
  }
}

自定义装饰器

字段注释装饰器语法

在 Prisma schema 的字段注释中,你可以使用以下装饰器:

通用装饰器

/// @ApiProperty({ description: "字段描述", example: "示例值" })
/// @Rule(RuleType.string().min(3).max(50))

创建时专用装饰器

/// @Create(@ApiProperty({ description: "仅创建DTO生效", example: "示例值" }))
/// @Create(@Rule(RuleType.string().required()))

更新时专用装饰器

/// @Update(@ApiProperty({ description: "仅更新DTO生效", example: "示例值" }))
/// @Update(@Rule(RuleType.string().optional()))

装饰器优先级

  1. 如果字段有 @Create@Update,则使用对应的装饰器
  2. 如果没有特定装饰器,则使用通用装饰器
  3. 自动生成的 @ApiProperty@Rule 会补充缺失的装饰器

支持的数据类型

| 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() | 关联字段类型 |

配置选项

基础配置

generator dto {
  provider = "midway-dto-prisma"
  output   = "../src/dto"
}

高级配置

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 导入
  • 支持添加自定义装饰器和工具

开发

构建项目

npm run build