MCPcopy Create free account
hub / github.com/53AI/53AIHub / AddEntityToFile

Function AddEntityToFile

api/controller/file_entity.go:32–139  ·  view source on GitHub ↗

AddEntityToFile godoc @Summary 添加实体到文件 @Description 为指定文件添加实体关联。如果实体不存在则创建。允许自定义 Type。 @Tags 文件管理 @Accept json @Produce json @Security BearerAuth @Param file_id path int true "文件ID" @Param request body AddEntityRequest true "实体信息" @Success 200 {object} model.CommonResponse{data=map[string]interface{

(c *gin.Context)

Source from the content-addressed store, hash-verified

30// @Success 200 {object} model.CommonResponse{data=map[string]interface{}}
31// @Router /api/files/{file_id}/entities [post]
32func AddEntityToFile(c *gin.Context) {
33 eid := config.GetEID(c)
34 fileIDStr := c.Param("file_id")
35 fileID, err := strconv.ParseInt(fileIDStr, 10, 64)
36 if err != nil {
37 c.JSON(http.StatusBadRequest, model.ParamError.ToResponse(errors.New("无效的文件ID")))
38 return
39 }
40
41 var req AddEntityRequest
42 if err := c.ShouldBindJSON(&req); err != nil {
43 c.JSON(http.StatusBadRequest, model.ParamError.ToResponse(err))
44 return
45 }
46
47 req.Type = strings.TrimSpace(req.Type)
48 req.Name = strings.TrimSpace(req.Name)
49 if req.Type == "" || req.Name == "" {
50 c.JSON(http.StatusBadRequest, model.ParamError.ToResponse(errors.New("实体类型和名称不能为空")))
51 return
52 }
53
54 var createdEntity *model.Entity
55 shouldIndex := false
56
57 // 使用事务保证一致性
58 err = model.DB.Transaction(func(tx *gorm.DB) error {
59 // 1. 获取文件信息
60 var file model.File
61 if err := tx.Where("eid = ? AND id = ?", eid, fileID).First(&file).Error; err != nil {
62 if errors.Is(err, gorm.ErrRecordNotFound) {
63 return errors.New("文件不存在")
64 }
65 return err
66 }
67
68 // 2. 获取库和空间信息
69 var library model.Library
70 if err := tx.Where("eid = ? AND id = ?", eid, file.LibraryID).First(&library).Error; err != nil {
71 return errors.New("关联的知识库不存在")
72 }
73
74 // 3. 获取/创建实体
75 entity, created, err := model.GetOrCreateEntityWithDBAndCreated(tx, eid, req.Type, req.Name)
76 if err != nil {
77 return err
78 }
79 if created {
80 createdEntity = entity
81 shouldIndex = true
82 }
83
84 // 4. 创建关联
85 relation := &model.EntityChunkRelation{
86 Eid: eid,
87 EntityID: entity.ID,
88 SpaceID: library.SpaceID,
89 LibraryID: file.LibraryID,

Callers

nothing calls this directly

Calls 7

IndexEntityMethod · 0.95
GetEIDMethod · 0.80
ToResponseMethod · 0.80
SaveMethod · 0.65
NewMethod · 0.45
CreateMethod · 0.45
ErrorMethod · 0.45

Tested by

no test coverage detected