+134
-15
@@ -2,6 +2,7 @@ package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -31,7 +32,7 @@ func NewFAQHandler(knowledgeService interfaces.KnowledgeService) *FAQHandler {
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param page query int false "页码"
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Param tag_id query string false "标签ID筛选"
|
||||
// @Param tag_id query int false "标签ID筛选(seq_id)"
|
||||
// @Param keyword query string false "关键词搜索"
|
||||
// @Param search_field query string false "搜索字段: standard_question(标准问题), similar_questions(相似问法), answers(答案), 默认搜索全部"
|
||||
// @Param sort_order query string false "排序方式: asc(按更新时间正序), 默认按更新时间倒序"
|
||||
@@ -49,12 +50,21 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
tagID := secutils.SanitizeForLog(c.Query("tag_id"))
|
||||
var tagSeqID int64
|
||||
tagIDStr := c.Query("tag_id")
|
||||
if tagIDStr != "" {
|
||||
var err error
|
||||
tagSeqID, err = strconv.ParseInt(tagIDStr, 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("tag_id 必须是整数"))
|
||||
return
|
||||
}
|
||||
}
|
||||
keyword := secutils.SanitizeForLog(c.Query("keyword"))
|
||||
searchField := secutils.SanitizeForLog(c.Query("search_field"))
|
||||
sortOrder := secutils.SanitizeForLog(c.Query("sort_order"))
|
||||
|
||||
result, err := h.knowledgeService.ListFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &page, tagID, keyword, searchField, sortOrder)
|
||||
result, err := h.knowledgeService.ListFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &page, tagSeqID, keyword, searchField, sortOrder)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -69,7 +79,9 @@ func (h *FAQHandler) ListEntries(c *gin.Context) {
|
||||
|
||||
// UpsertEntries godoc
|
||||
// @Summary 批量更新/插入FAQ条目
|
||||
// @Description 异步批量更新或插入FAQ条目
|
||||
// @Description 异步批量更新或插入FAQ条目。支持 dry_run 模式(设置 dry_run=true),异步验证不实际导入。
|
||||
// @Description dry_run 模式是异步操作,返回 task_id,通过 /faq/import/progress/{task_id} 查询进度和结果。
|
||||
// @Description 验证内容包括:1) 条目基本格式 2) 重复问题(批次内和知识库已有) 3) 内容安全检查。
|
||||
// @Tags FAQ管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
@@ -89,7 +101,10 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
taskID, err := h.knowledgeService.UpsertFAQEntries(ctx, secutils.SanitizeForLog(c.Param("id")), &req)
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
// 统一使用 UpsertFAQEntries,通过 DryRun 字段区分模式
|
||||
taskID, err := h.knowledgeService.UpsertFAQEntries(ctx, kbID, &req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -146,7 +161,7 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param entry_id path string true "FAQ条目ID"
|
||||
// @Param entry_id path int true "FAQ条目ID(seq_id)"
|
||||
// @Param request body types.FAQEntryPayload true "FAQ条目"
|
||||
// @Success 200 {object} map[string]interface{} "更新成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
@@ -162,8 +177,15 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.knowledgeService.UpdateFAQEntry(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")), secutils.SanitizeForLog(c.Param("entry_id")), &req); err != nil {
|
||||
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.UpdateFAQEntry(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")), entrySeqID, &req)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -171,6 +193,7 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) {
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": entry,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -240,12 +263,18 @@ func (h *FAQHandler) UpdateEntryFieldsBatch(c *gin.Context) {
|
||||
|
||||
// faqDeleteRequest is a request for deleting FAQ entries in batch
|
||||
type faqDeleteRequest struct {
|
||||
IDs []string `json:"ids" binding:"required,min=1,dive,required"`
|
||||
IDs []int64 `json:"ids" binding:"required,min=1"`
|
||||
}
|
||||
|
||||
// faqEntryTagBatchRequest is a request for updating tags for FAQ entries in batch
|
||||
// key: entry seq_id, value: tag seq_id (nil to remove tag)
|
||||
type faqEntryTagBatchRequest struct {
|
||||
Updates map[string]*string `json:"updates" binding:"required,min=1"`
|
||||
Updates map[int64]*int64 `json:"updates" binding:"required,min=1"`
|
||||
}
|
||||
|
||||
// addSimilarQuestionsRequest is a request for adding similar questions to a FAQ entry
|
||||
type addSimilarQuestionsRequest struct {
|
||||
SimilarQuestions []string `json:"similar_questions" binding:"required,min=1"`
|
||||
}
|
||||
|
||||
// DeleteEntries godoc
|
||||
@@ -255,7 +284,7 @@ type faqEntryTagBatchRequest struct {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param request body object{ids=[]string} true "要删除的FAQ ID列表"
|
||||
// @Param request body object{ids=[]int} true "要删除的FAQ ID列表(seq_id)"
|
||||
// @Success 200 {object} map[string]interface{} "删除成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Security Bearer
|
||||
@@ -272,7 +301,7 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) {
|
||||
|
||||
if err := h.knowledgeService.DeleteFAQEntries(ctx,
|
||||
secutils.SanitizeForLog(c.Param("id")),
|
||||
secutils.SanitizeForLogArray(req.IDs)); err != nil {
|
||||
req.IDs); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
@@ -362,7 +391,7 @@ func (h *FAQHandler) ExportEntries(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param entry_id path string true "FAQ条目ID"
|
||||
// @Param entry_id path int true "FAQ条目ID(seq_id)"
|
||||
// @Success 200 {object} map[string]interface{} "FAQ条目详情"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "条目不存在"
|
||||
@@ -372,9 +401,13 @@ func (h *FAQHandler) ExportEntries(c *gin.Context) {
|
||||
func (h *FAQHandler) GetEntry(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
entryID := secutils.SanitizeForLog(c.Param("entry_id"))
|
||||
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entryID)
|
||||
entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entrySeqID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
@@ -415,3 +448,89 @@ func (h *FAQHandler) GetImportProgress(c *gin.Context) {
|
||||
"data": progress,
|
||||
})
|
||||
}
|
||||
|
||||
// updateLastFAQImportResultDisplayStatusRequest is the request payload for UpdateLastImportResultDisplayStatus
|
||||
type updateLastFAQImportResultDisplayStatusRequest struct {
|
||||
DisplayStatus string `json:"display_status" binding:"required,oneof=open close"`
|
||||
}
|
||||
|
||||
// UpdateLastImportResultDisplayStatus godoc
|
||||
// @Summary 更新FAQ最后一次导入结果显示状态
|
||||
// @Description 更新FAQ知识库导入结果统计卡片的显示或隐藏状态
|
||||
// @Tags FAQ管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param request body updateLastFAQImportResultDisplayStatusRequest true "状态更新请求"
|
||||
// @Success 200 {object} map[string]interface{} "更新成功"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "知识库不存在或无导入记录"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /knowledge-bases/{id}/faq/import/last-result/display [put]
|
||||
func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
var req updateLastFAQImportResultDisplayStatusRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind display status update payload", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(ctx, kbID, req.DisplayStatus); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
})
|
||||
}
|
||||
|
||||
// AddSimilarQuestions godoc
|
||||
// @Summary 添加相似问
|
||||
// @Description 向指定的FAQ条目添加相似问题
|
||||
// @Tags FAQ管理
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param entry_id path int true "FAQ条目ID(seq_id)"
|
||||
// @Param request body addSimilarQuestionsRequest true "相似问列表"
|
||||
// @Success 200 {object} map[string]interface{} "更新后的FAQ条目"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
// @Failure 404 {object} errors.AppError "条目不存在"
|
||||
// @Security Bearer
|
||||
// @Security ApiKeyAuth
|
||||
// @Router /knowledge-bases/{id}/faq/entries/{entry_id}/similar-questions [post]
|
||||
func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
|
||||
if err != nil {
|
||||
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
|
||||
return
|
||||
}
|
||||
|
||||
var req addSimilarQuestionsRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind add similar questions payload", err)
|
||||
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
entry, err := h.knowledgeService.AddSimilarQuestions(ctx, kbID, entrySeqID, req.SimilarQuestions)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": entry,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/hibiken/asynq"
|
||||
)
|
||||
|
||||
@@ -375,7 +375,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
|
||||
// Generate task ID if not provided
|
||||
taskID := req.TaskID
|
||||
if taskID == "" {
|
||||
taskID = uuid.New().String()
|
||||
taskID = utils.GenerateTaskID("kb_clone", tenantID.(uint64), req.SourceID)
|
||||
}
|
||||
|
||||
// Create KB clone payload
|
||||
@@ -394,7 +394,8 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {
|
||||
}
|
||||
|
||||
// Enqueue KB clone task to Asynq
|
||||
task := asynq.NewTask(types.TypeKBClone, payloadBytes, asynq.Queue("default"), asynq.MaxRetry(3))
|
||||
task := asynq.NewTask(types.TypeKBClone, payloadBytes,
|
||||
asynq.TaskID(taskID), asynq.Queue("default"), asynq.MaxRetry(3))
|
||||
info, err := h.asynqClient.Enqueue(task)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to enqueue KB clone task: %v", err)
|
||||
|
||||
@@ -1,179 +0,0 @@
|
||||
# Session Handler 重构总结
|
||||
|
||||
## 📋 优化概述
|
||||
|
||||
本次重构主要通过提取公共辅助函数来简化代码,消除重复逻辑,提高代码的可维护性和可读性。
|
||||
|
||||
## 🆕 新增文件
|
||||
|
||||
### `helpers.go` - 辅助函数集合
|
||||
|
||||
创建了一个专门的辅助函数文件,包含以下功能:
|
||||
|
||||
#### SSE 相关
|
||||
- **`setSSEHeaders(c *gin.Context)`** - 设置 SSE 标准头部
|
||||
- **`sendCompletionEvent(c, requestID)`** - 发送完成事件
|
||||
- **`buildStreamResponse(evt, requestID)`** - 从 StreamEvent 构建 StreamResponse
|
||||
|
||||
#### 事件和流处理
|
||||
- **`createAgentQueryEvent(sessionID, assistantMessageID)`** - 创建 agent query 事件
|
||||
- **`writeAgentQueryEvent(ctx, sessionID, assistantMessageID)`** - 写入 agent query 事件到流管理器
|
||||
|
||||
#### 消息处理
|
||||
- **`createUserMessage(ctx, sessionID, query, requestID)`** - 创建用户消息
|
||||
- **`createAssistantMessage(ctx, assistantMessage)`** - 创建助手消息
|
||||
|
||||
#### StreamHandler 设置
|
||||
- **`setupStreamHandler(...)`** - 创建并订阅流处理器
|
||||
- **`setupStopEventHandler(...)`** - 注册停止事件处理器
|
||||
|
||||
#### 配置相关
|
||||
- **`createDefaultSummaryConfig()`** - 创建默认摘要配置
|
||||
- **`fillSummaryConfigDefaults(config)`** - 填充摘要配置默认值
|
||||
|
||||
#### 工具函数
|
||||
- **`validateSessionID(c)`** - 验证并提取 session ID
|
||||
- **`getRequestID(c)`** - 获取 request ID
|
||||
- **`getString(m, key)`** - 安全获取字符串值
|
||||
- **`getFloat64(m, key)`** - 安全获取浮点数值
|
||||
|
||||
## 🔄 优化的文件
|
||||
|
||||
### 1. `agent_stream_handler.go`
|
||||
**减少行数**: 428 → 410 行 (-18 行)
|
||||
|
||||
**优化内容**:
|
||||
- 移除了重复的辅助函数 `getString` 和 `getFloat64`(现在在 `helpers.go` 中)
|
||||
|
||||
### 2. `stream.go`
|
||||
**减少行数**: 440 → 364 行 (-76 行, **-17.3%**)
|
||||
|
||||
**优化内容**:
|
||||
- 使用 `setSSEHeaders()` 替代重复的 4 行头部设置代码
|
||||
- 使用 `buildStreamResponse()` 替代 10+ 行的响应构建逻辑(3 处)
|
||||
- 使用 `sendCompletionEvent()` 替代重复的完成事件发送代码(3 处)
|
||||
|
||||
**优化示例**:
|
||||
```go
|
||||
// Before (10+ lines)
|
||||
response := &types.StreamResponse{
|
||||
ID: message.RequestID,
|
||||
ResponseType: evt.Type,
|
||||
Content: evt.Content,
|
||||
Done: evt.Done,
|
||||
Data: evt.Data,
|
||||
}
|
||||
if evt.Type == types.ResponseTypeReferences {
|
||||
if refs, ok := evt.Data["references"].(types.References); ok {
|
||||
response.KnowledgeReferences = refs
|
||||
}
|
||||
}
|
||||
|
||||
// After (1 line)
|
||||
response := buildStreamResponse(evt, message.RequestID)
|
||||
```
|
||||
|
||||
### 3. `qa.go`
|
||||
**减少行数**: 536 → 485 行 (-51 行, **-9.5%**)
|
||||
|
||||
**优化内容**:
|
||||
- 使用 `setSSEHeaders()` 替代重复的头部设置(2 处)
|
||||
- 使用 `createUserMessage()` 替代 9 行的用户消息创建(3 处)
|
||||
- 使用 `createAssistantMessage()` 替代 3 行的助手消息创建(3 处)
|
||||
- 使用 `writeAgentQueryEvent()` 替代 15+ 行的事件写入代码(2 处)
|
||||
- 使用 `setupStreamHandler()` 替代 7 行的处理器设置(2 处)
|
||||
- 使用 `setupStopEventHandler()` 替代 7 行的停止事件处理器设置(2 处)
|
||||
- 使用 `getRequestID()` 简化请求 ID 获取(1 处)
|
||||
|
||||
### 4. `handler.go`
|
||||
**减少行数**: 354 → 312 行 (-42 行, **-11.9%**)
|
||||
|
||||
**优化内容**:
|
||||
- 使用 `createDefaultSummaryConfig()` 替代 12 行的配置创建(2 处)
|
||||
- 使用 `fillSummaryConfigDefaults()` 替代 9 行的默认值填充(1 处)
|
||||
|
||||
**优化示例**:
|
||||
```go
|
||||
// Before (21 lines)
|
||||
if request.SessionStrategy.SummaryParameters != nil {
|
||||
createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters
|
||||
} else {
|
||||
createdSession.SummaryParameters = &types.SummaryConfig{
|
||||
MaxTokens: h.config.Conversation.Summary.MaxTokens,
|
||||
TopP: h.config.Conversation.Summary.TopP,
|
||||
// ... 8 more fields
|
||||
}
|
||||
}
|
||||
if createdSession.SummaryParameters.Prompt == "" {
|
||||
createdSession.SummaryParameters.Prompt = h.config.Conversation.Summary.Prompt
|
||||
}
|
||||
// ... 2 more field checks
|
||||
|
||||
// After (5 lines)
|
||||
if request.SessionStrategy.SummaryParameters != nil {
|
||||
createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters
|
||||
} else {
|
||||
createdSession.SummaryParameters = h.createDefaultSummaryConfig()
|
||||
}
|
||||
h.fillSummaryConfigDefaults(createdSession.SummaryParameters)
|
||||
```
|
||||
|
||||
## 📊 总体统计
|
||||
|
||||
| 文件 | 优化前 | 优化后 | 减少 | 比例 |
|
||||
|------|-------|-------|------|------|
|
||||
| agent_stream_handler.go | 428 | 410 | -18 | -4.2% |
|
||||
| stream.go | 440 | 364 | -76 | -17.3% |
|
||||
| qa.go | 536 | 485 | -51 | -9.5% |
|
||||
| handler.go | 354 | 312 | -42 | -11.9% |
|
||||
| **总计** | **1,758** | **1,571** | **-187** | **-10.6%** |
|
||||
| helpers.go (新增) | 0 | 204 | +204 | - |
|
||||
| **净变化** | **1,758** | **1,775** | **+17** | **+1.0%** |
|
||||
|
||||
虽然总行数略有增加(+17 行),但代码质量显著提升:
|
||||
- ✅ 消除了大量重复代码
|
||||
- ✅ 提高了代码复用性
|
||||
- ✅ 增强了可维护性
|
||||
- ✅ 统一了代码风格
|
||||
- ✅ 便于未来扩展
|
||||
|
||||
## 🎯 关键改进
|
||||
|
||||
### 1. **代码复用性**
|
||||
通过提取公共函数,同样的逻辑只需维护一处,修改时更新一个地方即可。
|
||||
|
||||
### 2. **可读性提升**
|
||||
```go
|
||||
// Before: 需要阅读 10+ 行才能理解
|
||||
response := &types.StreamResponse{ /* 10 lines */ }
|
||||
|
||||
// After: 一行就能明白意图
|
||||
response := buildStreamResponse(evt, requestID)
|
||||
```
|
||||
|
||||
### 3. **一致性**
|
||||
所有 SSE 头部设置、消息创建、事件处理都使用统一的方法,降低出错风险。
|
||||
|
||||
### 4. **易于测试**
|
||||
辅助函数可以独立测试,提高单元测试的覆盖率。
|
||||
|
||||
### 5. **便于维护**
|
||||
如果需要修改 SSE 头部或事件格式,只需修改辅助函数,不需要搜索整个代码库。
|
||||
|
||||
## ✅ 验证结果
|
||||
|
||||
- ✅ 无 linter 错误
|
||||
- ✅ 编译成功
|
||||
- ✅ 保持原有功能不变
|
||||
- ✅ 代码结构更清晰
|
||||
|
||||
## 🔮 未来建议
|
||||
|
||||
1. **测试覆盖**: 为 `helpers.go` 中的辅助函数添加单元测试
|
||||
2. **文档完善**: 为复杂的辅助函数添加使用示例
|
||||
3. **持续优化**: 定期审查是否有新的重复代码可以提取
|
||||
|
||||
## 📝 总结
|
||||
|
||||
本次重构成功地消除了代码重复,提高了代码质量。虽然增加了一个新文件,但整体代码结构更加清晰,维护成本大幅降低。重构遵循了 DRY(Don't Repeat Yourself)原则,为未来的开发和维护打下了良好的基础。
|
||||
|
||||
+63
-8
@@ -1,7 +1,9 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
@@ -15,16 +17,44 @@ import (
|
||||
// TagHandler handles knowledge base tag operations.
|
||||
type TagHandler struct {
|
||||
tagService interfaces.KnowledgeTagService
|
||||
tagRepo interfaces.KnowledgeTagRepository
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
}
|
||||
|
||||
// DeleteTagRequest represents the request body for deleting a tag
|
||||
type DeleteTagRequest struct {
|
||||
ExcludeIDs []string `json:"exclude_ids"` // Chunk IDs to exclude from deletion
|
||||
ExcludeIDs []int64 `json:"exclude_ids"` // Chunk seq_ids to exclude from deletion
|
||||
}
|
||||
|
||||
// NewTagHandler creates a new TagHandler.
|
||||
func NewTagHandler(tagService interfaces.KnowledgeTagService) *TagHandler {
|
||||
return &TagHandler{tagService: tagService}
|
||||
func NewTagHandler(tagService interfaces.KnowledgeTagService, tagRepo interfaces.KnowledgeTagRepository, chunkRepo interfaces.ChunkRepository) *TagHandler {
|
||||
return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo}
|
||||
}
|
||||
|
||||
// resolveTagID resolves tag_id parameter which can be either UUID or seq_id (integer).
|
||||
// Returns the UUID of the tag.
|
||||
func (h *TagHandler) resolveTagID(c *gin.Context) (string, error) {
|
||||
ctx := c.Request.Context()
|
||||
tagIDParam := secutils.SanitizeForLog(c.Param("tag_id"))
|
||||
|
||||
// Try to parse as integer (seq_id)
|
||||
if seqID, err := strconv.ParseInt(tagIDParam, 10, 64); err == nil {
|
||||
// It's an integer, look up by seq_id
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
tag, err := h.tagRepo.GetBySeqID(ctx, tenantID, seqID)
|
||||
if err != nil {
|
||||
return "", errors.NewNotFoundError("标签不存在")
|
||||
}
|
||||
return tag.ID, nil
|
||||
}
|
||||
|
||||
// It's a UUID string
|
||||
return tagIDParam, nil
|
||||
}
|
||||
|
||||
// getChunksBySeqIDs retrieves chunks by their seq_ids.
|
||||
func (h *TagHandler) getChunksBySeqIDs(ctx context.Context, tenantID uint64, seqIDs []int64) ([]*types.Chunk, error) {
|
||||
return h.chunkRepo.ListChunksBySeqID(ctx, tenantID, seqIDs)
|
||||
}
|
||||
|
||||
// ListTags godoc
|
||||
@@ -127,7 +157,7 @@ type updateTagRequest struct {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param tag_id path string true "标签ID"
|
||||
// @Param tag_id path string true "标签ID (UUID或seq_id)"
|
||||
// @Param request body object true "标签更新信息"
|
||||
// @Success 200 {object} map[string]interface{} "更新后的标签"
|
||||
// @Failure 400 {object} errors.AppError "请求参数错误"
|
||||
@@ -137,7 +167,12 @@ type updateTagRequest struct {
|
||||
func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
tagID := secutils.SanitizeForLog(c.Param("tag_id"))
|
||||
tagID, err := h.resolveTagID(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req updateTagRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to bind update tag payload", err)
|
||||
@@ -167,7 +202,7 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "知识库ID"
|
||||
// @Param tag_id path string true "标签ID"
|
||||
// @Param tag_id path string true "标签ID (UUID或seq_id)"
|
||||
// @Param force query bool false "强制删除"
|
||||
// @Param content_only query bool false "仅删除内容,保留标签"
|
||||
// @Param body body DeleteTagRequest false "删除选项"
|
||||
@@ -178,7 +213,12 @@ func (h *TagHandler) UpdateTag(c *gin.Context) {
|
||||
// @Router /knowledge-bases/{id}/tags/{tag_id} [delete]
|
||||
func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
tagID := secutils.SanitizeForLog(c.Param("tag_id"))
|
||||
|
||||
tagID, err := h.resolveTagID(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
force := c.Query("force") == "true"
|
||||
contentOnly := c.Query("content_only") == "true"
|
||||
@@ -187,7 +227,22 @@ func (h *TagHandler) DeleteTag(c *gin.Context) {
|
||||
// Ignore bind error since body is optional
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
|
||||
if err := h.tagService.DeleteTag(ctx, tagID, force, contentOnly, req.ExcludeIDs); err != nil {
|
||||
// Convert seq_ids to UUIDs for excludeIDs
|
||||
var excludeUUIDs []string
|
||||
if len(req.ExcludeIDs) > 0 {
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
chunks, err := h.getChunksBySeqIDs(ctx, tenantID, req.ExcludeIDs)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Failed to resolve exclude_ids: %v", err)
|
||||
} else {
|
||||
excludeUUIDs = make([]string, len(chunks))
|
||||
for i, chunk := range chunks {
|
||||
excludeUUIDs[i] = chunk.ID
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := h.tagService.DeleteTag(ctx, tagID, force, contentOnly, excludeUUIDs); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"tag_id": tagID,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user