演示

RequestDto 与 ResponseDto

每个后端 API 的请求体与响应都必须使用 @quan-erp/shared-backend-core 的 RequestDto<T> 与 ResponseDto<T>。禁止返回原始载荷或接收未包装的 @Body。

概述

统一信封:payload + status + message + referenceId。控制器读取 body.payload,并用 ResponseDto.ok / okWithEmpty / error 返回。

  • 后端 — @quan-erp/shared-backend-core
  • 前端 — @quan-erp/shared-frontend-core(简化类型)
  • 不要返回原始实体或接受裸 DTO

1. ResponseDto<T>

成功与错误共用同一信封。

  • ResponseDto.ok — 成功并带 payload
  • ResponseDto.okWithEmpty — 成功且 payload 为 null
  • ResponseDto.error — 错误信封
字段类型说明
timestampstringISO 时间
status"success" | "error"结果标志
messagestring?面向用户的消息
codeHttpStatus?可选错误 HTTP 状态
referenceIdstring日志 / 支持追踪 UUID
payloadT实际数据
TSXcontroller responses
1import { 2 Delete, 3 Get, 4 HttpStatus, 5 Post, 6 ResponseDto, 7} from "@quan-erp/shared-backend-core"; 8 9@Get("/profile") 10async getProfile() { 11 const profile = await this.service.getProfile(); 12 return ResponseDto.ok(profile); 13} 14 15@Delete("/history/:id") 16async deleteHistory() { 17 await this.service.delete(/* … */); 18 return ResponseDto.okWithEmpty(); 19} 20 21@Post("/update") 22async update() { 23 try { 24 return ResponseDto.ok( 25 { success: true }, 26 { message: "Profile updated successfully" }, 27 ); 28 } catch { 29 return ResponseDto.error( 30 "Failed to update profile", 31 HttpStatus.INTERNAL_SERVER_ERROR, 32 ); 33 } 34}

2. RequestDto<T>

@Body() 期望 RequestDto<T>;从 body.payload 读取真实 DTO。

TSXrequest body
1import { Body, Post, RequestDto } from "@quan-erp/shared-backend-core"; 2 3@Post("/calculate") 4async calculate(@Body() body: RequestDto<LoanCalculationDto>) { 5 const data = body.payload; 6 return ResponseDto.ok(await this.service.calculate(data)); 7}

3. 前端配对

客户端用 new RequestDto(dto) 包装,将 response.data 转为 ResponseDto<T>,检查 status 后返回 payload。

  • POST/PUT — RequestDto 包装
  • status === "error" 时抛错
  • GET fetchFn — 只返回 payload
  • 见前端 → Platform APIs → RequestDto & ResponseDto