### Install @brakebein/prisma-generator-nestjs-dto Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Install the package as a development dependency using npm. ```bash npm install --save-dev @brakebein/prisma-generator-nestjs-dto ``` -------------------------------- ### Generated Output Structure Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Example of the generated file structure when using the default NestJS resource structure. ```tree src/generated/nestjs-dto/ user/ dto/ connect-user.dto.ts create-user.dto.ts update-user.dto.ts user.dto.ts entities/ user.entity.ts index.ts ``` -------------------------------- ### Configure Prisma Schema Generator Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Add the generator block to your schema.prisma file to configure DTO and Entity generation. This example shows various configuration options. ```prisma generator client { provider = "prisma-client-js" } generator nestjsDto { provider = "prisma-generator-nestjs-dto" output = "../src/generated/nestjs-dto" outputToNestJsResourceStructure = "true" flatResourceStructure = "false" exportRelationModifierClasses = "true" reExport = "true" generateFileTypes = "all" createDtoPrefix = "Create" updateDtoPrefix = "Update" dtoSuffix = "Dto" entityPrefix = "" entitySuffix = "" classValidation = "true" fileNamingStyle = "kebab" noDependencies = "false" outputType = "class" definiteAssignmentAssertion = "false" requiredResponseApiProperty = "true" prettier = "true" wrapRelationsAsType = "false" showDefaultValues = "false" } model User { id String @id @default(uuid()) email String @unique name String } ``` -------------------------------- ### Prisma Schema with DTO Annotations Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md Example of applying various DTO annotations to model fields in a Prisma Schema. Use triple-slash comments to add annotations like @DtoCreateOptional, @DtoUpdateHidden, and @DtoOverrideType. ```prisma model Post { /// @DtoCreateOptional /// @DtoUpdateHidden createdAt DateTime @default(now()) /// @DtoOverrideType(DurationLike, luxon) timeUntilExpires Json? } ``` -------------------------------- ### Enriching @ApiProperty with Schema Annotations Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use Prisma schema annotations like `@description`, `@example`, `@minLength`, `@maxLength`, `@minimum`, `@maximum`, and `@maxItems` to automatically populate `@ApiProperty` decorators in generated DTOs. Ensure these annotations are placed directly above the field they describe. ```prisma model Product { id String @id @default(uuid()) /// @description The product's display name /// @example "Wireless Keyboard" /// @minLength 3 /// @maxLength 100 name String /// @description Star rating (1–5) /// @minimum 1 /// @maximum 5 /// @example 4 rating Int @default(3) /// @description List of image URLs /// @maxItems 10 images Json[] } ``` -------------------------------- ### Prisma Schema Configuration for NestJS DTO Generator Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Configure the prisma-generator-nestjs-dto provider in your schema.prisma file. This setup enables features like outputting to a specific directory, generating relation modifier classes, and enforcing class-validator rules. ```prisma generator nestjsDto { provider = "prisma-generator-nestjs-dto" output = "../src/generated/nestjs-dto" outputToNestJsResourceStructure = "true" exportRelationModifierClasses = "true" reExport = "true" classValidation = "true" fileNamingStyle = "kebab" prettier = "true" } model Order { /// @description Unique order ID id String @id @default(uuid()) /// @DtoReadOnly createdAt DateTime @default(now()) /// @description Total price in USD cents /// @minimum 1 /// @example 4999 totalCents Int status OrderStatus @default(pending) customerId String /// @DtoRelationRequired /// @DtoRelationCanConnectOnCreate customer Customer @relation(fields: [customerId], references: [id]) /// @DtoRelationCanCreateOnCreate /// @DtoRelationCanConnectOnCreate /// @DtoRelationCanCreateOnUpdate /// @DtoRelationCanConnectOnUpdate items OrderItem[] } enum OrderStatus { pending processing shipped delivered cancelled } ``` -------------------------------- ### Infer Validation Decorators from Prisma Schema Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md This example demonstrates how Prisma schema attributes and comment tags are translated into NestJS validation decorators from the `class-validator` library. Optional fields, arrays, and specific types are handled automatically. ```prisma /// @Contains('Product') name String @db.VarChar(255) reviewCount Int @default(0) /// @ArrayNotEmpty tags String[] score Float? ``` -------------------------------- ### Generated Class Validator Decorators for DTOs Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md The generated TypeScript code includes validation decorators based on the Prisma schema. This example shows decorators for string types, optional integers, arrays, and numbers, including custom decorators like `@Contains` and `@ArrayNotEmpty`. ```typescript @IsNotEmpty() @IsString() @Contains('Product') name: string; @IsOptional() @IsInt() reviewCount?: number; @IsNotEmpty() @IsArray() @ArrayNotEmpty() tags: string[]; @IsOptional() @IsNumber() score?: number; ``` -------------------------------- ### Run Prisma Generation Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Execute the Prisma generate command to create DTOs and Entities based on your schema configuration. ```bash npx prisma generate ``` -------------------------------- ### Initialize Prisma Generator with `generatorHandler` Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt The `generatorHandler` function is the main entry point for the Prisma generator. It registers the generator with Prisma and defines the `onManifest` and `onGenerate` callbacks. Use this to integrate the generator into the `prisma generate` workflow. ```typescript import { generatorHandler, GeneratorOptions } from '@prisma/generator-helper'; import { WritableDeep } from 'type-fest'; // The generator registers itself via generatorHandler – invoked automatically by `prisma generate` generatorHandler({ onManifest: () => ({ defaultOutput: '../src/generated/nestjs-dto', prettyName: 'NestJS DTO Generator', }), onGenerate: async (options: WritableDeep) => { // Reads options.generator.config (all schema.prisma params) // Calls run() to compute file specs from the DMMF // Writes files to disk, optionally formatting with Prettier // Returns: Promise await generate(options); }, }); ``` -------------------------------- ### Configure Prisma Generator Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md Configure the generator in your schema.prisma file to specify output paths and customization options. ```prisma generator nestjsDto { provider = "prisma-generator-nestjs-dto" output = "../src/generated/nestjs-dto" prismaClientImportPath = "" outputToNestJsResourceStructure = "false" flatResourceStructure = "false" exportRelationModifierClasses = "true" reExport = "false" generateFileTypes = "all" createDtoPrefix = "Create" updateDtoPrefix = "Update" dtoSuffix = "Dto" entityPrefix = "" entitySuffix = "" classValidation = "false" fileNamingStyle = "camel" noDependencies = "false" outputType = "class" definiteAssignmentAssertion = "false" requiredResponseApiProperty = "true" prettier = "false" wrapRelationsAsType = "false" showDefaultValues = "false" } ``` -------------------------------- ### Execute Core Generator Pipeline with `run` Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt The `run` function processes DMMF and generator options to produce an array of file specifications. Configure various aspects of DTO generation, such as prefixes, suffixes, validation, and output structure. This function does not write files to disk. ```typescript import { run } from './generator'; import { DMMF } from '@prisma/generator-helper'; const fileSpecs = run({ output: '/project/src/generated/nestjs-dto', dmmf: dmmfDocument, // WritableDeep exportRelationModifierClasses: true, outputToNestJsResourceStructure: true, flatResourceStructure: false, connectDtoPrefix: 'Connect', createDtoPrefix: 'Create', updateDtoPrefix: 'Update', dtoSuffix: 'Dto', entityPrefix: '', entitySuffix: '', fileNamingStyle: 'kebab', classValidation: true, outputType: 'class', noDependencies: false, definiteAssignmentAssertion: false, requiredResponseApiProperty: true, prismaClientImportPath: '@prisma/client', outputApiPropertyType: true, generateFileTypes: 'all', wrapRelationsAsType: false, showDefaultValues: false, }); // fileSpecs: Array<{ fileName: string; content: string }> // e.g. [ // { fileName: '/project/src/generated/nestjs-dto/user/dto/create-user.dto.ts', content: '...' }, // { fileName: '/project/src/generated/nestjs-dto/user/entities/user.entity.ts', content: '...' }, // ... // ] fileSpecs.forEach(({ fileName, content }) => { console.log(fileName); console.log(content.slice(0, 200)); }); ``` -------------------------------- ### Frontend-Friendly Output with Interfaces Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use `noDependencies = "true"` and `outputType = "interface"` to generate DTOs without NestJS or Prisma imports, suitable for frontend projects. Enums are generated separately. ```prisma generator nestjsDtoFrontend { provider = "prisma-generator-nestjs-dto" output = "../frontend/src/types/api" outputType = "interface" noDependencies = "true" generateFileTypes = "dto" } model Invoice { id String @id @default(uuid()) amount Decimal dueDate DateTime status InvoiceStatus notes Json? } enum InvoiceStatus { draft sent paid } ``` ```typescript // enums.ts (generated when noDependencies = "true") export const invoiceStatus = ['draft', 'sent', 'paid'] as const; export type InvoiceStatus = (typeof invoiceStatus)[number]; // createInvoice.dto.ts import { InvoiceStatus } from './enums'; export interface CreateInvoiceDto { // Decimal → String when noDependencies = "true" amount: string; dueDate: Date; status: InvoiceStatus; // Json → Object when noDependencies = "true" notes?: { [key: string]: any } | null; } ``` -------------------------------- ### NestJS Resource Structure Output Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Configure `outputToNestJsResourceStructure = "true"` to organize generated files according to the NestJS CLI CRUD generator layout. This includes re-exporting modules via index files. ```prisma generator nestjsDto { provider = "prisma-generator-nestjs-dto" output = "../src/generated" outputToNestJsResourceStructure = "true" flatResourceStructure = "false" reExport = "true" fileNamingStyle = "kebab" } model Article { id String @id @default(uuid()) title String body String } ``` ```plaintext src/generated/ article/ dto/ connect-article.dto.ts create-article.dto.ts update-article.dto.ts article.dto.ts index.ts ← reExport barrel entities/ article.entity.ts index.ts index.ts ← root barrel re-exporting all modules ``` ```typescript export * from './article/dto'; export * from './article/entities'; ``` -------------------------------- ### Generated CreateQuestionDto Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md A DTO for creating a new Question entity, including relation inputs for category and tags. ```typescript // src/question/dto/create-question.dto.ts import { ApiExtraModels } from '@nestjs/swagger'; import { ConnectCategoryDto } from '../../category/dto/connect-category.dto'; import { CreateTagDto } from '../../tag/dto/create-tag.dto'; import { ConnectTagDto } from '../../tag/dto/connect-tag.dto'; export class CreateQuestionCategoryRelationInputDto { connect: ConnectCategoryDto; } export class CreateQuestionTagsRelationInputDto { create?: CreateTagDto[]; connect?: ConnectTagDto[]; } @ApiExtraModels( ConnectCategoryDto, CreateQuestionCategoryRelationInputDto, CreateTagDto, ConnectTagDto, CreateQuestionTagsRelationInputDto, ) export class CreateQuestionDto { category: CreateQuestionCategoryRelationInputDto; tags?: CreateQuestionTagsRelationInputDto; title: string; content: string; } ``` -------------------------------- ### Generated Question Entity Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md Represents the Question entity, mirroring the Prisma model structure with associated types. ```typescript // src/question/entities/question.entity.ts import { User } from '../../user/entities/user.entity'; import { Category } from '../../category/entities/category.entity'; import { Tag } from '../../tag/entities/tag.entity'; import { Response } from '../../response/entities/response.entity'; export class Question { id: string; createdAt: Date; createdBy?: User; createdById: string; updatedAt: Date; updatedBy?: User; updatedById: string; category?: Category; categoryId: string; tags?: Tag[]; title: string; content: string; responses?: Response[]; } ``` -------------------------------- ### Annotate Prisma Schema for Swagger API Properties Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md Use comment tags like `@description` and `@minimum` above Prisma schema fields to add custom schema information. This information is then used to generate `@ApiProperty()` decorators with corresponding properties in the DTOs. ```prisma /// @description Number of reviews /// @minimum 9 reviewCount Int @default(0) ``` -------------------------------- ### Prisma Generator NestJS DTO Configuration Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Configure the NestJS DTO generator within your schema.prisma file. All parameters are optional and shown with their defaults. ```prisma generator nestjsDto { provider = "prisma-generator-nestjs-dto" // Output path relative to schema.prisma output = "../src/generated/nestjs-dto" // Override Prisma client import path (auto-detected by default) prismaClientImportPath = "" // Write DTOs/entities to NestJS CRUD resource subfolders (model/dto/, model/entities/) outputToNestJsResourceStructure = "false" // Flatten the resource structure (model/ instead of model/dto/ and model/entities/) flatResourceStructure = "false" // Export relation modifier helper classes exportRelationModifierClasses = "true" // Generate an index.ts barrel file per folder reExport = "false" // "all" | "dto" | "entity" generateFileTypes = "all" // Prefix/suffix for class names createDtoPrefix = "Create" updateDtoPrefix = "Update" dtoSuffix = "Dto" entityPrefix = "" entitySuffix = "" // "camel" | "pascal" | "kebab" | "snake" fileNamingStyle = "camel" // Add class-validator decorators to CreateDTO and UpdateDTO classValidation = "false" // "class" | "interface" outputType = "class" // Omit NestJS/Prisma-specific imports and decorators (for frontend DTOs) noDependencies = "false" // Add ! to required fields (needed when strictPropertyInitialization is enabled) definiteAssignmentAssertion = "false" // Response DTO fields required by default in @ApiProperty requiredResponseApiProperty = "true" // Auto-format output files with Prettier prettier = "false" // Import relations as types to avoid SWC circular reference issues wrapRelationsAsType = "false" // Make @default() fields visible in CreateDTO/UpdateDTO automatically showDefaultValues = "false" } ``` -------------------------------- ### Field-Level Annotations for DTO Control Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use triple-slash comments above fields to control their inclusion and behavior in generated DTOs and entities. These annotations offer fine-grained control over visibility and mutability. ```prisma model Post { id String @id @default(uuid()) /// @DtoReadOnly // Omitted from CreateDTO and UpdateDTO (read-only timestamp, etc.) createdAt DateTime @default(now()) /// @DtoCreateHidden // Omitted only from CreateDTO internalToken String? /// @DtoUpdateHidden // Omitted only from UpdateDTO score Float? /// @DtoEntityHidden // Omitted only from Entity passwordHash String /// @DtoConnectHidden // Omitted from ConnectDTO (applies only to @id / @unique fields) slug String @unique /// @DtoApiHidden // Adds @ApiHideProperty() – still validated, but hidden in Swagger UI sensitiveField String /// @DtoIgnoreModel (applied to model, not field) // Skip this entire model – no files will be generated for it } ``` -------------------------------- ### Generated UpdateQuestionDto Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md A DTO for updating an existing Question entity, allowing optional updates to title, content, and tags. ```typescript // src/question/dto/update-question.dto.ts import { ApiExtraModels } from '@nestjs/swagger'; import { CreateTagDto } from '../../tag/dto/create-tag.dto'; import { ConnectTagDto } from '../../tag/dto/connect-tag.dto'; export class UpdateQuestionTagsRelationInputDto { create?: CreateTagDto[]; connect?: ConnectTagDto[]; } @ApiExtraModels(CreateTagDto, ConnectTagDto, UpdateQuestionTagsRelationInputDto) export class UpdateQuestionDto { tags?: UpdateQuestionTagsRelationInputDto; title?: string; content?: string; } ``` -------------------------------- ### Generated Swagger API Property Decorator Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md This TypeScript code shows the `@ApiProperty()` decorator generated from the Prisma schema annotations. It includes custom properties like `description` and `minimum`, as well as inferred `type` and `format`. ```typescript @ApiProperty({ description: 'Number of reviews', minimum: 9, type: 'integer', format: 'int32', }) reviewCount: number; ``` -------------------------------- ### Prisma Schema Configuration Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md Defines the Prisma schema with generator configuration and model definitions, including custom annotations for DTO generation. ```prisma generator nestjsDto { provider = "prisma-generator-nestjs-dto" output = "../src" outputToNestJsResourceStructure = "true" } model Question { id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid /// @DtoReadOnly createdAt DateTime @default(now()) /// @DtoRelationRequired createdBy User? @relation("CreatedQuestions", fields: [createdById], references: [id]) createdById String? @db.Uuid updatedAt DateTime @updatedAt /// @DtoRelationRequired updatedBy User? @relation("UpdatedQuestions", fields: [updatedById], references: [id]) updatedById String? @db.Uuid /// @DtoRelationRequired /// @DtoRelationCanConnectOnCreate category Category? @relation(fields: [categoryId], references: [id]) categoryId String? @db.Uuid /// @DtoCreateOptional /// @DtoRelationCanCreateOnCreate /// @DtoRelationCanConnectOnCreate /// @DtoRelationCanCreateOnUpdate /// @DtoRelationCanConnectOnUpdate tags Tag[] title String content String responses Response[] } ``` -------------------------------- ### Generated CreateOrderDto for NestJS Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt This DTO is automatically generated from the Prisma schema. It includes class-validator decorators for validation and @nestjs/swagger decorators for API documentation, ensuring type safety and clear API contracts. ```typescript // src/generated/nestjs-dto/order/dto/create-order.dto.ts import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; import { IsNotEmpty, IsInt, Min, IsEnum, IsOptional, IsArray, ValidateNested } from 'class-validator'; import { Type } from 'class-transformer'; import { ConnectCustomerDto } from '../../customer/dto/connect-customer.dto'; import { CreateOrderItemDto } from '../../order-item/dto/create-order-item.dto'; import { ConnectOrderItemDto } from '../../order-item/dto/connect-order-item.dto'; import { OrderStatus } from '@prisma/client'; export class CreateOrderCustomerRelationInputDto { connect: ConnectCustomerDto; } export class CreateOrderItemsRelationInputDto { create?: CreateOrderItemDto[]; connect?: ConnectOrderItemDto[]; } @ApiExtraModels( ConnectCustomerDto, CreateOrderCustomerRelationInputDto, CreateOrderItemDto, ConnectOrderItemDto, CreateOrderItemsRelationInputDto, ) export class CreateOrderDto { @ApiProperty({ description: 'Total price in USD cents', minimum: 1, example: 4999, type: 'integer', format: 'int32' }) @IsNotEmpty() @IsInt() @Min(1) totalCents!: number; @ApiProperty({ enum: OrderStatus, enumName: 'OrderStatus', required: false }) @IsOptional() @IsEnum(OrderStatus) status?: OrderStatus; @ApiProperty({ type: CreateOrderCustomerRelationInputDto }) @IsNotEmpty() @ValidateNested() @Type(() => CreateOrderCustomerRelationInputDto) customer!: CreateOrderCustomerRelationInputDto; @ApiProperty({ type: CreateOrderItemsRelationInputDto, required: false }) @IsOptional() @ValidateNested() @Type(() => CreateOrderItemsRelationInputDto) items?: CreateOrderItemsRelationInputDto; } ``` -------------------------------- ### Optional and Required Field Overrides Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Override default optional/required behavior for fields in CreateDTO and UpdateDTO using specific annotations. Useful for fields with defaults or those that should always be present. ```prisma model Order { id String @id @default(uuid()) /// @DtoCreateOptional // Adds field optionally to CreateDTO (useful for @id, @updatedAt, @default fields) externalRef String @default("") /// @DtoCreateRequired // Marks a normally-omitted field as required in CreateDTO /// @DtoUpdateRequired // Marks a normally-omitted field as required in UpdateDTO confirmedAt DateTime @updatedAt /// @DtoUpdateOptional // Adds field optionally to UpdateDTO metadata Json? } ``` -------------------------------- ### Check Field Annotations with `isAnnotatedWith` Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt The `isAnnotatedWith` utility checks if a Prisma DMMF field or model has a specific annotation in its documentation comment. It can also return annotation parameters, such as type names or import sources, when requested. ```typescript import { isAnnotatedWith } from './generator/field-classifiers'; import { DTO_READ_ONLY, DTO_OVERRIDE_TYPE, DTO_CREATE_OPTIONAL, } from './generator/annotations'; import type { DMMF } from '@prisma/generator-helper'; // Check boolean presence const field: Pick = { documentation: '@DtoReadOnly\nSome description', }; isAnnotatedWith(field, DTO_READ_ONLY); // → true // Return annotation parameters (e.g. type name, import source) const fieldWithType: Pick = { documentation: '@DtoOverrideType(MySpecialType, my-package)', }; const params = isAnnotatedWith(fieldWithType, DTO_OVERRIDE_TYPE, { returnAnnotationParameters: true, }); // → 'MySpecialType, my-package' const [typeName, importPath] = (params as string).split(', '); // typeName → 'MySpecialType' // importPath → 'my-package' // No annotation present isAnnotatedWith({ documentation: undefined }, DTO_CREATE_OPTIONAL); // → false ``` -------------------------------- ### Generated DTO with class-validator Decorators Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt This TypeScript code demonstrates a generated DTO incorporating `class-validator` decorators inferred from Prisma schema annotations. It includes necessary imports for validation decorators. ```typescript // create-user.dto.ts import { IsNotEmpty, IsString, IsEmail, MaxLength, MinLength, Matches, IsArray, ArrayNotEmpty, IsUUID, IsOptional, IsInt } from 'class-validator'; export class CreateUserDto { @ApiProperty({ type: 'string' }) @IsNotEmpty() @IsString() @IsEmail({}) @MaxLength(255) email!: string; @ApiProperty({ type: 'string' }) @IsNotEmpty() @IsString() @MinLength(8) @Matches('^(?=.*[A-Z])(?=.*[0-9]).+$', 'g') password!: string; @ApiProperty({ type: 'string', isArray: true }) @IsNotEmpty() @IsArray() @ArrayNotEmpty() @IsUUID('4', { each: true }) roleIds!: string[]; @ApiProperty({ type: 'integer', format: 'int32', required: false, nullable: true }) @IsOptional() @IsInt() age?: number | null; } ``` -------------------------------- ### Circular Reference Handling with `wrapRelationsAsType` Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Set `wrapRelationsAsType = "true"` to prevent SWC circular reference issues by importing relation types instead of values. This ensures safe imports for related entities. ```prisma generator nestjsDto { provider = "prisma-generator-nestjs-dto" output = "../src/generated" wrapRelationsAsType = "true" } model Author { id String @id @default(uuid()) books Book[] } model Book { id String @id @default(uuid()) title String authorId String /// @DtoRelationRequired author Author @relation(fields: [authorId], references: [id]) } ``` ```typescript // book.entity.ts import type { Author } from '../author/entities/author.entity'; export class BookEntity { @ApiProperty() id!: string; @ApiProperty({ type: 'string' }) title!: string; // Imported as `type` – safe for SWC @ApiProperty({ type: () => Author }) author?: Author; } ``` -------------------------------- ### Parse API Property Decorator Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use `parseApiProperty` to build an array of `IApiProperty` objects for the `@ApiProperty()` decorator. Control inclusion of documentation, defaults, and type information based on the `ParsedField` and options. ```typescript import { parseApiProperty } from './generator/api-decorator'; import type { ParsedField } from './generator/types'; const field: ParsedField = { name: 'reviewCount', kind: 'scalar', type: 'Int', isRequired: false, isList: false, isId: false, isUnique: false, isReadOnly: false, hasDefaultValue: true, default: 0, isNullable: true, documentation: '@description Number of reviews\n@minimum 0\n@example 5', }; const props = parseApiProperty(field, { default: true, doc: true, type: true }); // → [ // { name: 'description', value: 'Number of reviews' }, // { name: 'minimum', value: '0' }, // { name: 'example', value: '5' }, // { name: 'type', value: 'integer' }, // { name: 'format', value: 'int32' }, // { name: 'default', value: '0' }, // { name: 'required', value: 'false' }, // { name: 'nullable', value: 'true' }, // ] // Exclude default and type info (e.g. for ConnectDTO) const connectProps = parseApiProperty(field, { default: false, type: false }); // → [ // { name: 'description', value: 'Number of reviews' }, // { name: 'minimum', value: '0' }, // { name: 'example', value: '5' }, // { name: 'required', value: 'false' }, // { name: 'nullable', value: 'true' }, // ] ``` -------------------------------- ### Conditional Validation with @DtoCreateValidateIf and @DtoUpdateValidateIf Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use `@DtoCreateValidateIf` and `@DtoUpdateValidateIf` annotations in the Prisma schema to apply validation decorators conditionally based on other field values. These annotations accept a function that returns a boolean. ```prisma model Post { id String @id @default(uuid()) otherProperty String @unique /// @ValidateIf(o => o.otherProperty === 'value') general String /// @DtoCreateValidateIf(o => o.otherProperty) /// @IsNotEmpty() exampleCreate String /// @DtoUpdateValidateIf(o => o.otherProperty === 'someValue') /// @Contains('something') exampleUpdate String } ``` -------------------------------- ### Adding Validation Decorators with classValidation Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt When `classValidation` is enabled in the generator options, you can add `class-validator` decorators directly in the Prisma schema comment blocks to automatically include them in the generated DTOs. ```prisma model User { id String @id @default(uuid()) /// @IsEmail({}) /// @MaxLength(255) email String /// @MinLength(8) /// @Matches('^(?=.*[A-Z])(?=.*[0-9]).+$', 'g') password String /// @ArrayNotEmpty /// @IsUUID('4') roleIds String[] /// @IsOptional() age Int? } ``` -------------------------------- ### Generated DTO with @ApiProperty Annotations Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt This TypeScript code shows the generated DTO based on the Prisma schema with `@ApiProperty` decorators enriched by schema annotations. It includes standard NestJS validation decorators like `@IsNotEmpty` and `@IsString`. ```typescript // create-product.dto.ts export class CreateProductDto { @ApiProperty({ description: "The product's display name", example: 'Wireless Keyboard', minLength: 3, maxLength: 100, type: 'string', }) @IsNotEmpty() @IsString() name!: string; @ApiProperty({ description: 'Star rating (1–5)', minimum: 1, maximum: 5, example: 4, type: 'integer', format: 'int32', default: 3, required: false, }) @IsOptional() @IsInt() rating?: number; @ApiProperty({ description: 'List of image URLs', maxItems: 10, type: Object, isArray: true, }) @IsNotEmpty() @IsArray() images!: Prisma.JsonValue[]; } ``` -------------------------------- ### Generated DTOs with Conditional Validation Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt These TypeScript code snippets show the generated DTOs for creation and update operations, incorporating conditional validation decorators based on the Prisma schema annotations. Note the use of `@IsOptional` for update DTO fields. ```typescript // create-post.dto.ts export class CreatePostDto { @ApiProperty({ type: 'string' }) @ValidateIf((o) => o.otherProperty === 'value') @IsNotEmpty() @IsString() general!: string; @ApiProperty({ type: 'string' }) @ValidateIf((o) => o.otherProperty) @IsNotEmpty() exampleCreate!: string; } ``` ```typescript // update-post.dto.ts export class UpdatePostDto { @ApiProperty({ type: 'string', required: false }) @IsOptional() @IsString() general?: string; @ApiProperty({ type: 'string', required: false }) @ValidateIf((o) => o.otherProperty === 'someValue') @IsNotEmpty() @Contains('something') exampleUpdate?: string; } ``` -------------------------------- ### Generated ConnectQuestionDto Source: https://github.com/brakebein/prisma-generator-nestjs-dto/blob/main/README.md A DTO used to connect to a Question entity, typically used in relation fields of other DTOs. ```typescript // src/question/dto/connect-question.dto.ts export class ConnectQuestionDto { id: string; } ``` -------------------------------- ### Generate Standalone Enum File Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use `generateEnums` to create a standalone `enums.ts` file containing typed const arrays for enums when `noDependencies` is set to `true`. This is compatible with both class and interface output. ```typescript import { generateEnums } from './generator/generate-enums'; import type { DMMF } from '@prisma/generator-helper'; const enums: DMMF.DatamodelEnum[] = [ { name: 'UserRole', values: [{ name: 'admin' }, { name: 'user' }, { name: 'guest' }], dbName: null, documentation: undefined, }, { name: 'OrderStatus', values: [{ name: 'pending' }, { name: 'shipped' }, { name: 'delivered' }], dbName: null, documentation: undefined, }, ]; const content = generateEnums(enums); console.log(content); // Output: // // export const userRole = ['admin', 'user', 'guest'] as const; // export type UserRole = (typeof userRole)[number]; // // export const orderStatus = ['pending', 'shipped', 'delivered'] as const; // export type OrderStatus = (typeof orderStatus)[number]; ``` -------------------------------- ### Build Class Validator Decorators Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use `parseClassValidators` to generate a list of `class-validator` decorators for a field. It combines inferred type validators with those specified in the field's documentation. ```typescript import { parseClassValidators } from './generator/class-validator'; import type { ParsedField } from './generator/types'; const nameField: ParsedField = { name: 'name', kind: 'scalar', type: 'String', isRequired: true, isList: false, isId: false, isUnique: false, isReadOnly: false, hasDefaultValue: false, documentation: "@MinLength(2)\n@MaxLength(100)\n@Contains('Product')", }; parseClassValidators(nameField); // → [ // { name: 'IsNotEmpty' }, // inferred from isRequired // { name: 'MinLength', value: '2' }, // { name: 'MaxLength', value: '100' }, // { name: 'Contains', value: "'Product'" }, // // note: IsString is replaced by the user-defined validators above // ] // List field with enum const tagsField: ParsedField = { name: 'roles', kind: 'enum', type: 'UserRole', isRequired: false, isList: true, isId: false, isUnique: false, isReadOnly: false, hasDefaultValue: false, }; parseClassValidators(tagsField); // → [ // { name: 'IsOptional' }, // { name: 'IsArray' }, // { name: 'IsEnum', value: 'UserRole, { each: true }' }, // ] ``` -------------------------------- ### Relation Modifier Annotations Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Control how relations are handled in DTOs using relation modifier annotations. These annotations specify requirements, creation/connection options, and inclusion of foreign keys. ```prisma model Article { id String @id @default(uuid()) title String authorId String /// @DtoRelationRequired // Marks relation as required in Entity (overrides optional FK) /// @DtoRelationCanCreateOnCreate // Adds `create` input option to CreateDTO for this relation /// @DtoRelationCanConnectOnCreate // Adds `connect` input option to CreateDTO for this relation /// @DtoRelationCanCreateOnUpdate // Adds `create` input option to UpdateDTO /// @DtoRelationCanConnectOnUpdate // Adds `connect` input option to UpdateDTO /// @DtoRelationCanUpdateOnUpdate // Adds `update` input option to UpdateDTO (-to-one only) /// @DtoRelationCanDisconnectOnUpdate // Adds `disconnect` input option to UpdateDTO author User? @relation(fields: [authorId], references: [id]) /// @DtoRelationIncludeId // Includes the FK field in DTOs (instead of CanCreate/CanConnect) tagId String tag Tag? @relation(fields: [tagId], references: [id]) } ``` -------------------------------- ### Composite Types with @DtoTypeFullUpdate Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use composite types in Prisma schema for MongoDB. The `@DtoTypeFullUpdate` decorator enforces full replacement for nested types in UpdateDTOs, using the CreateDTO instead of a specific UpdateDTO. ```prisma datasource db { provider = "mongodb" url = env("DATABASE_URL") } type Address { street String city String country String } type Score { value Int comment String? } model Profile { id String @id @default(auto()) @map("_id") @db.ObjectId name String address Address /// @DtoTypeFullUpdate // UpdateDTO uses CreateScoreDto (full replacement) instead of UpdateScoreDto score Score } ``` ```typescript // create-address.dto.ts export class CreateAddressDto { @ApiProperty({ type: 'string' }) street!: string; @ApiProperty({ type: 'string' }) city!: string; @ApiProperty({ type: 'string' }) country!: string; } // update-profile.dto.ts import { CreateScoreDto } from './create-score.dto'; import { CreateAddressDto } from './create-address.dto'; export class UpdateProfileDto { @ApiProperty({ type: CreateAddressDto, required: false }) address?: CreateAddressDto; // Uses CreateScoreDto because of @DtoTypeFullUpdate @ApiProperty({ type: CreateScoreDto, required: false }) score?: CreateScoreDto; } ``` -------------------------------- ### Overriding TypeScript Types with @DtoOverrideType Source: https://context7.com/brakebein/prisma-generator-nestjs-dto/llms.txt Use `@DtoOverrideType` in the Prisma schema to specify a custom TypeScript type and its import path for a JSON field. This allows for complex types beyond basic primitives. ```prisma model Event { id String @id @default(uuid()) /// @DtoOverrideType(DurationLike, luxon) // Generates: duration: DurationLike + import { DurationLike } from 'luxon' duration Json /// @DtoOverrideType(AddressDto, ../common/address.dto) // Generates: address: AddressDto + import { AddressDto } from '../common/address.dto' address Json? /// @DtoOverrideType(Config, ../config, default) // Generates: config: Config + import Config from '../config' config Json /// @DtoOverrideApiPropertyType(AddressSchema, ../common/address.schema) // Like DtoOverrideType but only affects @ApiProperty({ type: () => AddressSchema }) metadata Json? } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.