Conversation
WalkthroughAdds Swagger/OpenAPI support to the NestJS template: dependency, env/config entries, conditional initialization in bootstrap, many Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
template/nestJs/src/user/dto/update-pwd-user.dto.ts (1)
26-32: Fix validation logic contradiction.The
oldPasswordfield is marked as optional (oldPassword?: string) but decorated with@IsNotEmpty, which will fail validation when the field is undefined. Either remove the?to make it required, or remove/adjust the@IsNotEmptyvalidation.Apply one of these fixes:
Option 1: Make the field required
- oldPassword?: string; + oldPassword: string;Option 2: Make validation conditional (if the field is optional by design)
@ApiProperty({ description: '老密码' }) + @IsOptional() @IsNotEmpty({ message: i18nValidationMessage<I18nTranslations>('validation.NOT_EMPTY'), }) oldPassword?: string;template/nestJs/src/menu/menu.controller.ts (1)
60-72: Add ParseIntPipe for numeric query parameters.The
@Query()decorator returns strings by default, butidandparentIdare typed asnumber. This type mismatch will cause runtime issues when the service expects numeric values for database operations or comparisons.Apply this diff to properly parse the query parameters:
@ApiOperation({summary: '删除菜单'}) @ApiQuery({name: 'id', description: '菜单id'}) @ApiQuery({name: 'parentId', description: '菜单父级ID'}) @ApiOkResponse({type: Menu}) @Reject() @Delete() @Permission('menu::remove') async deleteMenu( - @Query('id') id: number, - @Query('parentId') parentId: number + @Query('id', ParseIntPipe) id: number, + @Query('parentId', ParseIntPipe) parentId: number ) { return this.menuService.deleteMenu(id, parentId); }Note: You'll need to import
ParseIntPipefrom@nestjs/common(it's already available in the imports on line 2).
🧹 Nitpick comments (16)
template/nestJs/src/user/dto/create-user.dto.ts (1)
34-51: Enhance API documentation for optional fields.Eight optional fields use empty
@ApiProperty({})decorators, while the required fields above have descriptive metadata. This inconsistency reduces the value of the generated Swagger documentation.Consider adding:
- Descriptions for each field (similar to lines 7-9, 15-17, 23-25, 30-32)
formatmetadata for date fields (probationStart, probationEnd, protocolStart, protocolEnd)enumorexamplefor the status fieldtypeandisArrayfor better clarity on the roleIds arrayExample enhancement:
- @ApiProperty({}) + @ApiProperty({ + description: '部门', + required: false + }) department?: string; - @ApiProperty({}) + @ApiProperty({ + description: '试用期开始日期', + required: false, + format: 'date' + }) probationStart?: string; - @ApiProperty({}) + @ApiProperty({ + description: '用户状态', + required: false, + example: 1 + }) status?: number;template/nestJs/src/application/dto/pagination-query.dto.ts (2)
7-12:pagefield Swagger metadata matches validation constraints
minimum: 1in Swagger is consistent with@Min(1)and the default value; this will render a clear optionalpageparameter in the docs. Consider addingdefault: 1to the decorator if you want Swagger UI to show the default explicitly.
14-20:limitconstraints are consistently documented and validatedSwagger
minimum/maximumvalues align with@Min(1)/@Max(100), so the docs correctly reflect allowed page sizes. You might also adddefault: 1(and possibly anexample) in the decorator to improve generated API docs.template/nestJs/.env.example (1)
22-24: Align SWAGGER_ env formatting with existing style (optional).*
SWAGGER_TITLE/DESC/VERSIONcurrently use double quotes and no spaces around=, whereas the rest of the file uses single quotes andKEY = 'value'. For consistency and easier linting, consider matching the existing style, and (ifENABLE_SWAGGERis the main toggle inmain.ts) optionally add a commented example here so template users can discover it.template/nestJs/libs/models/src/application.ts (1)
14-43: Clarifyclassifydocs and consider wiringtagto TagEnum.
- The
// TODO: 没理解这是什么beforeclassifysuggests the field’s meaning is still unclear. Since this PR is documentation-focused, it’d be good either to (a) add a meaningful description to@ApiProperty()forclassify, or (b) move the TODO into an issue tracker and drop the inline comment before merging.- You already have
TagEnumdefined; consider tighteningtagto use it (e.g.,tag: TagEnum) and exposing it via@ApiProperty({ description: '应用Tag', enum: TagEnum })so allowed values are explicit in Swagger.template/nestJs/src/user/dto/update-user.dto.ts (1)
8-47: Verify new password fields usage and align optional flags with TypeScript types.
- Adding
oldPassword/newPasswordtoUpdateUserDtowill expose these on any endpoint using this DTO (likely general user/admin update). Please double‑check that the service layer handles them securely and that this doesn’t conflict with the existing password‑specific DTOs (update-pwd-user,update-pwd-admin), e.g., to avoid having multiple inconsistent ways to change a password.- Fields like
department,employeeType,probationStart/End/Duration,protocolStart/End,address,statusare decorated with@ApiPropertyOptional()but are declared without a?in the type. Runtime behavior is still “optional” (noIsNotEmpty), but for consistency between TS types and Swagger schema it would be cleaner to either mark these as optional (field?: type) or rely onPartialType(CreateUserDto)instead of redeclaring them.template/nestJs/src/role/dto/update-role.dto.ts (1)
5-5: Consider adding a description to the ApiProperty decorator.The
idfield's@ApiProperty()decorator lacks a description, while other fields inCreateRoleDtoinclude descriptive metadata (e.g.,description: '角色名'). Adding a description here improves API documentation clarity.Apply this diff to add a description:
- @ApiProperty() + @ApiProperty({ + description: '角色ID' + }) id: number;template/nestJs/src/health-check.controller.ts (1)
7-11: Consider using String class instead of string literal for type.For consistency with NestJS/Swagger conventions, consider using the
Stringclass constructor instead of the string literal'string'.Apply this diff:
@ApiOkResponse({ - type: 'string', + type: String, description: '确保健康检查能通过:`curl -k 127.0.0.1:3000/healthCheck` 获取到内容,而不是 404', example: 'success' })template/nestJs/src/user/dto/batch-remove-user.dto.ts (1)
3-9: Consider adding validation decorators.The
emailsfield would benefit from validation decorators to ensure data integrity before reaching the service layer.Apply this diff:
import { ApiProperty } from "@nestjs/swagger"; +import { IsArray, IsNotEmpty } from "class-validator"; export class BatchRemoveUserDto { @ApiProperty({ type: [String], description: '要删除的email集合' }) + @IsArray() + @IsNotEmpty() emails: string[]; }template/nestJs/src/i18/dto/batch-remove-i18.dto.ts (1)
3-9: Consider adding validation decorators.The
idsfield would benefit from validation decorators to ensure data integrity, consistent with validation patterns used elsewhere in the codebase.Apply this diff:
import { ApiProperty } from "@nestjs/swagger"; +import { IsArray, IsNotEmpty } from "class-validator"; export class BatchRemoveI18Records { @ApiProperty({ description: '想要删除的国际化字段ID数组', type: [Number] }) + @IsArray() + @IsNotEmpty() ids: number[]; }template/nestJs/src/main.ts (1)
95-97: Consider explicit boolean check for ENABLE_SWAGGER.While the current implementation works (undefined is falsy), explicitly checking for
=== truewould make the intent clearer and protect against potential configuration issues where the value might be undefined.Apply this diff for more explicit configuration checking:
- if (cfg.get('ENABLE_SWAGGER')) { + if (cfg.get('ENABLE_SWAGGER') === true) { prepareSwagger(cfg, app); }template/nestJs/src/permission/permission.controller.ts (1)
39-45: Add ApiOkResponse decorator for consistency.The update endpoint has an ApiOperation but is missing an ApiOkResponse decorator to document the successful response type, unlike other endpoints in this controller.
Apply this diff to add the response documentation:
@ApiOperation({summary: '修改一个权限字段'}) + @ApiOkResponse({ + description: '更新后的数据库记录', + type: PermissionEntity + }) @Reject() @Patch() @Permission('permission::update')template/nestJs/src/menu/entity/tree-node.entity.ts (1)
1-47: Well-structured tree node DTO with one minor suggestion.The TreeNode class is properly implemented with comprehensive ApiProperty decorators. The recursive type reference for
children(line 16) correctly handles the tree structure.One minor observation: the description for
parentIdat line 36 ('节点') is less descriptive compared to other fields. Consider using '父节点ID' or '父级菜单ID' for clarity.Optional improvement for parentId description:
@ApiProperty({ - description: '节点' + description: '父节点ID' }) parentId: number;template/nestJs/src/i18/i18.controller.ts (1)
126-135: Consider destructuring the parameter directly.The batch removal endpoint correctly updates to use a typed DTO. For cleaner code, you could destructure the
idsproperty directly in the parameter declaration, similar to the pattern used intemplate/nestJs/src/user/user.controller.ts.Apply this diff for more concise code:
- batchRemove(@Body() body: BatchRemoveI18Records) { - return this.i18Service.batchRemove(body.ids); + batchRemove(@Body() { ids }: BatchRemoveI18Records) { + return this.i18Service.batchRemove(ids);template/nestJs/src/user/user.controller.ts (1)
26-26: Remove unused import:ApiProperty.The
ApiPropertydecorator is imported but not used in this controller file. It's typically used in DTOs and entity classes, not controllers.Apply this diff:
-import { ApiBearerAuth, ApiCreatedResponse, ApiOkResponse, ApiOperation, ApiParam, ApiProperty } from '@nestjs/swagger'; +import { ApiBearerAuth, ApiCreatedResponse, ApiOkResponse, ApiOperation, ApiParam } from '@nestjs/swagger';template/nestJs/src/public/api-paginated-response.ts (1)
42-52: Add@ApiPropertydecorator to theitemsfield for consistency.The
itemsfield lacks an@ApiPropertydecorator, whilemetaandlinksare properly decorated. Although theApiPaginatedResponsedecorator factory handles the schema generation, maintaining consistent decoration improves code clarity and maintainability.Apply this diff:
export class Pagination<T> { + @ApiProperty() items: T[]; @ApiProperty({ type: PaginationMeta })
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (44)
template/nestJs/.env.example(1 hunks)template/nestJs/libs/models/src/application.ts(2 hunks)template/nestJs/libs/models/src/i18n.ts(1 hunks)template/nestJs/libs/models/src/lang.ts(1 hunks)template/nestJs/libs/models/src/menu.ts(1 hunks)template/nestJs/libs/models/src/permission.ts(1 hunks)template/nestJs/libs/models/src/role.ts(1 hunks)template/nestJs/libs/models/src/user.ts(1 hunks)template/nestJs/nest-cli.json(1 hunks)template/nestJs/package.json(1 hunks)template/nestJs/src/application/application.controller.ts(1 hunks)template/nestJs/src/application/dto/pagination-query.dto.ts(1 hunks)template/nestJs/src/application/entites/find-application.entity.ts(1 hunks)template/nestJs/src/config-schema.ts(2 hunks)template/nestJs/src/health-check.controller.ts(1 hunks)template/nestJs/src/i18/dto/batch-remove-i18.dto.ts(1 hunks)template/nestJs/src/i18/dto/create-i18.dto.ts(1 hunks)template/nestJs/src/i18/dto/create-lang.dto.ts(1 hunks)template/nestJs/src/i18/dto/update-i18.dto.ts(1 hunks)template/nestJs/src/i18/entites/find-all-i18n.entity.ts(1 hunks)template/nestJs/src/i18/i18.controller.ts(3 hunks)template/nestJs/src/i18/lang.controller.ts(2 hunks)template/nestJs/src/main.ts(3 hunks)template/nestJs/src/menu/dto/create-menu.dto.ts(1 hunks)template/nestJs/src/menu/dto/update-menu.dto.ts(1 hunks)template/nestJs/src/menu/entity/tree-node.entity.ts(1 hunks)template/nestJs/src/menu/menu.controller.ts(1 hunks)template/nestJs/src/permission/dto/create-permission.dto.ts(1 hunks)template/nestJs/src/permission/dto/update-permission.dto.ts(1 hunks)template/nestJs/src/permission/entity/get-all-permission.entry.ts(1 hunks)template/nestJs/src/permission/permission.controller.ts(2 hunks)template/nestJs/src/public/api-paginated-response.ts(1 hunks)template/nestJs/src/public/menu-tree.ts(1 hunks)template/nestJs/src/role/dto/create-role.dto.ts(1 hunks)template/nestJs/src/role/dto/update-role.dto.ts(1 hunks)template/nestJs/src/role/entities/get-all-role-detail.entity.ts(1 hunks)template/nestJs/src/role/role.controller.ts(2 hunks)template/nestJs/src/user/dto/batch-remove-user.dto.ts(1 hunks)template/nestJs/src/user/dto/create-user.dto.ts(1 hunks)template/nestJs/src/user/dto/pagination-query.dto.ts(1 hunks)template/nestJs/src/user/dto/update-pwd-admin.dto.ts(1 hunks)template/nestJs/src/user/dto/update-pwd-user.dto.ts(1 hunks)template/nestJs/src/user/dto/update-user.dto.ts(1 hunks)template/nestJs/src/user/user.controller.ts(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (24)
template/nestJs/src/application/application.controller.ts (1)
template/nestJs/src/application/entites/find-application.entity.ts (1)
FindApplicationEntity(25-34)
template/nestJs/src/permission/dto/create-permission.dto.ts (1)
template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/libs/models/src/role.ts (2)
template/nestJs/libs/models/src/menu.ts (1)
Entity(4-59)template/nestJs/libs/models/src/permission.ts (1)
Entity(4-22)
template/nestJs/libs/models/src/i18n.ts (2)
template/nestJs/libs/models/src/lang.ts (1)
Entity(5-24)template/tinyvue/src/api/lang.ts (1)
Lang(3-6)
template/nestJs/src/i18/lang.controller.ts (3)
template/tinyvue/src/api/lang.ts (1)
Lang(3-6)template/tinyvue/src/api/permission.ts (1)
Permission(3-7)template/nestJs/src/i18/dto/create-lang.dto.ts (1)
CreateLang(6-14)
template/nestJs/src/permission/permission.controller.ts (4)
template/tinyvue/src/api/permission.ts (1)
Permission(3-7)template/nestJs/src/permission/dto/create-permission.dto.ts (1)
CreatePermissionDto(6-22)template/nestJs/src/permission/dto/update-permission.dto.ts (1)
UpdatePermissionDto(7-15)template/nestJs/src/permission/entity/get-all-permission.entry.ts (1)
GetAllPermission(5-18)
template/nestJs/src/role/role.controller.ts (4)
template/tinyvue/src/api/permission.ts (1)
Permission(3-7)template/nestJs/src/role/dto/create-role.dto.ts (1)
CreateRoleDto(4-24)template/nestJs/src/role/entities/get-all-role-detail.entity.ts (1)
GetAllRoleDetail(40-50)template/nestJs/src/role/dto/update-role.dto.ts (1)
UpdateRoleDto(4-7)
template/nestJs/src/main.ts (1)
template/nestJs/src/config-schema.ts (1)
Configure(3-85)
template/nestJs/src/i18/i18.controller.ts (4)
template/tinyvue/src/api/permission.ts (1)
Permission(3-7)template/nestJs/src/i18/dto/create-i18.dto.ts (1)
CreateI18Dto(6-22)template/nestJs/src/i18/entites/find-all-i18n.entity.ts (1)
FindAllI18n(25-38)template/nestJs/src/i18/dto/batch-remove-i18.dto.ts (1)
BatchRemoveI18Records(3-9)
template/nestJs/src/user/dto/create-user.dto.ts (1)
template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/libs/models/src/permission.ts (2)
template/nestJs/libs/models/src/role.ts (1)
Entity(12-42)template/tinyvue/src/api/permission.ts (1)
Permission(3-7)
template/nestJs/src/user/dto/update-pwd-admin.dto.ts (2)
template/nestJs/src/user/dto/create-user.dto.ts (1)
CreateUserDto(6-52)template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/src/i18/dto/create-i18.dto.ts (1)
template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/src/i18/entites/find-all-i18n.entity.ts (2)
template/tinyvue/src/api/lang.ts (1)
Lang(3-6)template/nestJs/src/public/api-paginated-response.ts (2)
PaginationMeta(4-21)PaginationLinks(23-40)
template/nestJs/libs/models/src/lang.ts (2)
template/nestJs/libs/models/src/i18n.ts (1)
Entity(5-33)template/tinyvue/src/api/lang.ts (1)
Lang(3-6)
template/nestJs/src/role/dto/update-role.dto.ts (1)
template/nestJs/src/role/dto/create-role.dto.ts (1)
CreateRoleDto(4-24)
template/nestJs/src/menu/dto/update-menu.dto.ts (1)
template/nestJs/src/menu/dto/create-menu.dto.ts (1)
CreateMenuDto(6-62)
template/nestJs/src/permission/dto/update-permission.dto.ts (1)
template/nestJs/src/permission/dto/create-permission.dto.ts (1)
CreatePermissionDto(6-22)
template/nestJs/libs/models/src/menu.ts (6)
template/nestJs/libs/models/src/lang.ts (1)
Entity(5-24)template/nestJs/libs/models/src/application.ts (1)
Entity(12-44)template/nestJs/libs/models/src/i18n.ts (1)
Entity(5-33)template/nestJs/libs/models/src/permission.ts (1)
Entity(4-22)template/nestJs/libs/models/src/role.ts (1)
Entity(12-42)template/nestJs/libs/models/src/user.ts (1)
Entity(20-83)
template/nestJs/src/user/dto/update-pwd-user.dto.ts (2)
template/nestJs/src/user/dto/create-user.dto.ts (1)
CreateUserDto(6-52)template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/libs/models/src/user.ts (6)
template/nestJs/libs/models/src/lang.ts (1)
Entity(5-24)template/nestJs/libs/models/src/application.ts (1)
Entity(12-44)template/nestJs/libs/models/src/i18n.ts (1)
Entity(5-33)template/nestJs/libs/models/src/menu.ts (1)
Entity(4-59)template/nestJs/libs/models/src/permission.ts (1)
Entity(4-22)template/nestJs/libs/models/src/role.ts (1)
Entity(12-42)
template/nestJs/src/user/dto/update-user.dto.ts (2)
template/nestJs/src/user/dto/create-user.dto.ts (1)
CreateUserDto(6-52)template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/src/menu/dto/create-menu.dto.ts (1)
template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/src/user/user.controller.ts (5)
template/nestJs/src/user/dto/create-user.dto.ts (1)
CreateUserDto(6-52)template/nestJs/src/user/dto/update-user.dto.ts (1)
UpdateUserDto(8-52)template/nestJs/src/user/dto/update-pwd-admin.dto.ts (1)
UpdatePwdAdminDto(8-25)template/nestJs/src/user/dto/update-pwd-user.dto.ts (1)
UpdatePwdUserDto(8-33)template/nestJs/src/user/dto/batch-remove-user.dto.ts (1)
BatchRemoveUserDto(3-9)
🪛 dotenv-linter (4.0.0)
template/nestJs/.env.example
[warning] 23-23: [QuoteCharacter] The value has quote characters (', ")
(QuoteCharacter)
[warning] 23-23: [UnorderedKey] The SWAGGER_DESC key should go before the SWAGGER_TITLE key
(UnorderedKey)
[warning] 24-24: [QuoteCharacter] The value has quote characters (', ")
(QuoteCharacter)
🔇 Additional comments (41)
template/nestJs/nest-cli.json (1)
44-44: Trailing newline addition—LGTM.The addition of a trailing newline at the end of the file is a minor, non-functional improvement. The JSON structure and configuration remain unchanged and valid.
template/nestJs/src/application/dto/pagination-query.dto.ts (3)
1-1: Swagger import wiring looks correctImporting
ApiPropertyOptionalfrom@nestjs/swaggeraligns with the new DTO annotations and keeps Swagger typing explicit.
22-24: Optionalclassifyfield is correctly exposed to SwaggerUsing
@ApiPropertyOptionaltogether with@IsOptional()cleanly documents this query filter without changing behavior.
26-28:keywordsquery parameter is consistently documentedSwagger and validation setup for
keywordsmatches the pattern used forclassify, keeping pagination filters uniformly described.template/nestJs/package.json (1)
23-55: Swagger dependency addition appears consistent; just confirm Nest 10 compatibility.
@nestjs/swaggeris pinned to8.1.1, matching the existing pattern of exact versions for NestJS core packages. As long as it’s confirmed compatible with@nestjs/core10.0.3 via your test suite and/or docs, this addition looks good.template/nestJs/libs/models/src/permission.ts (1)
1-21: Permission entity Swagger metadata LGTM.The ApiProperty descriptions on
id,desc, andnameare clear and line up with the front-endPermissionshape; no behavioral changes, just better docs.template/nestJs/src/role/dto/create-role.dto.ts (1)
1-23: CreateRoleDto Swagger docs align with existing validation.
nameis required and documented, and bothpermissionIdsandmenuIdsare arrays of numeric IDs withtype: [Number]plus@IsArray()/@IsNotEmpty(), so the generated OpenAPI schema should accurately reflect how the DTO is validated.template/nestJs/src/permission/dto/create-permission.dto.ts (1)
4-21: CreatePermissionDto Swagger docs look consistent with validation.The ApiProperty descriptions for
name(usage key) anddesc(human‑readable short description) line up well with the existingIsNotEmptyconstraints; this cleanly documents how permissions should be modeled without affecting behavior.template/nestJs/src/user/dto/update-pwd-admin.dto.ts (1)
6-24: LGTM!The Swagger decorators are properly applied with clear descriptions, and the use of
ApiPropertyOptionalfor the optionalconfirmNewPasswordfield is appropriate.template/nestJs/src/config-schema.ts (1)
69-110: LGTM!The Swagger configuration fields are well-structured with appropriate JSDoc comments, sensible defaults, and proper Joi validation schema.
template/nestJs/libs/models/src/menu.ts (1)
1-59: LGTM!The ApiProperty decorators are consistently applied to all Menu entity fields with clear descriptions, and the metadata correctly reflects the database schema (e.g.,
nullable: trueforparentId).template/nestJs/src/application/application.controller.ts (1)
4-14: LGTM!The Swagger decorators properly document the endpoint with a clear operation summary and the correct response type.
template/nestJs/src/public/menu-tree.ts (1)
1-25: LGTM!The
MenuTreeNodeclass is well-structured with comprehensive ApiProperty decorators for all fields. The circular reference for thechildrenproperty is properly handled withtype: [MenuTreeNode].template/nestJs/src/i18/lang.controller.ts (1)
15-68: Good Swagger documentation coverage.The controller endpoints are well-documented with appropriate decorators, including operation summaries, response types, and parameter descriptions.
template/nestJs/libs/models/src/role.ts (1)
10-41: LGTM! Swagger metadata properly applied.The
@ApiPropertydecorators are correctly applied to all public fields with appropriate descriptions and type annotations for relations.template/nestJs/src/i18/dto/update-i18.dto.ts (1)
1-1: Good practice: using PartialType from @nestjs/swagger.Switching from
@nestjs/mapped-typesto@nestjs/swaggerforPartialTypeis the recommended approach, as it properly maintains Swagger metadata for the partial DTO.template/nestJs/src/role/role.controller.ts (1)
18-121: Excellent Swagger documentation coverage.All endpoints are properly documented with
@ApiOperation, response types, query parameters, and path parameters. This provides comprehensive API documentation.template/nestJs/libs/models/src/lang.ts (1)
3-23: LGTM! Swagger metadata properly applied.The
@ApiPropertydecorators are correctly applied to all public fields with appropriate descriptions. The type function for the relation field is properly formatted.template/nestJs/src/i18/dto/create-lang.dto.ts (1)
4-9: LGTM! Swagger metadata added correctly.The ApiProperty decorator is properly applied to document the
namefield for Swagger/OpenAPI generation.template/nestJs/src/i18/dto/create-i18.dto.ts (1)
4-21: LGTM! Swagger metadata properly applied.All DTO fields are correctly annotated with ApiProperty decorators and appropriate descriptions for API documentation.
template/nestJs/libs/models/src/i18n.ts (1)
3-32: LGTM! Entity documentation correctly implemented.The ApiProperty decorators are properly applied to all entity fields with appropriate descriptions. The use of arrow function syntax
type: ()=>Langfor the relationship field correctly handles potential circular dependencies.template/nestJs/src/permission/permission.controller.ts (3)
26-36: LGTM! Create endpoint properly documented.The create endpoint has appropriate Swagger annotations with operation summary and response type.
47-60: LGTM! Find endpoint comprehensively documented.All query parameters and response types are properly documented with appropriate Swagger decorators.
62-70: LGTM! Delete endpoint properly documented.The delete endpoint has complete Swagger annotations including operation summary, parameter documentation, and response type.
template/nestJs/src/permission/entity/get-all-permission.entry.ts (1)
1-18: LGTM! Paginated response DTO correctly structured.The GetAllPermission class properly defines a paginated response envelope with correct ApiProperty decorators for Swagger documentation. The structure follows standard pagination patterns with items, metadata, and links.
template/nestJs/src/menu/dto/update-menu.dto.ts (2)
6-6: Good choice using PartialType from @nestjs/swagger.Importing
PartialTypefrom@nestjs/swaggerinstead of@nestjs/mapped-typesensures that Swagger metadata is properly inherited from the base DTO, which is the recommended approach when using Swagger documentation.
9-13: LGTM! ID field properly added for updates.The addition of the
idfield with appropriate validation and Swagger documentation is correct for an update DTO.template/nestJs/src/permission/dto/update-permission.dto.ts (1)
5-14: LGTM! Swagger metadata properly added.The import change from
@nestjs/mapped-typesto@nestjs/swaggerforPartialTypeis correct for Swagger integration, and theApiPropertydecorator appropriately documents theidfield for API documentation.template/nestJs/src/i18/i18.controller.ts (1)
20-23: LGTM! Comprehensive Swagger integration.The new imports support the Swagger documentation enhancements throughout the controller, including proper type definitions for responses and request bodies.
template/nestJs/src/role/entities/get-all-role-detail.entity.ts (1)
40-50: LGTM! GetAllRoleDetail structure is correct.The class properly combines role information with menu tree data, and both fields are appropriately typed and documented with Swagger decorators.
template/nestJs/src/application/entites/find-application.entity.ts (1)
25-34: LGTM! FindApplicationEntity structure is correct.The response entity properly defines the data array and total count with appropriate Swagger documentation.
template/nestJs/src/user/user.controller.ts (2)
34-45: LGTM! Swagger documentation properly added.The register endpoint is well-documented with operation summary, response type, and bearer authentication requirement.
126-137: LGTM! Clean batch removal implementation.The batch removal endpoint correctly uses a typed DTO with parameter destructuring, providing both type safety and clean code. This is an exemplary pattern for similar batch operations.
template/nestJs/src/menu/dto/create-menu.dto.ts (1)
4-61: LGTM! Comprehensive Swagger documentation added.All DTO fields are properly documented with
ApiPropertydecorators, including appropriate metadata like descriptions and nullable flags. TheparentIdfield correctly specifiesnullable: true.template/nestJs/src/public/api-paginated-response.ts (1)
55-78: LGTM! Well-designed pagination decorator factory.The
ApiPaginatedResponsedecorator correctly composes Swagger metadata for paginated responses using schema composition withallOf. This enables proper type-safe documentation for generic paginated endpoints.template/nestJs/libs/models/src/user.ts (1)
15-67: LGTM! User entity properly documented for Swagger.All entity fields are appropriately decorated with
@ApiProperty, including proper handling of nullable fields and the relation to the Role entity. The metadata additions don't affect the entity's runtime behavior.template/nestJs/src/menu/menu.controller.ts (5)
16-18: LGTM!The Swagger decorator imports are appropriate for the API documentation added to the endpoints.
33-39: LGTM!The endpoint is properly documented and protected with the
@Permissionguard.
42-49: LGTM!The endpoint is properly documented with
ApiCreatedResponsefor the creation operation and protected with appropriate guards.
51-58: Verify the Boolean return type matches MenuService.updateMenu implementation.The endpoint is properly documented and protected. However, returning
Booleanfor an update operation is unconventional—typically REST APIs return the updated entity or a structured response. Confirm that the@ApiOkResponse({type: Boolean})declaration aligns with whatthis.menuService.updateMenu(dto)actually returns.
24-30: Add authentication guard and email validation to prevent unauthorized access.This endpoint lacks an authentication/authorization guard (no
@Permissiondecorator visible), which could allow unauthorized access to any user's role-based menu tree by providing an email address. Additionally, the email parameter lacks format validation.Apply the missing security controls and input validation before merging.
| /** | ||
| * JWT secrect | ||
| */ |
There was a problem hiding this comment.
Fix typo in comment.
"secrect" should be "secret".
Apply this diff:
/**
- * JWT secrect
+ * JWT secret
*/📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * JWT secrect | |
| */ | |
| /** | |
| * JWT secret | |
| */ |
🤖 Prompt for AI Agents
In template/nestJs/src/config-schema.ts around lines 30 to 32, the JSDoc comment
contains a typo "JWT secrect"; update the comment to read "JWT secret" so the
spelling is correct and descriptive.
| /** | ||
| * 数据库 端口 | ||
| */ |
There was a problem hiding this comment.
Fix incorrect comment.
The comment says "数据库 端口" (database port) but this field is REDIS_PORT, so it should say "Redis 端口" (Redis port).
Apply this diff:
/**
- * 数据库 端口
+ * Redis 端口
*/📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /** | |
| * 数据库 端口 | |
| */ | |
| /** | |
| * Redis 端口 | |
| */ |
🤖 Prompt for AI Agents
In template/nestJs/src/config-schema.ts around lines 42 to 44, the JSDoc/comment
incorrectly labels the field as "数据库 端口" (database port) while the constant is
REDIS_PORT; update the comment text to "Redis 端口" (Redis port) to accurately
reflect the field purpose and maintain consistency with other Redis-related
comments.
| return this.langService.update(id, data); | ||
| } | ||
|
|
||
| @ApiOperation({summary: '修改某个的语言'}) |
There was a problem hiding this comment.
Fix incorrect API operation summary.
The summary says "修改某个的语言" (update language), but this is a DELETE endpoint. It should say "删除某个的语言" (delete language).
Apply this diff:
- @ApiOperation({summary: '修改某个的语言'})
+ @ApiOperation({summary: '删除某个的语言'})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @ApiOperation({summary: '修改某个的语言'}) | |
| @ApiOperation({summary: '删除某个的语言'}) |
🤖 Prompt for AI Agents
In template/nestJs/src/i18/lang.controller.ts around line 56, the @ApiOperation
summary is incorrect for a DELETE endpoint; update the Chinese summary string
from "修改某个的语言" to "删除某个的语言" so the annotation correctly reflects the operation.
| function prepareSwagger(cfg: ConfigService<Configure>,app: INestApplication<any>){ | ||
| const swaggerConfig = new DocumentBuilder() | ||
| .setTitle(cfg.get('SWAGGER_TITLE')) | ||
| .setDescription(cfg.get('SWAGGER_DESC')) | ||
| .setVersion(cfg.get('SWAGGER_VERSION')) | ||
| .build(); | ||
| const documentFactory = () => SwaggerModule.createDocument(app, swaggerConfig); | ||
| SwaggerModule.setup('api', app, documentFactory) | ||
| } |
There was a problem hiding this comment.
Add validation for required Swagger configuration values.
The function doesn't validate that SWAGGER_TITLE, SWAGGER_DESC, and SWAGGER_VERSION are defined before use. If these environment variables are missing, the Swagger UI will display "undefined" for these fields.
Consider adding validation:
function prepareSwagger(cfg: ConfigService<Configure>,app: INestApplication<any>){
+ const title = cfg.get('SWAGGER_TITLE');
+ const description = cfg.get('SWAGGER_DESC');
+ const version = cfg.get('SWAGGER_VERSION');
+
+ if (!title || !description || !version) {
+ console.warn('Swagger configuration incomplete. Some values may display as undefined.');
+ }
+
const swaggerConfig = new DocumentBuilder()
- .setTitle(cfg.get('SWAGGER_TITLE'))
- .setDescription(cfg.get('SWAGGER_DESC'))
- .setVersion(cfg.get('SWAGGER_VERSION'))
+ .setTitle(title || 'API Documentation')
+ .setDescription(description || 'API Description')
+ .setVersion(version || '1.0')
.build();
const documentFactory = () => SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api', app, documentFactory)
}🤖 Prompt for AI Agents
In template/nestJs/src/main.ts around lines 104 to 112, the prepareSwagger
function uses cfg.get('SWAGGER_TITLE'), cfg.get('SWAGGER_DESC'), and
cfg.get('SWAGGER_VERSION') without validating they exist; add a simple
validation step that reads each value, checks for null/undefined/empty string,
and either supply a sensible default or throw a clear error (preferably throw
during startup so missing config fails fast); then pass the validated values to
DocumentBuilder; ensure any thrown error includes which variable is missing to
aid debugging.
| export class RoleInfo { | ||
| @ApiProperty({ | ||
| type: RoleInfoItem | ||
| }) | ||
| items: RoleInfoItem; | ||
| @ApiProperty({ | ||
| type: PaginationMeta | ||
| }) | ||
| meta: PaginationMeta; | ||
| @ApiProperty({ | ||
| type: PaginationLinks | ||
| }) | ||
| links: PaginationLinks; | ||
| } |
There was a problem hiding this comment.
Fix type error: items should be an array.
The items field is typed as a singular RoleInfoItem but should be an array type RoleInfoItem[]. This is evident from:
- The plural field name "items"
- The pagination context (similar to
FindAllI18n.items: FindAllI18nItem[]) - Expected API response structure for listing operations
Apply this diff to fix the type:
export class RoleInfo {
@ApiProperty({
type: RoleInfoItem
})
- items: RoleInfoItem;
+ items: RoleInfoItem[];
@ApiProperty({
type: PaginationMeta
})
meta: PaginationMeta;Note: You may also need to update the @ApiProperty decorator:
@ApiProperty({
- type: RoleInfoItem
+ type: [RoleInfoItem]
})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export class RoleInfo { | |
| @ApiProperty({ | |
| type: RoleInfoItem | |
| }) | |
| items: RoleInfoItem; | |
| @ApiProperty({ | |
| type: PaginationMeta | |
| }) | |
| meta: PaginationMeta; | |
| @ApiProperty({ | |
| type: PaginationLinks | |
| }) | |
| links: PaginationLinks; | |
| } | |
| export class RoleInfo { | |
| @ApiProperty({ | |
| type: [RoleInfoItem] | |
| }) | |
| items: RoleInfoItem[]; | |
| @ApiProperty({ | |
| type: PaginationMeta | |
| }) | |
| meta: PaginationMeta; | |
| @ApiProperty({ | |
| type: PaginationLinks | |
| }) | |
| links: PaginationLinks; | |
| } |
🤖 Prompt for AI Agents
In template/nestJs/src/role/entities/get-all-role-detail.entity.ts around lines
25 to 38, the items field is incorrectly typed as a singular RoleInfoItem;
change its TypeScript type to RoleInfoItem[] and update the @ApiProperty
decorator to indicate an array (e.g., set type: RoleInfoItem and isArray: true)
so the property and OpenAPI metadata reflect an array of items; keep meta and
links as-is.
| import { ApiProperty } from '@nestjs/swagger'; | ||
| export class PaginationQueryDto { | ||
| @ApiProperty({ | ||
| description: '页数', | ||
| default: 'process.env.PAGITION_PAGE', | ||
| type: Number | ||
| }) | ||
| @IsOptional() | ||
| @Transform(value => isNaN(Number(value)) ? 1 : Number(value)) | ||
| page?: number = Number(process.env.PAGITION_PAGE); | ||
|
|
||
| @ApiProperty({ | ||
| description: '每页的大小', | ||
| default: 'process.env.PAGITION_PAGE', | ||
| type: Number | ||
| }) | ||
| @IsOptional() | ||
| @Transform(value => isNaN(Number(value)) ? 10 : Number(value)) | ||
| limit?: number = Number(process.env.PAGITION_PAGE); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
find . -name ".env*" -o -name "package.json" | head -20Repository: opentiny/tiny-pro
Length of output: 178
🏁 Script executed:
rg "PAGITION_PAGE|PAGINATION_PAGE" --type-list | head -5Repository: opentiny/tiny-pro
Length of output: 178
🏁 Script executed:
rg "PAGITION_PAGE|PAGINATION_PAGE" -nRepository: opentiny/tiny-pro
Length of output: 178
🌐 Web query:
class-transformer @Transform decorator API callback parameter class-transformer 0.5
💡 Result:
In class-transformer v0.5 the @Transform callback receives a single parameter — an object with these properties:
- value — the raw property value before transform.
- key — the property name.
- obj — the source/plain object being transformed.
- type — the transformation type (e.g., "plainToClass", "classToPlain", etc.).
- options — the ClassTransformOptions passed into the transformation (when present).
Example usage:
@Transform(({ value, key, obj, type, options }) => /* ... */ , { toClassOnly: true }). [1][2][3]
Sources: class-transformer docs / README and v0.5 API docs. [1] GitHub README (class-transformer). [2] jsDocs / v0.5.1 docs. [3] npm/js examples.
Fix pagination defaults: env var typo, Swagger default, and Transform callback.
There are three coupled issues:
-
Env var name typo:
Code and SwaggerdefaultusePAGITION_PAGE, but.env.examplelikely definesPAGINATION_PAGE/PAGINATION_LIMIT. This prevents.envsettings from being honored. -
Swagger
defaultis a string literal:
default: 'process.env.PAGITION_PAGE'documents the string itself rather than the numeric default value. Should be a number. -
Transform callback ignores query parameters:
In class-transformer 0.5.x,@Transformreceives{ value, key, obj, ... }, not the raw value. Using@Transform(value => ...)meansvalueis an object, soNumber(value)becomesNaN. TheisNaN(...)check always returns true, picking the fallback (1 / 10) regardless of the query parameter.
Fix with:
import { Transform } from 'class-transformer';
import * as process from "process";
import { ApiProperty } from '@nestjs/swagger';
+
+const DEFAULT_PAGE = Number(process.env.PAGINATION_PAGE ?? 1);
+const DEFAULT_LIMIT = Number(process.env.PAGINATION_LIMIT ?? 10);
+
export class PaginationQueryDto {
@ApiProperty({
description: '页数',
- default: 'process.env.PAGITION_PAGE',
+ default: DEFAULT_PAGE,
type: Number
})
@IsOptional()
- @Transform(value => isNaN(Number(value)) ? 1 : Number(value))
- page?: number = Number(process.env.PAGITION_PAGE);
+ @Transform(({ value }) => {
+ const num = Number(value ?? DEFAULT_PAGE);
+ return Number.isNaN(num) ? DEFAULT_PAGE : num;
+ })
+ page?: number = DEFAULT_PAGE;
@ApiProperty({
description: '每页的大小',
- default: 'process.env.PAGITION_PAGE',
+ default: DEFAULT_LIMIT,
type: Number
})
@IsOptional()
- @Transform(value => isNaN(Number(value)) ? 10 : Number(value))
- limit?: number = Number(process.env.PAGITION_PAGE);
+ @Transform(({ value }) => {
+ const num = Number(value ?? DEFAULT_LIMIT);
+ return Number.isNaN(num) ? DEFAULT_LIMIT : num;
+ })
+ limit?: number = DEFAULT_LIMIT;
}This ensures query parameters are actually respected, Swagger docs show numeric defaults, and .env settings are honored with corrected env var names.
🤖 Prompt for AI Agents
In template/nestJs/src/user/dto/pagination-query.dto.ts around lines 4 to 22,
fix three issues: correct the env var typos to PAGINATION_PAGE and
PAGINATION_LIMIT everywhere, change the ApiProperty default to a numeric value
(use Number(process.env.PAGINATION_PAGE) / Number(process.env.PAGINATION_LIMIT)
or literals) instead of the string literal, and update the Transform callbacks
to accept the transform object (e.g. ({ value }) => isNaN(Number(value)) ?
Number(process.env.PAGINATION_PAGE) || 1 : Number(value)) so query params are
parsed correctly and env defaults are used.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
template/nestJs/src/auth/dto/refresh-token.dto.ts (1)
1-9: Swagger metadata looks correct; consider slightly richer docs text
@ApiPropertyontokenis correctly wired and keeps validation intact. For clearer generated docs, you might expand the description (e.g. “Refresh token used to obtain a new access token”) and/or add anexamplefield.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
template/nestJs/src/auth/auth.controller.ts(2 hunks)template/nestJs/src/auth/dto/create-api-token.dto.ts(1 hunks)template/nestJs/src/auth/dto/create-auth.dto.ts(1 hunks)template/nestJs/src/auth/dto/logout-auth.dto.ts(1 hunks)template/nestJs/src/auth/dto/refresh-token.dto.ts(1 hunks)template/nestJs/src/auth/dto/revoke-api-token.dto.ts(1 hunks)template/nestJs/src/auth/entity/token.ts(2 hunks)
🧰 Additional context used
🧬 Code graph analysis (3)
template/nestJs/src/auth/auth.controller.ts (4)
template/nestJs/src/auth/entity/token.ts (2)
TokenPair(24-41)ApiToken(43-52)template/nestJs/src/auth/dto/create-auth.dto.ts (1)
CreateAuthDto(6-22)template/nestJs/src/auth/dto/logout-auth.dto.ts (1)
LogoutAuthDto(6-19)template/nestJs/src/auth/dto/create-api-token.dto.ts (1)
CreateApiTokenDto(4-23)
template/nestJs/src/auth/dto/create-auth.dto.ts (1)
template/nestJs/src/.generate/i18n.generated.ts (1)
I18nTranslations(7-58)
template/nestJs/src/auth/dto/refresh-token.dto.ts (1)
template/tinyvue/src/api/user.ts (1)
RefreshToken(47-49)
🔇 Additional comments (11)
template/nestJs/src/auth/dto/revoke-api-token.dto.ts (1)
1-15: Swagger metadata matches validators and types
@ApiPropertyis correctly imported and applied totokenIdwith descriptions that align with the existingIsEmail/IsStringvalidators and string types. No behavior change, and the DTO remains consistent and clear for OpenAPI generation. You may just confirm that the description language/style matches the rest of the auth DTOs in this PR for documentation consistency.template/nestJs/src/auth/dto/logout-auth.dto.ts (1)
4-9: LGTM! API documentation added correctly.The ApiProperty decorator provides clear documentation for the token field with no impact on runtime validation.
template/nestJs/src/auth/dto/create-api-token.dto.ts (1)
1-22: LGTM! Comprehensive API documentation.All three fields are properly documented with clear Chinese descriptions, consistent with the validation decorators.
template/nestJs/src/auth/entity/token.ts (1)
24-41: LGTM! TokenPair class well-documented.All fields have clear descriptions explaining the token format and TTL units (milliseconds).
template/nestJs/src/auth/dto/create-auth.dto.ts (1)
1-21: LGTM! Clean API documentation additions.Both email and password fields are properly documented with clear descriptions, and the unused
I18nContextimport has been appropriately removed.template/nestJs/src/auth/auth.controller.ts (6)
10-11: LGTM! Swagger imports added correctly.The imports bring in the necessary decorators and response types for API documentation.
17-30: LGTM! refreshToken endpoint well-documented.The endpoint has comprehensive documentation with both operation details and response type specification.
32-43: LGTM! login endpoint properly documented.The endpoint includes operation summary and correct response type (TokenPair).
45-52: LGTM! logout endpoint documented appropriately.The endpoint has an operation summary. No response type is needed as logout operations typically return simple status responses.
54-66: LGTM! generateApiToken endpoint comprehensively documented.The endpoint includes both operation metadata and the correct response type (ApiToken).
68-76: LGTM! revokeApiToken endpoint properly documented.The endpoint has clear operation documentation describing its purpose.
| export class ApiToken { | ||
| @ApiProperty({}) | ||
| token: string; | ||
| @ApiProperty({}) | ||
| tokenId: string; | ||
| @ApiProperty({ | ||
| description: '有效期' | ||
| }) | ||
| expiresIn: number; | ||
| } |
There was a problem hiding this comment.
Add descriptions to empty ApiProperty decorators.
The token and tokenId fields have empty @ApiProperty({}) decorators that provide no documentation value, while expiresIn has a proper description. For consistency with the rest of the codebase and to make the API documentation useful, add descriptive text.
Apply this diff to add descriptions:
export class ApiToken {
- @ApiProperty({})
+ @ApiProperty({
+ description: 'API令牌'
+ })
token: string;
- @ApiProperty({})
+ @ApiProperty({
+ description: '令牌ID'
+ })
tokenId: string;
@ApiProperty({
description: '有效期'
})
expiresIn: number;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export class ApiToken { | |
| @ApiProperty({}) | |
| token: string; | |
| @ApiProperty({}) | |
| tokenId: string; | |
| @ApiProperty({ | |
| description: '有效期' | |
| }) | |
| expiresIn: number; | |
| } | |
| export class ApiToken { | |
| @ApiProperty({ | |
| description: 'API令牌' | |
| }) | |
| token: string; | |
| @ApiProperty({ | |
| description: '令牌ID' | |
| }) | |
| tokenId: string; | |
| @ApiProperty({ | |
| description: '有效期' | |
| }) | |
| expiresIn: number; | |
| } |
🤖 Prompt for AI Agents
In template/nestJs/src/auth/entity/token.ts around lines 43 to 52 the
ApiProperty decorators for token and tokenId are empty, so update those
decorators to include descriptive text (e.g., description for token:
"authentication token string" and for tokenId: "unique token identifier") and
optionally add an example or format field to improve Swagger docs; keep the
existing expiresIn description intact.
PR
PR Checklist
Please check if your PR fulfills the following requirements:
PR Type
What kind of change does this PR introduce?
What is the current behavior?
Issue Number: N/A
What is the new behavior?
Does this PR introduce a breaking change?
Other information
Summary by CodeRabbit
New Features
Configuration
Dependencies
✏️ Tip: You can customize this high-level summary in your review settings.