Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
Project Development Standards
General Principles
- Type safety with input/output separation: Use DTOs only for request validation and transformation; use VOs only for response encapsulation.
- Clear layer responsibilities: Controller handles routing/parameter binding/response transformation only; Service handles business orchestration and permission filtering; Repository handles data access only, without business logic or permission checks.
- Unified exceptions: Business errors use AppException + ResponseCode; protocol-level errors (for example rate limit/auth transport semantics) may use standard HttpException; global filter ensures unified response format.
Naming & Files
- Classes/Interfaces/Enums use PascalCase; variables/functions use camelCase; constants use UPPER_SNAKE_CASE.
- File suffixes:
*.controller.ts/*.service.ts/*.module.ts/*.dto.ts/*.vo.ts/*.repository.ts. - File names must use kebab-case; camelCase is prohibited:
platform-rules.constants.ts, notplatformRules.config.ts. *.config.tsfiles are only for zod configuration; not allowed for constants, utils, or interfaces.- Do not arbitrarily nest folders like
dto/; create*.dto.tsfiles directly in the module root directory.
Repository Method Naming
- Methods must start with these prefixes:
get/list/create/update/delete/count - Aggregation methods may start with aggregation keywords:
aggregate/sum/avgetc. - Batch operations use
createMany/updateMany/deleteManyformat - Methods returning a single value must start with
get, format:getByXxx - Methods returning arrays must start with
list, format:listByXxx - Methods returning counts must start with
count, format:countByXxx - Pagination methods must end with
WithPagination, e.g.,listWithPagination - Non-standard prefixes are prohibited:
find/del/add/set/checketc. - Business verbs as prefixes are prohibited:
verify/mark/publishetc.
Examples
- ✅
getById/getByUserId/getByIdAndStatus - ✅
listByUserId/listWithPagination/listByStatus - ✅
create/createMany/createByUser - ✅
updateById/updateByStatus/updateManyByIds - ✅
deleteById/deleteByUserId/deleteManyByIds - ✅
countByUserId/countByStatus/aggregateByDate - ❌
findById→getById - ❌
findList→listWithPagination - ❌
delOne→deleteById - ❌
addUseCount→updateUseCountById - ❌
verify→updateVerifyById - ❌
markAsRead→updateAsReadByIds
DTO (Input)
- Write zod schema first, then use
createZodDto(schema, 'IdString')to generate DTO; using entities as input is prohibited. - Pagination input must use
PaginationDtoSchema(page ≥1, pageSize ∈[1,1000], string numbers auto-convert).
import { createZodDto, PaginationDtoSchema } from '@yikart/common';
import { z } from 'zod';
export const CreateOrderDtoSchema = z.object({
productId: z.string(),
quantity: z.number().int().positive().default(1),
returnTo: z.url().optional(),
});
export class CreateOrderDto extends createZodDto(CreateOrderDtoSchema, 'CreateOrderDto') {}
VO (Output)
- VOs expose only stable external fields; mapping is done in Service, Controller outputs using
VoClass.create(data)(regular VO); returning database entities directly is prohibited. - Pagination responses must use
createPaginationVo(pagination VO instantiation usesnew), with fields: page, pageSize, totalPages, total, list.
import { createPaginationVo, createZodDto } from '@yikart/common';
import { z } from 'zod';
export const OrderDetailVoSchema = z.object({ id: z.string(), amount: z.number(), createdAt: z.coerce.date() });
export class OrderDetailVo extends createZodDto(OrderDetailVoSchema, 'OrderDetailVo') {}
export class OrderListVo extends createPaginationVo(OrderDetailVoSchema, 'OrderListVo') {}
API Documentation (Swagger)
- Every Controller must have
@ApiTags('Category/Module')decorator for grouping - Every Controller method must have
@ApiDocdecorator for documentation - DTO/VO schema fields must use
.describe('description')for field documentation
Controller Documentation
import { ApiTags } from '@nestjs/swagger'
import { ApiDoc } from '@yikart/common'
@ApiTags('AI/Material-Adaptation')
@Controller('/material-adaptation')
export class MaterialAdaptationController {
@ApiDoc({
summary: '适配素材到多个平台',
description: '使用 AI 将素材内容适配到指定的社交媒体平台',
body: AdaptMaterialDtoSchema,
response: [MaterialAdaptationVo],
})
@Post('/')
async adaptMaterial(...): Promise<MaterialAdaptationVo[]> { ... }
}
DTO/VO Field Documentation
export const CreateOrderDtoSchema = z.object({
productId: z.string().describe('产品 ID'),
quantity: z.number().int().positive().default(1).describe('购买数量'),
returnTo: z.url().optional().describe('回调地址'),
});
export const OrderDetailVoSchema = z.object({
id: z.string().describe('订单 ID'),
amount: z.number().describe('订单金额'),
createdAt: z.coerce.date().describe('创建时间'),
});
ApiDoc Options
summary(required): Brief description of the endpointdescription(optional): Detailed descriptionbody(optional): Request body Zod schema (useXxxDtoSchema, not the class)query(optional): Query parameters Zod schemaresponse(optional): Response VO class or[VoClass]for array response
Exceptions & Error Codes
- Business exceptions use
new AppException(code)ornew AppException(code, data); messages are generated from code→message mapping, custom overrides are prohibited.
import { AppException, ResponseCode } from '@yikart/common';
throw new AppException(ResponseCode.MaterialGroupNotFound, { groupId: 'group_xxx' });
ResponseCode Standards
- Success code is fixed at
Success = 0; business error codes start from10000and are allocated by module range, cross-module reuse is prohibited. - Naming uses PascalCase and must specify the concrete resource: e.g.,
ContractNotFound,CommentNotFound; generic permission names (Unauthorized/AccessDeniedetc.) are prohibited. - Define and export only in the common package; all services reference the same source to avoid scattered definitions.
- Must maintain code→default message mapping; use "Unknown error" for unmatched codes.
- Collaboration with AppException: pass only
codeorcode+data, custom messages are not allowed (messages are generated from mapping). - Addition workflow: Add constant to
ResponseCode→ Add default message to message mapping → Use in business code.
Permissions & Data Access
- Permissions are filtered through query conditions; prefer specific resource NotFound over generic permission exceptions; permission logic belongs in Service layer.
- Repository only accesses its own data model; cross-model operations, permission checks, and extra existence queries are prohibited (existence checks are done by Service first).
Data Filtering & Aggregation
- All filtering, counting, and aggregation MUST be done at database layer (Repository), not in application code.
- Prohibited: fetching a list from DB then using
.filter()/.some()/.find()/.reduce()to narrow results in memory. - Use Repository methods with proper query conditions instead.
// WRONG — filtering in memory
const records = await this.repo.listByUserId(userId)
const pending = records.filter(r => r.status === 'pending')
const total = pending.reduce((sum, r) => sum + r.amount, 0)
// CORRECT — filtering at database layer
const pending = await this.repo.listByUserIdAndStatus(userId, 'pending')
const total = await this.repo.sumAmountByUserIdAndStatus(userId, 'pending')
- Exception: filtering on external API responses is acceptable since the data is not from our DB.
Logging & Lint
- Using console is prohibited; use dependency-injected Logger instance (e.g.,
this.logger.log()). - Strictly follow ESLint (root
eslint.config.mjs); must passpnpm lint -wand type checking before commit.
Mandatory Rules (Hard Requirements)
- Controller handles routing/parameter binding/response transformation only; Service handles business orchestration and permission filtering; Repository handles data access only.
- Controller output must use VOs uniformly (regular VO uses
VoClass.create(data); pagination VO usesnew); Service returns entity data, Controller converts to VO, not the reverse. - Pagination Service methods must return
[list, total]tuple directly from Repository (transparent pass-through);new ListVo()is only called in Controller; field mapping, default value filling, and field renaming are done insidenew ListVo(list.map(...), total, pagination)in Controller; if no mapping is needed, passlistdirectly. - VO schema optional fields must use
.optional();.nullable()is only for fields that can be explicitly set tonullin business logic; DBrequired: false/field?: Typemust map to.optional(), not.nullable(). - DTO/VO must be defined with zod schema and generated using
createZodDto/createPaginationVo. - Pagination: input uses
PaginationDtoSchema; output fields are fixed as page, pageSize, totalPages, total, list. - AppException is constructed only with code or code+data, messages come from mapping; standard HttpException is reserved for protocol-layer errors.
- Permissions are filtered through query conditions; unmatched results are represented as specific resource NotFound; permission logic is in Service layer.
- Prefer soft delete (
deletedAt); state transitions are handled in Service layer; avoid complex state enums. - Statistics/counts are implemented at database layer, application-layer iteration aggregation is prohibited.
- HTTP decorator paths must start with
/, empty parameters are prohibited; methods with pagination must end withWithPagination. - Every Controller must have
@ApiTagsdecorator; every Controller method must have@ApiDocdecorator. - All DTO/VO schema fields must have
.describe()for API documentation.
Prohibited Practices (Hard Requirements)
- Writing business logic in Controller or directly accessing database; returning database entities directly; skipping DTO/VO.
- Injecting Repository in Controller; data must be accessed through Service layer; Controller must not contain complex logic.
- Performing permission checks, cross-model operations, or extra existence queries in Repository; Repository methods containing unnecessary parameters.
- Using generic permission exception names (Unauthorized/PermissionDenied/AccessDenied) instead of specific resource NotFound.
- Overriding AppException default messages or creating custom business exception types; customizing HTTP status codes to represent business errors.
- Using
throw new Error()instead ofAppException + ResponseCodefor business errors; unexpected infrastructure exceptions may be propagated to the global filter directly. - Using Logger static methods or
console; reading environment variables directly (must go through config module). - Using
as anyor explicitly bypassing type checking; disabling/ignoring Lint during development. - Using
z.nativeEnum; must usez.enumand explicitly list enum values. - Arbitrarily wrapping business logic with try-catch; exceptions should be handled uniformly by the framework.
- Delete operations returning meaningless objects like
{ success: true }; should returnvoid. - Using wrong HTTP methods: delete uses
@Delete()not@Put(); update uses@Patch()not@Put(). - Designing complex state enums; doing statistics/aggregation iteration at application layer; pagination methods not following naming conventions.
- HTTP decorators not starting with
/or being empty; Controller methods not following naming conventions. - Writing redundant comments; code should be self-explanatory, avoid unnecessary comments explaining obvious logic.
- Creating Controller methods without
@ApiDocdecorator; creating DTO/VO schema fields without.describe(). - Writing data migration logic as NestJS Service/Controller; migrations must be pure MongoDB shell scripts placed in
migrations/directory, executed viamongosh. - Using
@InjectModelor@InjectConnectionin Service files; data access must go through Repository layer. - Pagination Service methods doing
list.map(item => ({...}))entity mapping for response fields; Service method return values containingpageNo/pageSizepagination parameters (Controller already has these). - Using
.nullable()for DB optional fields (required: false/field?: Type) instead of.optional(); this causes type mismatch and forces Controller to add?? nullconversions.
Build Verification
- Must use
pnpm nx build <project>to verify builds - Using
tscdirectly for compilation is prohibited - After renaming methods, must run
pnpm nx buildto ensure all references are updated - Before merging, ensure all builds pass:
pnpm nx run-many --target=build --all