API契约:补齐主链路成功响应 DTO
This commit is contained in:
1 parent
1a14f18b07
commit
ebce42f9dc
8 files changed
+389
-54
No files matched your search
@@ -0,0 +1,27 @@
|
||||
# HTTP API 版本化迁移边界
|
||||
|
||||
本文记录阶段三当前切片完成后的 API 版本化边界。当前仓库尚未切换现有路径;新版本路由必须先完成前端调用方迁移和契约测试,再删除旧别名。
|
||||
|
||||
## 当前兼容路径
|
||||
|
||||
| 领域 | 现有路径 | 目标 `/api/v1` 路径 | 迁移状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| 会话 | `/verify`、`/logout` | `/api/v1/session`、`/api/v1/session/logout` | 旧路径保留,待前端统一请求层后迁移 |
|
||||
| 账号 | `/cookies/details`、`/cookies/{cid}/...` | `/api/v1/accounts/...` | 旧路径保留,具名 DTO 已开始落地 |
|
||||
| 订单 | `/api/orders...` | `/api/v1/orders...` | 旧路径保留,列表 DTO 已落地 |
|
||||
| 聊天 | `/api/chat...` | `/api/v1/chat...` | 旧路径保留,会话/消息 DTO 已落地 |
|
||||
|
||||
## 迁移规则
|
||||
|
||||
1. 新增接口只能使用 `/api/v1` 前缀,禁止继续增加未版本化的业务路径。
|
||||
2. 旧路径通过同一 handler 或薄适配器保留,不复制业务逻辑;适配器只负责路径和请求/响应兼容。
|
||||
3. 前端请求层先切换到 `/api/v1`,并保留旧响应字段的边界归一;Go、React 和外部调用方契约测试全部通过后,才可以删除旧别名。
|
||||
4. 删除旧路径前必须记录调用方、发布日期、迁移版本和回滚方案;发布说明要明确旧路径的移除版本。
|
||||
5. 错误响应始终使用 `code`、`message`、`request_id`,恢复信息只能放入 `details`;版本适配器不得重新引入 `detail`、`msg` 或 HTTP 200 + `success:false`。
|
||||
|
||||
## 当前切片证据
|
||||
|
||||
- 认证会话校验使用 `sessionVerificationResponse`。
|
||||
- 订单列表使用 `orderListResponse` 和 `orderDTO`。
|
||||
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
|
||||
- 旧路径仍由现有路由提供,尚未宣称 `/api/v1` 已经可用。
|
||||
@@ -133,7 +133,8 @@ app shell / routes
|
||||
- 已完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移”:订单刷新、手动发货和订单导入不再返回顶层 HTTP 200 + `success:false`,批量结果改用 `partial_failure`,刷新明细错误统一使用 `message`;账号任务的 502 错误改用统一错误 DTO;新增订单/账号契约测试并通过全量门禁,逐项结果中的 `success` 仅保留为批处理行状态;
|
||||
- 已完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移”:聊天发送失败和商品发布失败均改用统一 `code`/`message`/`request_id` 错误 DTO,商品远端已成功但本地保存失败的恢复信息迁移到可选 `details`;React 错误类型同步支持 `details`,新增 HTTP DTO、聊天/自动化/商品契约测试并通过前端门禁;
|
||||
- 已完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移”:二维码生成、扫码状态持久化、风控验证失败和账号不匹配均改用正确的非 2xx 状态码与统一错误 DTO;历史密码登录入口返回明确的 `password_login_disabled` 未实现错误;新增二维码/密码登录契约测试并通过全量门禁;
|
||||
- 阶段 3 下一 PR 切片为“统一业务成功响应具名 DTO 与版本化路径准备”:盘点剩余动态 map 成功响应,先为认证、账号、订单和聊天主链路补齐具名响应 DTO,并记录 `/api/v1` 兼容迁移边界,不拆分单个 handler 提交;
|
||||
- 已完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备”:认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO,新增响应契约测试,并记录 `/api/v1` 兼容迁移边界;未提前切换旧路径,保持可回滚;
|
||||
- 阶段 3 下一 PR 切片为“剩余业务成功响应 DTO 与客户端契约收口”:继续按领域迁移剩余账号、商品、自动化和订单详情成功响应,不拆分单个 handler 提交;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -515,3 +516,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移” | 订单批量接口移除顶层 HTTP 200 + `success:false`,逐项失败保留行级状态并统一为 `message`;账号任务 502 改用统一错误 DTO;订单/账号契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:聊天、商品与自动化业务 API 错误响应迁移 |
|
||||
| 2026-08-14 | 完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移” | 聊天发送和商品发布失败统一为 `code`/`message`/`request_id`,远端发布后的商品核对信息迁移到 `details`;React 错误类型、HTTP DTO 测试和业务契约测试已更新;前端类型检查、测试、构建及 Go 注释门禁通过 | 阶段 3:二维码登录、密码登录和剩余公共业务错误响应迁移 |
|
||||
| 2026-08-14 | 完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移” | 二维码与密码登录遗留 HTTP 200 + `success:false` 已迁移为非 2xx 错误;账号不匹配保留 `scanned_account_id` 到 `details`;二维码/密码登录契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:统一业务成功响应具名 DTO 与版本化路径准备 |
|
||||
| 2026-08-14 | 完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备” | 认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO;新增响应契约测试和 `/api/v1` 迁移边界文档;全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:剩余业务成功响应 DTO 与客户端契约收口 |
|
||||
@@ -147,18 +147,18 @@ func (s *Server) verify(w http.ResponseWriter, r *http.Request) {
|
||||
initialized, _ := s.Store.Users.IsSystemInitialized(ctx)
|
||||
sess := auth.SessionFromContext(ctx)
|
||||
if sess != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"authenticated": true,
|
||||
"user_id": sess.UserID,
|
||||
"username": sess.Username,
|
||||
"is_admin": sess.IsAdmin,
|
||||
"initialized": initialized,
|
||||
writeJSON(w, http.StatusOK, sessionVerificationResponse{
|
||||
Authenticated: true,
|
||||
UserID: sess.UserID,
|
||||
Username: sess.Username,
|
||||
IsAdmin: sess.IsAdmin,
|
||||
Initialized: initialized,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"authenticated": false,
|
||||
"initialized": initialized,
|
||||
writeJSON(w, http.StatusOK, sessionVerificationResponse{
|
||||
Authenticated: false,
|
||||
Initialized: initialized,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
s.Auth.Logout(r.Context(), sess.SessionID)
|
||||
}
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"message": "已登出"})
|
||||
writeJSON(w, http.StatusOK, messageResponse{Message: "已登出"})
|
||||
}
|
||||
|
||||
// changeAdminPassword 修改管理员密码。
|
||||
@@ -203,7 +203,7 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功,请重新登录", "requires_relogin": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true, Message: "密码修改成功,请重新登录", RequiresRelogin: true})
|
||||
}
|
||||
|
||||
// changePassword 修改当前用户密码。
|
||||
@@ -236,7 +236,7 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "密码修改成功,请重新登录", "requires_relogin": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true, Message: "密码修改成功,请重新登录", RequiresRelogin: true})
|
||||
}
|
||||
|
||||
// updateCredentials 修改当前登录用户的用户名和/或密码,并撤销全部旧会话。
|
||||
@@ -291,9 +291,9 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"message": "登录凭据已更新,请使用新用户名和密码重新登录",
|
||||
"requires_relogin": true,
|
||||
writeJSON(w, http.StatusOK, operationResponse{
|
||||
Success: true,
|
||||
Message: "登录凭据已更新,请使用新用户名和密码重新登录",
|
||||
RequiresRelogin: true,
|
||||
})
|
||||
}
|
||||
@@ -75,7 +75,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
FetchChatUserInfo(context.Context, string, string) (*mtop.ChatUserInfo, error)
|
||||
})
|
||||
if !canResolve {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor})
|
||||
return
|
||||
}
|
||||
resolveCtx, resolveCancel := context.WithTimeout(r.Context(), 25*time.Second)
|
||||
@@ -131,7 +131,7 @@ func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"sessions": rows, "has_more": hasMore, "next_cursor": nextCursor})
|
||||
writeJSON(w, http.StatusOK, chatSessionPageResponse{Sessions: newChatSessionDTOs(rows), HasMore: hasMore, NextCursor: nextCursor})
|
||||
}
|
||||
|
||||
func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -215,7 +215,7 @@ func (s *Server) sendChatImage(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "图片已发送,但状态保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"message": sent})
|
||||
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
|
||||
}
|
||||
|
||||
func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -256,7 +256,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
current = s.resolveSelectedChatIdentity(r.Context(), accountID, current)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"messages": page.Messages, "has_more": page.HasMore, "next_cursor": page.NextCursor, "session": current})
|
||||
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, NextCursor: page.NextCursor, Session: newChatSessionDTO(current)})
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -277,7 +277,7 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"messages": rows, "has_more": len(rows) == limit, "session": current})
|
||||
writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(rows), HasMore: len(rows) == limit, Session: newChatSessionDTO(current)})
|
||||
}
|
||||
|
||||
func (s *Server) resolveSelectedChatIdentity(ctx context.Context, accountID string, session db.ChatSession) db.ChatSession {
|
||||
@@ -362,7 +362,7 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "消息已发送,但状态保存失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"message": sent})
|
||||
writeJSON(w, http.StatusCreated, chatMessageEnvelope{Message: newChatMessageDTOFromPointer(sent)})
|
||||
}
|
||||
|
||||
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -383,7 +383,7 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -521,7 +521,7 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": req.ID})
|
||||
writeJSON(w, http.StatusOK, accountMutationResponse{Success: true, ID: req.ID})
|
||||
}
|
||||
|
||||
// updateCookie 更新 cookie 值。
|
||||
|
||||
@@ -72,40 +72,40 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
orders := make([]map[string]any, 0, len(rows))
|
||||
orders := make([]orderDTO, 0, len(rows))
|
||||
for _, o := range rows {
|
||||
st := db.NormalizeOrderStatus(o.OrderStatus)
|
||||
orders = append(orders, map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": o.ItemTitle,
|
||||
"item_image": itemImageFromDetail(o.ItemDetail),
|
||||
"buyer_id": o.BuyerID,
|
||||
"spec_name": o.SpecName,
|
||||
"spec_value": o.SpecValue,
|
||||
"quantity": o.Quantity,
|
||||
"amount": o.Amount,
|
||||
"order_status": st,
|
||||
"status": st,
|
||||
"cookie_id": o.CookieID,
|
||||
"is_bargain": o.IsBargain,
|
||||
"system_shipped": o.SystemShipped,
|
||||
"receiver_name": o.ReceiverName,
|
||||
"receiver_phone": o.ReceiverPhone,
|
||||
"receiver_address": o.ReceiverAddr,
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
orders = append(orders, orderDTO{
|
||||
OrderID: o.OrderID,
|
||||
ItemID: o.ItemID,
|
||||
ItemTitle: o.ItemTitle,
|
||||
ItemImage: itemImageFromDetail(o.ItemDetail),
|
||||
BuyerID: o.BuyerID,
|
||||
SpecName: o.SpecName,
|
||||
SpecValue: o.SpecValue,
|
||||
Quantity: o.Quantity,
|
||||
Amount: o.Amount,
|
||||
OrderStatus: st,
|
||||
Status: st,
|
||||
CookieID: o.CookieID,
|
||||
IsBargain: o.IsBargain,
|
||||
SystemShipped: o.SystemShipped,
|
||||
ReceiverName: o.ReceiverName,
|
||||
ReceiverPhone: o.ReceiverPhone,
|
||||
ReceiverAddress: o.ReceiverAddr,
|
||||
ReceiverCity: o.ReceiverCity,
|
||||
CreatedAt: o.CreatedAt,
|
||||
UpdatedAt: o.UpdatedAt,
|
||||
})
|
||||
}
|
||||
totalPages := (total + pageSize - 1) / pageSize
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"data": orders,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total_pages": totalPages,
|
||||
writeJSON(w, http.StatusOK, orderListResponse{
|
||||
Success: true,
|
||||
Data: orders,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
TotalPages: totalPages,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestNamedSuccessResponseContracts 验证认证、订单和聊天主链路使用具名成功响应 DTO。
|
||||
func TestNamedSuccessResponseContracts(t *testing.T) {
|
||||
// srv 是用于验证成功响应 DTO 的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
|
||||
// verifyReq 是读取当前会话状态的请求。
|
||||
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
|
||||
verifyReq.AddCookie(sessionCookie)
|
||||
// verifyRecorder 是捕获会话状态响应的测试记录器。
|
||||
verifyRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(verifyRecorder, verifyReq)
|
||||
if verifyRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("verify status=%d body=%s", verifyRecorder.Code, verifyRecorder.Body.String())
|
||||
}
|
||||
// verifyResponse 是会话校验具名响应 DTO。
|
||||
var verifyResponse sessionVerificationResponse
|
||||
// verifyDecodeErr 表示会话响应 JSON 反序列化失败的原因。
|
||||
if verifyDecodeErr := json.Unmarshal(verifyRecorder.Body.Bytes(), &verifyResponse); verifyDecodeErr != nil {
|
||||
t.Fatalf("decode verify response: %v", verifyDecodeErr)
|
||||
}
|
||||
if !verifyResponse.Authenticated || !verifyResponse.Initialized || verifyResponse.Username != "admin" {
|
||||
t.Fatalf("verify response=%+v", verifyResponse)
|
||||
}
|
||||
|
||||
// orderReq 是读取当前用户订单列表的请求。
|
||||
orderReq := httptest.NewRequest(http.MethodGet, "/api/orders", nil)
|
||||
orderReq.AddCookie(sessionCookie)
|
||||
// orderRecorder 是捕获订单列表响应的测试记录器。
|
||||
orderRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(orderRecorder, orderReq)
|
||||
if orderRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("order status=%d body=%s", orderRecorder.Code, orderRecorder.Body.String())
|
||||
}
|
||||
// orderResponse 是订单列表具名响应 DTO。
|
||||
var orderResponse orderListResponse
|
||||
// orderDecodeErr 表示订单列表响应 JSON 反序列化失败的原因。
|
||||
if orderDecodeErr := json.Unmarshal(orderRecorder.Body.Bytes(), &orderResponse); orderDecodeErr != nil {
|
||||
t.Fatalf("decode order response: %v", orderDecodeErr)
|
||||
}
|
||||
if !orderResponse.Success || orderResponse.Page != 1 || orderResponse.PageSize != 20 {
|
||||
t.Fatalf("order response=%+v", orderResponse)
|
||||
}
|
||||
|
||||
// chatReq 是读取账号聊天会话列表的请求。
|
||||
chatReq := httptest.NewRequest(http.MethodGet, "/api/chat/sessions?account_id=acc1", nil)
|
||||
chatReq.AddCookie(sessionCookie)
|
||||
// chatRecorder 是捕获聊天会话响应的测试记录器。
|
||||
chatRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(chatRecorder, chatReq)
|
||||
if chatRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("chat status=%d body=%s", chatRecorder.Code, chatRecorder.Body.String())
|
||||
}
|
||||
// chatResponse 是聊天会话分页具名响应 DTO。
|
||||
var chatResponse chatSessionPageResponse
|
||||
// chatDecodeErr 表示聊天会话响应 JSON 反序列化失败的原因。
|
||||
if chatDecodeErr := json.Unmarshal(chatRecorder.Body.Bytes(), &chatResponse); chatDecodeErr != nil {
|
||||
t.Fatalf("decode chat response: %v", chatDecodeErr)
|
||||
}
|
||||
if chatResponse.Sessions == nil || chatResponse.HasMore {
|
||||
t.Fatalf("chat response=%+v", chatResponse)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
package server
|
||||
|
||||
import "xianyu-go/internal/db"
|
||||
|
||||
// operationResponse 是密码、会话和设置变更接口共用的操作结果 DTO。
|
||||
type operationResponse struct {
|
||||
// Success 表示操作是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Message 是可以直接展示给用户的操作结果说明。
|
||||
Message string `json:"message,omitempty"`
|
||||
// RequiresRelogin 表示操作完成后当前会话已被撤销,需要重新登录。
|
||||
RequiresRelogin bool `json:"requires_relogin,omitempty"`
|
||||
}
|
||||
|
||||
// messageResponse 是只返回提示文本的简单成功响应 DTO。
|
||||
type messageResponse struct {
|
||||
// Message 是接口操作结果说明。
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// sessionVerificationResponse 是会话校验接口的具名响应 DTO。
|
||||
type sessionVerificationResponse struct {
|
||||
// Authenticated 表示当前请求是否带有有效会话。
|
||||
Authenticated bool `json:"authenticated"`
|
||||
// Initialized 表示系统是否已经完成管理员初始化。
|
||||
Initialized bool `json:"initialized"`
|
||||
// UserID 是当前会话用户 ID;未认证时为空值。
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
// Username 是当前会话用户名;未认证时为空字符串。
|
||||
Username string `json:"username,omitempty"`
|
||||
// IsAdmin 表示当前会话用户是否为管理员。
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
}
|
||||
|
||||
// accountMutationResponse 是账号新增等简单变更接口的具名成功响应 DTO。
|
||||
type accountMutationResponse struct {
|
||||
// Success 表示账号变更是否完成。
|
||||
Success bool `json:"success"`
|
||||
// ID 是新增或更新账号的稳定标识。
|
||||
ID string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
// chatSessionDTO 是聊天会话对外暴露的非敏感 DTO,不直接复用数据库模型。
|
||||
type chatSessionDTO struct {
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// ChatID 是平台聊天会话标识。
|
||||
ChatID string `json:"chat_id"`
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string `json:"buyer_id"`
|
||||
// BuyerName 是买家昵称。
|
||||
BuyerName string `json:"buyer_name"`
|
||||
// BuyerAvatar 是买家头像地址。
|
||||
BuyerAvatar string `json:"buyer_avatar_url"`
|
||||
// ItemID 是会话关联商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemTitle 是会话关联商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// LastMessage 是最近一条消息摘要。
|
||||
LastMessage string `json:"last_message"`
|
||||
// LastMessageAt 是最近消息时间的 Unix 秒。
|
||||
LastMessageAt int64 `json:"last_message_at"`
|
||||
// UnreadCount 是当前会话未读消息数量。
|
||||
UnreadCount int `json:"unread_count"`
|
||||
}
|
||||
|
||||
// newChatSessionDTO 将数据库聊天会话转换为 API DTO。
|
||||
func newChatSessionDTO(session db.ChatSession) chatSessionDTO {
|
||||
return chatSessionDTO{
|
||||
AccountID: session.CookieID, ChatID: session.ChatID, BuyerID: session.BuyerID,
|
||||
BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID,
|
||||
ItemTitle: session.ItemTitle, LastMessage: session.LastMessage,
|
||||
LastMessageAt: session.LastMessageAt, UnreadCount: session.UnreadCount,
|
||||
}
|
||||
}
|
||||
|
||||
// newChatSessionDTOs 批量转换聊天会话,保持接口响应不直接暴露数据库模型。
|
||||
func newChatSessionDTOs(sessions []db.ChatSession) []chatSessionDTO {
|
||||
// result 是转换后的聊天会话 DTO 列表。
|
||||
result := make([]chatSessionDTO, 0, len(sessions))
|
||||
// session 是当前待转换的数据库聊天会话。
|
||||
for _, session := range sessions {
|
||||
result = append(result, newChatSessionDTO(session))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// chatMessageDTO 是聊天消息对外暴露的具名 DTO,不直接复用数据库模型。
|
||||
type chatMessageDTO struct {
|
||||
// ID 是本地消息主键。
|
||||
ID int64 `json:"id"`
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// ChatID 是平台聊天会话标识。
|
||||
ChatID string `json:"chat_id"`
|
||||
// MessageKey 是消息幂等键。
|
||||
MessageKey string `json:"message_key"`
|
||||
// Direction 是消息方向。
|
||||
Direction string `json:"direction"`
|
||||
// SenderID 是消息发送者平台标识。
|
||||
SenderID string `json:"sender_id"`
|
||||
// SenderName 是消息发送者名称。
|
||||
SenderName string `json:"sender_name"`
|
||||
// MessageType 是消息类型。
|
||||
MessageType string `json:"message_type"`
|
||||
// Content 是消息文本或媒体地址。
|
||||
Content string `json:"content"`
|
||||
// Status 是消息投递状态。
|
||||
Status string `json:"status"`
|
||||
// SentAt 是消息发送时间的 Unix 秒。
|
||||
SentAt int64 `json:"sent_at"`
|
||||
}
|
||||
|
||||
// newChatMessageDTO 将数据库聊天消息转换为 API DTO。
|
||||
func newChatMessageDTO(message db.ChatMessage) chatMessageDTO {
|
||||
return chatMessageDTO{
|
||||
ID: message.ID, AccountID: message.CookieID, ChatID: message.ChatID,
|
||||
MessageKey: message.MessageKey, Direction: message.Direction,
|
||||
SenderID: message.SenderID, SenderName: message.SenderName,
|
||||
MessageType: message.MessageType, Content: message.Content,
|
||||
Status: message.Status, SentAt: message.SentAt,
|
||||
}
|
||||
}
|
||||
|
||||
// newChatMessageDTOFromPointer 转换可为空的聊天消息指针,避免成功响应因空值 panic。
|
||||
func newChatMessageDTOFromPointer(message *db.ChatMessage) chatMessageDTO {
|
||||
if message == nil {
|
||||
return chatMessageDTO{}
|
||||
}
|
||||
return newChatMessageDTO(*message)
|
||||
}
|
||||
|
||||
// newChatMessageDTOs 批量转换聊天消息,保持接口响应与数据库模型解耦。
|
||||
func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO {
|
||||
// result 是转换后的聊天消息 DTO 列表。
|
||||
result := make([]chatMessageDTO, 0, len(messages))
|
||||
// message 是当前待转换的数据库聊天消息。
|
||||
for _, message := range messages {
|
||||
result = append(result, newChatMessageDTO(message))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// chatSessionPageResponse 是聊天会话分页接口的具名响应 DTO。
|
||||
type chatSessionPageResponse struct {
|
||||
// Sessions 是当前页聊天会话。
|
||||
Sessions []chatSessionDTO `json:"sessions"`
|
||||
// HasMore 表示是否还有下一页。
|
||||
HasMore bool `json:"has_more"`
|
||||
// NextCursor 是下一页游标。
|
||||
NextCursor int64 `json:"next_cursor,omitempty"`
|
||||
}
|
||||
|
||||
// chatMessageEnvelope 是发送聊天消息接口的具名响应 DTO。
|
||||
type chatMessageEnvelope struct {
|
||||
// Message 是已经写入本地队列的消息。
|
||||
Message chatMessageDTO `json:"message"`
|
||||
}
|
||||
|
||||
// chatMessagePageResponse 是聊天消息分页接口的具名响应 DTO。
|
||||
type chatMessagePageResponse struct {
|
||||
// Messages 是当前页聊天消息。
|
||||
Messages []chatMessageDTO `json:"messages"`
|
||||
// HasMore 表示是否还有更多历史消息。
|
||||
HasMore bool `json:"has_more"`
|
||||
// NextCursor 是下一页游标。
|
||||
NextCursor int64 `json:"next_cursor,omitempty"`
|
||||
// Session 是当前聊天会话摘要。
|
||||
Session chatSessionDTO `json:"session"`
|
||||
}
|
||||
|
||||
// orderDTO 是订单列表和详情接口共用的具名响应 DTO。
|
||||
type orderDTO struct {
|
||||
// OrderID 是平台订单标识。
|
||||
OrderID string `json:"order_id"`
|
||||
// ItemID 是关联商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemTitle 是关联商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// ItemImage 是关联商品图片地址。
|
||||
ItemImage string `json:"item_image"`
|
||||
// BuyerID 是买家平台标识。
|
||||
BuyerID string `json:"buyer_id"`
|
||||
// SpecName 是商品规格名称。
|
||||
SpecName string `json:"spec_name"`
|
||||
// SpecValue 是商品规格值。
|
||||
SpecValue string `json:"spec_value"`
|
||||
// Quantity 是购买数量。
|
||||
Quantity string `json:"quantity"`
|
||||
// Amount 是订单实付金额。
|
||||
Amount string `json:"amount"`
|
||||
// OrderStatus 是归一化后的订单状态。
|
||||
OrderStatus string `json:"order_status"`
|
||||
// Status 是兼容前端使用的订单状态别名。
|
||||
Status string `json:"status"`
|
||||
// CookieID 是订单所属账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// IsBargain 表示订单是否来自议价。
|
||||
IsBargain int `json:"is_bargain"`
|
||||
// SystemShipped 表示是否由系统完成发货。
|
||||
SystemShipped bool `json:"system_shipped"`
|
||||
// ReceiverName 是收货人姓名。
|
||||
ReceiverName string `json:"receiver_name"`
|
||||
// ReceiverPhone 是收货人电话。
|
||||
ReceiverPhone string `json:"receiver_phone"`
|
||||
// ReceiverAddress 是收货地址。
|
||||
ReceiverAddress string `json:"receiver_address"`
|
||||
// ReceiverCity 是收货城市。
|
||||
ReceiverCity string `json:"receiver_city"`
|
||||
// CreatedAt 是订单创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// UpdatedAt 是订单更新时间。
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// orderListResponse 是订单分页接口的具名响应 DTO。
|
||||
type orderListResponse struct {
|
||||
// Success 表示查询是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Data 是当前页订单。
|
||||
Data []orderDTO `json:"data"`
|
||||
// Total 是符合筛选条件的订单总数。
|
||||
Total int `json:"total"`
|
||||
// Page 是当前页码。
|
||||
Page int `json:"page"`
|
||||
// PageSize 是当前页大小。
|
||||
PageSize int `json:"page_size"`
|
||||
// TotalPages 是总页数。
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
Reference in new issue
Block a user