kongdeqiang
2026-10-09 9af621d181217a03b1b3dce208a163915db974a3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.custom.webui.controller;
 
import com.custom.webui.dto.req.ChatCreateRequest;
import com.custom.webui.dto.req.ChatUpdateRequest;
import com.custom.webui.dto.resp.ChatDTO;
import com.custom.webui.dto.resp.Result;
import com.custom.webui.security.CurrentUser;
import com.custom.webui.service.ChatService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.List;
 
/** 会话 CRUD 接口,对应侧边栏的对话列表。 */
@RestController
@RequestMapping("/api/chats")
@RequiredArgsConstructor
public class ChatController {
 
    private final ChatService chatService;
 
    /** 当前用户的全部会话,按最近活跃排序 */
    @GetMapping
    public Result<List<ChatDTO>> list() {
        return Result.success(chatService.listByUser(CurrentUser.requireUserId()));
    }
 
    /**
     * 搜索历史对话。
     *
     * <p>同时匹配会话标题与消息内容 —— 用户往往记得「聊过什么」却想不起原话,
     * 而标题只是首条提问的截断,只搜标题会漏掉大量结果。
     *
     * @param q     关键词;为空时返回空列表
     * @param limit 最多返回条数,默认 30,上限 100
     */
    @GetMapping("/search")
    public Result<List<ChatDTO>> search(@RequestParam("q") String q,
                                       @RequestParam(value = "limit", defaultValue = "30") int limit) {
        return Result.success(chatService.search(CurrentUser.requireUserId(), q, limit));
    }
 
    /** 新建会话 */
    @PostMapping
    public Result<ChatDTO> create(@Valid @RequestBody(required = false) ChatCreateRequest request) {
        // request 允许为 null:前端点「新对话」时不必构造空 body
        return Result.success(chatService.create(CurrentUser.requireUserId(), request));
    }
 
    /** 修改会话标题或模型参数(temperature / top_p / systemPrompt / modelName) */
    @PutMapping("/{id}")
    public Result<ChatDTO> update(@PathVariable Long id,
                                 @Valid @RequestBody ChatUpdateRequest request) {
        return Result.success(chatService.update(CurrentUser.requireUserId(), id, request));
    }
 
    /** 删除会话及其全部关联数据 */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        chatService.delete(CurrentUser.requireUserId(), id);
        return Result.success();
    }
}