Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Nov 7, 2025

Description

When a file download endpoint returns an error with application/json content-type, but the response data is a Blob (due to responseType configuration), JSONBigInt.parse() throws because it expects a string.

Changes:

  • Added typeof data === 'string' check before JSONBigInt.parse() in playground/src/api/request.ts
  • Non-string data (Blob, ArrayBuffer, etc.) now bypasses JSONBigInt parsing and returns as-is

Before:

transformResponse: (data: any, header: AxiosResponseHeaders) => {
  return header.getContentType()?.toString().includes('application/json')
    ? cloneDeep(JSONBigInt({ storeAsString: true, strict: true }).parse(data))
    : data;
}

After:

transformResponse: (data: any, header: AxiosResponseHeaders) => {
  if (
    header.getContentType()?.toString().includes('application/json') &&
    typeof data === 'string'
  ) {
    return cloneDeep(
      JSONBigInt({ storeAsString: true, strict: true }).parse(data),
    );
  }
  return data;
}

Type of change

  • 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

  • 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

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • cdnjs.cloudflare.com
  • registry.npmmirror.com
    • Triggering command: node /usr/local/bin/pnpm install (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Original prompt

This section details on the original issue you should resolve

<issue_title>Bug: 接口请求中json-bigint序列化导致报错</issue_title>
<issue_description>### Version

Vben Admin V5

Describe the bug?

场景:下载文件接口正常返回content-type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
,当接口异常时返回content-type:application/json; charset=utf-8的错误信息提示,但是此时data是Blob数据导致JSONBigInt对该数据做序列化处理报错。

文件:playground\src\api\request.ts

 const client = new RequestClient({
    ...options,
    baseURL,
    transformResponse: (data: any, header: AxiosResponseHeaders) => {
      // storeAsString指示将BigInt存储为字符串,设为false则会存储为内置的BigInt类型
      return header.getContentType()?.toString().includes('application/json')
        ? cloneDeep(
            JSONBigInt({ storeAsString: true, strict: true }).parse(data),
          )
        : data;
    },
  });

这里未对data对象进行类型判断,当data非string类型,JSONBigInt会报错。

Reproduction

建议加上data类型判断:

const client = new RequestClient({
    ...options,
    baseURL,
    transformResponse: (data: any, header: AxiosResponseHeaders) => {
      // storeAsString指示将BigInt存储为字符串,设为false则会存储为内置的BigInt类型
      if (
        header['content-type'].includes('application/json') &&
        typeof data === 'string'
      ) {
        return cloneDeep(
          JSONBigInt({ storeAsString: true, strict: true }).parse(data),
        );
      }
      return data;
    },
  });

System Info

win11

Relevant log output

Validations

Comments on the Issue (you are @copilot in this section)


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Summary by CodeRabbit

  • Bug Fixes
    • Improved API response handling by refining JSON parsing validation. The system now validates response content type and data format before processing, preventing potential parsing errors and enhancing reliability across different API response scenarios.

@changeset-bot
Copy link

changeset-bot bot commented Nov 7, 2025

⚠️ No Changeset found

Latest commit: 58b4d7e

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 7, 2025

Walkthrough

A type check is added to the transformResponse function to ensure JSONBigInt only parses string data when the response content-type is application/json, preventing serialization errors on non-string response bodies like Blob objects.

Changes

Cohort / File(s) Change Summary
JSONBigInt Type Validation
playground/src/api/request.ts
Added typeof data === 'string' check alongside content-type validation before applying JSONBigInt parsing to prevent errors when response body is non-string data (e.g., Blob)

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

  • Single file with minimal logic addition (one additional type guard condition)
  • Straightforward bug fix addressing a specific edge case
  • No architectural or behavioral complexity

Possibly related PRs

  • #6271: Modified transformResponse in the same file to apply cloneDeep and strict JSONBigInt parsing
  • #6250: Introduced JSONBigInt parsing for application/json responses in playground/src/api/request.ts

Suggested reviewers

  • mynetfan
  • anncwb
  • jinmao88
  • vince292007

Poem

🐰 A rabbit hops through response streams wide,
Adding a string check as safety guide,
No more Blob confusion, no parsing despair,
JSONBigInt now parses with proper care! 🎉

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main bug fix - preventing JSONBigInt parsing errors on non-string data, which is the primary change in this PR.
Description check ✅ Passed The PR description is comprehensive, providing context, code changes, and checklist completion. All major template sections are addressed with specific examples and status.
Linked Issues check ✅ Passed The code changes directly address issue #6889: adds typeof data === 'string' check before JSONBigInt.parse() in transformResponse logic, preventing errors when data is Blob/non-string with JSON content-type.
Out of Scope Changes check ✅ Passed All changes in playground/src/api/request.ts are directly related to fixing the JSONBigInt serialization error specified in issue #6889; no unrelated modifications detected.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch copilot/fix-json-bigint-serialization-error

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1e09fa4 and 58b4d7e.

📒 Files selected for processing (1)
  • playground/src/api/request.ts (1 hunks)
⏰ 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). (9)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Lint (ubuntu-latest)
  • GitHub Check: Check (windows-latest)
  • GitHub Check: Lint (windows-latest)
  • GitHub Check: Test (windows-latest)
  • GitHub Check: post-update (windows-latest)
  • GitHub Check: post-update (ubuntu-latest)
🔇 Additional comments (1)
playground/src/api/request.ts (1)

32-40: LGTM! The type guard correctly prevents JSONBigInt parsing errors on non-string data.

The fix properly addresses the issue where Blob or ArrayBuffer responses with application/json content-type would cause JSONBigInt.parse() to throw. By requiring typeof data === 'string', only actual JSON strings are parsed.

The .toString() call on line 33 is defensive but harmless—if getContentType() returns a string, it's redundant; if it returns undefined, the optional chaining prevents it from being reached.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

Co-authored-by: likui628 <90845831+likui628@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix JSONBigInt serialization error in API response fix: prevent JSONBigInt parsing error on non-string data Nov 7, 2025
Copilot AI requested a review from likui628 November 7, 2025 12:13
Copilot finished work on behalf of likui628 November 7, 2025 12:13
@likui628 likui628 marked this pull request as ready for review November 7, 2025 12:41
@likui628
Copy link
Collaborator

likui628 commented Nov 7, 2025

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 7, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

Bug: 接口请求中json-bigint序列化导致报错

2 participants