Skip to content

feat: 优化分页组件 - #1298

Merged
xyfacai merged 1 commit into
QuantumNous:mainfrom
xiangyuanliu:feat/page-format
Jun 27, 2025
Merged

feat: 优化分页组件#1298
xyfacai merged 1 commit into
QuantumNous:mainfrom
xiangyuanliu:feat/page-format

Conversation

@xiangyuanliu

@xiangyuanliu xiangyuanliu commented Jun 25, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Improved pagination support for user listings, including page number, page size, and timestamp filtering in API responses.
  • Refactor

    • Standardized and centralized pagination logic across the application for a more consistent and reliable API experience.
    • Updated API responses for user lists to return a unified pagination object, enhancing clarity and usability.

@coderabbitai

coderabbitai Bot commented Jun 25, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

A new PageInfo struct and related helper functions were introduced to centralize pagination and timestamp filtering logic. The user controller and model functions were refactored to utilize this new struct, replacing manual parameter parsing and response construction with a more structured approach. Response formats and function signatures were updated accordingly.

Changes

File(s) Change Summary
common/page_info.go Added PageInfo struct, pagination methods, and GetPageQuery function for parameter parsing.
controller/user.go Refactored GetAllUsers to use common.GetPageQuery and return PageInfo in responses.
model/user.go Updated GetAllUsers to accept *PageInfo and use its methods for pagination logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller
    participant Common
    participant Model

    Client->>Controller: GET /users?p=1&page_size=10
    Controller->>Common: GetPageQuery(c)
    Common-->>Controller: PageInfo or error
    Controller->>Model: GetAllUsers(pageInfo)
    Model-->>Controller: users, total, error
    Controller->>PageInfo: SetTotal(total), SetItems(users)
    Controller-->>Client: JSON response { data: PageInfo }
Loading

Poem

In fields of code where queries hop,
A rabbit found a single stop—
For pages, times, and counts galore,
Now bundled neat, not spread on floor.
With paws, it cheered: "Less fuss, more fun!
Pagination’s job—together, done!"
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🔭 Outside diff range comments (1)
controller/user.go (1)

276-307: Maintain consistency with SearchUsers function.

The SearchUsers function still uses the old manual parameter parsing approach while GetAllUsers now uses the new PageInfo abstraction. This creates inconsistency in the codebase.

Consider refactoring SearchUsers to also use common.GetPageQuery() for consistency:

 func SearchUsers(c *gin.Context) {
 	keyword := c.Query("keyword")
 	group := c.Query("group")
-	p, _ := strconv.Atoi(c.Query("p"))
-	pageSize, _ := strconv.Atoi(c.Query("page_size"))
-	if p < 1 {
-		p = 1
-	}
-	if pageSize < 0 {
-		pageSize = common.ItemsPerPage
+	pageInfo, err := common.GetPageQuery(c)
+	if err != nil {
+		c.JSON(http.StatusOK, gin.H{
+			"success": false,
+			"message": "分页参数解析失败",
+		})
+		return
 	}
-	startIdx := (p - 1) * pageSize
-	users, total, err := model.SearchUsers(keyword, group, startIdx, pageSize)
+	users, total, err := model.SearchUsers(keyword, group, pageInfo.GetStartIdx(), pageInfo.GetPageSize())
🧹 Nitpick comments (3)
common/page_info.go (1)

11-12: Consider utilizing the timestamp fields.

The StartTimestamp and EndTimestamp fields are defined but not used in GetPageQuery(). Consider either using them for filtering or documenting their intended purpose.

Do you want me to implement timestamp filtering logic or should these fields be removed if they're not needed?

model/user.go (1)

137-137: Consider adding timestamp filtering.

The PageInfo struct includes StartTimestamp and EndTimestamp fields, but they're not being used for filtering users. Consider adding timestamp-based filtering if these fields are intended to be functional.

 	// Get paginated users within same transaction
+	query := tx.Unscoped().Order("id desc")
+	if pageInfo.StartTimestamp > 0 {
+		query = query.Where("created_at >= ?", time.Unix(pageInfo.StartTimestamp, 0))
+	}
+	if pageInfo.EndTimestamp > 0 {
+		query = query.Where("created_at <= ?", time.Unix(pageInfo.EndTimestamp, 0))
+	}
+	err = query.Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("password").Find(&users).Error
-	err = tx.Unscoped().Order("id desc").Limit(pageInfo.GetPageSize()).Offset(pageInfo.GetStartIdx()).Omit("password").Find(&users).Error
controller/user.go (1)

249-256: Use consistent language for error messages.

The error message "parse page query failed" is in English while other error messages in this controller are in Chinese. This creates inconsistency in the API responses.

-			"message": "parse page query failed",
+			"message": "分页参数解析失败",
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf4700a and 76da067.

📒 Files selected for processing (3)
  • common/page_info.go (1 hunks)
  • controller/user.go (1 hunks)
  • model/user.go (2 hunks)
🔇 Additional comments (2)
model/user.go (1)

117-117: LGTM! Clean refactoring to use PageInfo.

The function signature change properly utilizes the new pagination abstraction while maintaining the same functionality.

controller/user.go (1)

266-272: Verify the API response format change impact.

The response format has changed from separate fields (items, total, page, page_size) to embedding the entire PageInfo object. This is a breaking change that could affect existing API consumers.

#!/bin/bash
# Description: Search for API consumers that might be affected by this response format change
# Expected: Find references to the old response fields

echo "Searching for API consumers that might be affected..."
rg "\.data\.(items|total|page|page_size)" -A 2 -B 2
rg "response.*\.data\." -A 2 -B 2
rg "GetAllUsers.*response" -A 5 -B 5

Comment thread common/page_info.go
Comment on lines +18 to +20
func (p *PageInfo) GetStartIdx() int {
return (p.Page - 1) * p.PageSize
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation to prevent negative indices.

The GetStartIdx() method could return negative values if Page is 0, which could cause issues with database queries.

 func (p *PageInfo) GetStartIdx() int {
+	if p.Page < 1 {
+		return 0
+	}
 	return (p.Page - 1) * p.PageSize
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (p *PageInfo) GetStartIdx() int {
return (p.Page - 1) * p.PageSize
}
func (p *PageInfo) GetStartIdx() int {
if p.Page < 1 {
return 0
}
return (p.Page - 1) * p.PageSize
}
🤖 Prompt for AI Agents
In common/page_info.go around lines 18 to 20, the GetStartIdx() method can
return a negative index if Page is 0. Add validation to check if Page is less
than 1 and return 0 in that case to prevent negative indices, ensuring the
method always returns a non-negative start index.

Comment thread common/page_info.go
}

if pageInfo.PageSize == 0 {
pageInfo.PageSize = ItemsPerPage

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

❌ Incorrect review comment

Fix the undefined constant reference.

The ItemsPerPage constant is referenced but not defined in this file or imported from the common package.


🏁 Script executed:

#!/bin/bash
# Description: Search for ItemsPerPage definition in the codebase
# Expected: Find where ItemsPerPage is defined

rg "ItemsPerPage.*=" -A 2 -B 2

Length of output: 215


Fix the undefined constant reference.

The ItemsPerPage constant is referenced but not defined in this file or imported from the common package.

#!/bin/bash
# Description: Search for ItemsPerPage definition in the codebase
# Expected: Find where ItemsPerPage is defined

rg "ItemsPerPage.*=" -A 2 -B 2
🤖 Prompt for AI Agents
In common/page_info.go at line 59, the constant ItemsPerPage is used but not
defined or imported. Locate the definition of ItemsPerPage in the codebase, then
either define it in this file or import it properly from the package where it is
declared. Ensure the constant is accessible in this file to fix the undefined
reference error.

Comment thread common/page_info.go
Comment on lines +58 to +61
if pageInfo.PageSize == 0 {
pageInfo.PageSize = ItemsPerPage
}
return pageInfo, nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add validation for PageSize.

There's no validation to prevent negative or excessively large PageSize values, which could cause performance issues or security concerns.

 	if pageInfo.PageSize == 0 {
 		pageInfo.PageSize = ItemsPerPage
+	} else if pageInfo.PageSize < 0 || pageInfo.PageSize > 1000 {
+		return nil, errors.New("invalid page_size: must be between 1 and 1000")
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if pageInfo.PageSize == 0 {
pageInfo.PageSize = ItemsPerPage
}
return pageInfo, nil
if pageInfo.PageSize == 0 {
pageInfo.PageSize = ItemsPerPage
} else if pageInfo.PageSize < 0 || pageInfo.PageSize > 1000 {
return nil, errors.New("invalid page_size: must be between 1 and 1000")
}
return pageInfo, nil
🤖 Prompt for AI Agents
In common/page_info.go around lines 58 to 61, add validation to ensure PageSize
is neither negative nor excessively large. Before setting the default PageSize,
check if PageSize is less than or equal to zero or exceeds a defined maximum
limit, and handle these cases by either setting it to a safe default or
returning an error. This prevents potential performance or security issues
caused by invalid PageSize values.

@xyfacai
xyfacai merged commit d389bef into QuantumNous:main Jun 27, 2025
x22x22 pushed a commit to x22x22/new-api that referenced this pull request Apr 24, 2026
jiutubaba pushed a commit to jiutubaba/fx-api that referenced this pull request May 17, 2026
The hardcoded codex CLI version (0.104.0) causes upstream rejection
when using gpt-5.5 with compact, as the server treats the request
as an outdated client and returns 400/502.

Update codexCLIVersion, codexCLIUserAgent, and openAICodexProbeVersion
to 0.125.0 to match the current Codex CLI release.

Fixes QuantumNous#1933, QuantumNous#1887, QuantumNous#1865
Related: QuantumNous#1609, QuantumNous#1298, QuantumNous#849
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