Skip to content

Conversation

oliver225
Copy link

@oliver225 oliver225 commented Aug 14, 2025

Description

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features
    • Added a configurable rule to determine when session re-authentication should run based on the response, not just status codes. This enables finer-grained control across diverse backends.
    • Introduced an option to enable or skip refresh per response, reducing unnecessary retry loops and improving stability.
    • Enhances user experience by minimizing unexpected logouts and surfacing errors more accurately when refresh is not appropriate.

Copy link

changeset-bot bot commented Aug 14, 2025

⚠️ No Changeset found

Latest commit: 62711d6

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link
Contributor

coderabbitai bot commented Aug 14, 2025

Walkthrough

Replaced a fixed 401-based re-authentication trigger in authenticateResponseInterceptor with a configurable predicate enableRefreshFunc(response). Updated the interceptor’s public signature to include this predicate and added the RequestResponse type import to support it.

Changes

Cohort / File(s) Summary of Changes
Request interceptor config update
packages/effects/request/src/request-client/preset-interceptors.ts
Added enableRefreshFunc(response: RequestResponse) to authenticateResponseInterceptor config and used it to gate refresh logic; removed hard-coded 401 check; imported RequestResponse type for the new predicate.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant Interceptor
    participant enableRefreshFunc
    participant AuthRefresh

    Caller->>Interceptor: handle response/error
    Interceptor->>enableRefreshFunc: evaluate(response)
    enableRefreshFunc-->>Interceptor: boolean
    alt enableRefreshFunc == false
        Interceptor-->>Caller: throw original error
    else enableRefreshFunc == true
        Interceptor->>AuthRefresh: perform refresh & retry
        AuthRefresh-->>Interceptor: retry result
        Interceptor-->>Caller: return retried response or error
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested reviewers

  • anncwb
  • mynetfan
  • jinmao88

Poem

A nibble of logic, a hop and a check,
No longer 401 on the deck—
I sniff the response, decide with care,
Refresh if needed, else leave it there.
Thump-thump! Configurable paths I tread,
Carrots of types for the journey ahead. 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@oliver225 oliver225 changed the title feat: axion request 根据外部函数判断是否需要刷新 feat: axiox request 根据外部函数判断是否需要刷新 Aug 14, 2025
@oliver225 oliver225 changed the title feat: axiox request 根据外部函数判断是否需要刷新 feat: axios request 根据外部函数判断是否需要刷新 Aug 14, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3cf0c0e and 62711d6.

📒 Files selected for processing (1)
  • packages/effects/request/src/request-client/preset-interceptors.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/effects/request/src/request-client/preset-interceptors.ts (1)
packages/effects/request/src/request-client/types.ts (2)
  • RequestResponse (79-79)
  • ResponseInterceptorConfig (80-80)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
🔇 Additional comments (1)
packages/effects/request/src/request-client/preset-interceptors.ts (1)

2-6: Importing RequestResponse type looks correct

Good addition; it aligns with the new predicate’s signature usage below.

Comment on lines +56 to 58
enableRefreshFunc,
formatToken,
}: {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make enableRefreshFunc optional with a safe default (preserve backward compatibility and avoid runtime errors)

Requiring callers to always provide enableRefreshFunc is a breaking change and risks a runtime TypeError if omitted. Also, a default of “status === 401” preserves prior behavior.

Apply this diff to make the predicate optional and provide a default:

 export const authenticateResponseInterceptor = ({
   client,
   doReAuthenticate,
   doRefreshToken,
   enableRefreshToken,
-  enableRefreshFunc,
+  enableRefreshFunc = (resp?: RequestResponse) => resp?.status === 401,
   formatToken,
 }: {
   client: RequestClient;
   doReAuthenticate: () => Promise<void>;
   doRefreshToken: () => Promise<string>;
   enableRefreshToken: boolean;
-  enableRefreshFunc: (response: RequestResponse) => boolean;
+  enableRefreshFunc?: (response?: RequestResponse) => boolean;
   formatToken: (token: string) => null | string;
 }): ResponseInterceptorConfig => {

Also applies to: 63-65

🤖 Prompt for AI Agents
In packages/effects/request/src/request-client/preset-interceptors.ts around
lines 56-58 (and similarly 63-65), the enableRefreshFunc parameter is currently
required; make it optional and supply a safe default predicate that preserves
prior behavior (status === 401). Update the function signature/destructuring to
provide a default value for enableRefreshFunc (e.g. enableRefreshFunc = (status)
=> status === 401) and adjust the type to be optional (or include the default in
the parameter type), ensuring all usages within the file call the predicate
safely without causing runtime errors when callers omit it.

Comment on lines +69 to 72
// 根据外部传入的函数判断是否需要 重新认证
if (!enableRefreshFunc(response)) {
throw error;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Guard against undefined error.response and canceled requests to prevent crashes

error.response can be undefined (e.g., network errors, CORS, aborts). Calling enableRefreshFunc(response) unguarded can throw. Also, skip refresh logic for canceled requests.

Apply this diff to make the check robust:

-      // 根据外部传入的函数判断是否需要 重新认证
-      if (!enableRefreshFunc(response)) {
+      // 根据外部传入的函数判断是否需要重新认证;对取消请求和无响应场景进行保护
+      if (axios.isCancel?.(error) || !response || !enableRefreshFunc(response)) {
         throw error;
       }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/effects/request/src/request-client/preset-interceptors.ts around
lines 69-72, the code calls enableRefreshFunc(response) without guarding against
error.response being undefined and without handling canceled requests; update
the logic to first detect canceled/aborted requests (e.g. error.code ===
'ERR_CANCELED' or use axios.isCancel(error) if axios is used) and immediately
rethrow in that case, then check that error.response exists before calling
enableRefreshFunc(response) and only invoke it when a response is present;
otherwise rethrow the original error.

@jinmao88
Copy link
Collaborator

有点破坏性更新的问题

@jinmao88 jinmao88 closed this Aug 28, 2025
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