Skip to content

Conversation

@smallnest
Copy link
Owner

@smallnest smallnest commented Jan 6, 2026

概述

优化首页笔记本列表加载性能,将 API 请求从 1 + 2N 个减少到 1 个(N 为笔记本数量)。

问题背景

原有实现中,首页加载笔记本列表时:

  • 首先调用 GET /api/notebooks 获取所有笔记本
  • 然后为每个笔记本卡片调用 loadNotebookCardCounts 方法
  • 该方法对每个笔记本发起 2 个额外的 API 请求(sources 和 notes 统计)

这导致如果有 10 个笔记本,首页加载需要 21 个 API 请求,严重影响加载性能。

实施的改动

后端

  1. 新增类型定义 (backend/types.go:46-56)

    • 添加 NotebookWithStats 结构体,包含 source_count 和 note_count 字段
  2. 新增数据库方法 (backend/store.go:250-290)

    • 添加 ListNotebooksWithStats 方法
    • 使用单个 SQL 查询配合子查询,一次性获取所有笔记本及其统计信息
  3. 新增 API 端点 (backend/server.go:109, 212-220)

    • 添加 GET /api/notebooks/stats 路由
    • 实现 handleListNotebooksWithStats 处理函数

前端

  1. 修改数据获取 (backend/frontend/static/app.js:382)

    • loadNotebooks 方法改为调用 /notebooks/stats API
  2. 优化渲染逻辑 (backend/frontend/static/app.js:428-430)

    • renderNotebookCards 直接使用 API 返回的统计信息
    • 移除了对 loadNotebookCardCounts 的异步调用
  3. 删除冗余代码

    • 移除 loadNotebookCardCounts 方法(不再需要)

性能提升

笔记本数量 优化前请求数 优化后请求数 改善
1 3 1 67%
10 21 1 95%
50 101 1 99%

实现细节

  • 使用 SQL 子查询 (SELECT COUNT(*)...) 在单次查询中计算统计信息
  • 保留了原有的 /notebooks 端点以确保向后兼容
  • 前端缓存逻辑保持不变,继续使用 5 分钟 TTL

This PR was written using Vibe Kanban

## 优化内容

### 后端改动 (backend/types.go)
- 添加了 `NotebookWithStats` 结构体,包含 `source_count` 和 `note_count` 字段

### 后端改动 (backend/store.go:250-290)
- 新增 `ListNotebooksWithStats` 方法,使用单个 SQL 查询获取所有笔记本及其统计信息
- 使用子查询一次性统计每个笔记本的 sources 和 notes 数量

### 后端改动 (backend/server.go)
- 添加新的 API 路由 `GET /api/notebooks/stats`
- 添加 `handleListNotebooksWithStats` 处理函数

### 前端改动 (backend/frontend/static/app.js)
- `loadNotebooks` 方法改为调用 `/notebooks/stats` API
- `renderNotebookCards` 方法直接使用 API 返回的统计信息,无需额外请求
- 删除了 `loadNotebookCardCounts` 方法(原每个笔记本2个独立请求)

## 性能提升

**优化前:** 如果有 N 个笔记本,首页加载需要 1 + 2N 个 API 请求
**优化后:** 无论多少个笔记本,首页加载只需 1 个 API 请求

例如有 10 个笔记本时:
- 优化前:21 个请求
- 优化后:1 个请求
@smallnest smallnest merged commit ce7061b into master Jan 6, 2026
1 check passed
@smallnest smallnest changed the title 显示性能优化 (vibe-kanban) 性能优化: 首页笔记本列表单次API获取 (Vibe Kanban) Jan 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants