Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrating to modern axios lib for http request #107

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

suhaotian
Copy link

@suhaotian suhaotian commented Jan 29, 2025

From #105, I think xior.js is another good choice:

  • Xior size only 8kb (axios ~36KB)
  • Xior use fetch (axios support fetch since ^v1.7)

So I made this PR. Anything need change let me know, Thanks :)

Summary by CodeRabbit

  • Dependencies

    • Replaced axios library with xior for HTTP requests
    • Updated configuration to support the new HTTP client library
  • Code Changes

    • Migrated all HTTP request handling from axios to xior
    • Updated type definitions and method signatures to match new library
  • Testing

    • Modified test cases to work with the new HTTP client library

Copy link

coderabbitai bot commented Jan 29, 2025

Walkthrough

This pull request involves a comprehensive migration from the Axios HTTP client library to the Xior library across multiple project files. The changes include updating package dependencies, modifying import statements, adjusting type definitions, and reconfiguring build settings to replace Axios with Xior. The transition affects the HTTP request handling in the project's client-side REST implementation, with corresponding updates to test specifications and configuration files.

Changes

File Change Summary
package.json Removed axios@^1.7.7 dependency, added xior@^0.6.3
src/client/rest/APIRequester.ts Replaced Axios imports and types with Xior equivalents, updated method signatures
src/client/rest/APIRequester.spec.ts Updated test mocks and imports from Axios to Xior
vite.config.ts Modified external dependencies, replaced 'axios' with 'xior'

Sequence Diagram

sequenceDiagram
    participant Client
    participant APIRequester
    participant Xior
    Client->>APIRequester: Create request
    APIRequester->>Xior: Configure HTTP client
    APIRequester->>Xior: Send request
    Xior-->>APIRequester: Return response
    APIRequester-->>Client: Provide response data
Loading

Possibly related PRs

  • cleanse deps #73: Changes to package.json dependencies related to HTTP client libraries

Poem

🐰 Axios waves goodbye, Xior takes the stage,
HTTP requests dance on a brand new page.
Libraries swap with a magical leap,
Code transforms while developers sleep.
A rabbit's delight: smooth migration's art! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

Copy link

@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: 1

🧹 Nitpick comments (1)
src/client/rest/APIRequester.spec.ts (1)

22-22: Add tests for header manipulation.

The tests use empty headers objects, but we should add test cases for:

  1. Custom headers
  2. Multiple headers
  3. Case-insensitive header names
 it('accept a standard URL', async () => {
   mockedAxios.get.mockResolvedValueOnce({ data: null } as any)

   const request = new APIRequester('https://rest.testnet.initia.xyz')
-  await request.get('/foo')
+  await request.get('/foo', {}, { 'Content-Type': 'application/json' })

   expect(mockedAxios.get).toHaveBeenCalledWith(
     'https://rest.testnet.initia.xyz/foo',
     {
-      headers: {},
+      headers: { 'Content-Type': 'application/json' },
       params: {},
     }
   )
 })

+it('handles headers case-insensitively', async () => {
+  mockedAxios.get.mockResolvedValueOnce({ data: null } as any)
+
+  const request = new APIRequester('https://rest.testnet.initia.xyz')
+  await request.get('/foo', {}, {
+    'content-type': 'application/json',
+    'X-Custom-Header': 'value'
+  })
+
+  expect(mockedAxios.get).toHaveBeenCalledWith(
+    'https://rest.testnet.initia.xyz/foo',
+    {
+      headers: {
+        'content-type': 'application/json',
+        'X-Custom-Header': 'value'
+      },
+      params: {},
+    }
+  )
+})

Also applies to: 37-37, 52-52, 67-67

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d4e636d and dd4a065.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • package.json (1 hunks)
  • src/client/rest/APIRequester.spec.ts (2 hunks)
  • src/client/rest/APIRequester.ts (2 hunks)
  • vite.config.ts (1 hunks)
🔇 Additional comments (5)
package.json (1)

66-66: Verify xior package stability and security.

The migration to xior v0.6.3 (pre-1.0) requires careful consideration:

  1. The package is relatively new and pre-1.0, which may indicate potential API instability
  2. The small bundle size (8KB) is attractive, but we should verify that it doesn't compromise on features or security
✅ Verification successful

Migration to xior appears reasonable despite pre-1.0 status

The package shows good stability indicators:

  • Active maintenance with regular updates
  • Minimal, stable dependencies
  • Similar API to axios, reducing migration complexity
  • Edge runtime support and small bundle size (287.2 kB)
  • MIT licensed
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify xior package stability and security

# Check npm package details
echo "Checking npm package details..."
npm view xior time --json | jq '."modified"'
npm view xior versions --json

# Check GitHub activity
echo "Checking GitHub activity..."
gh api repos/galvez/xior --jq '.stargazers_count, .open_issues_count, .created_at, .updated_at, .pushed_at'

# Check for security advisories
echo "Checking for security advisories..."
npm audit xior

Length of output: 1479


Script:

#!/bin/bash
# Get more comprehensive package information
echo "Package details:"
npm view xior

echo -e "\nDownload statistics (last week):"
npm view xior downloads

echo -e "\nDependencies:"
npm view xior dependencies

echo -e "\nRepository and homepage:"
npm view xior repository.url homepage

Length of output: 1309

vite.config.ts (1)

19-19: LGTM!

Correctly added xior to external dependencies to prevent bundling.

src/client/rest/APIRequester.ts (3)

81-81: Verify headers handling compatibility.

The change from AxiosHeaders to Record<string, string> might affect header manipulation. Ensure that xior handles headers similarly to axios, especially for:

  1. Case-insensitive header names
  2. Multiple values for the same header

Line range hint 27-41: Verify HTTP client features compatibility.

Please ensure that xior supports all axios features being used:

  1. Base URL handling
  2. Timeout configuration
  3. Default headers
  4. Config merging
✅ Verification successful

All required axios features are supported by xior

The codebase demonstrates that xior is being used as a drop-in replacement for axios, with identical API patterns and full support for:

  • Base URL handling
  • Timeout configuration
  • Default headers
  • Config merging
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for axios-specific features in use

# Search for axios feature usage
echo "Searching for axios feature usage..."
rg -A 5 "axios\.(create|get|post|request|interceptors)"

# Search for timeout usage
echo "Searching for timeout configuration..."
rg -A 5 "timeout:|setTimeout"

Length of output: 4596


Script:

#!/bin/bash
# Search for xior related files and usage
echo "Searching for xior imports and usage..."
rg "from ['|\"]xior['|\"]|require\(['|\"]xior['|\"]\)"

echo "Searching for xior documentation files..."
fd -g "*xior*.md"

echo "Searching for xior configuration patterns..."
rg -A 5 "xior\.(create|configure|setup)"

Length of output: 516


Script:

#!/bin/bash
# View content of files using xior
echo "Content of APIRequester.ts:"
cat src/client/rest/APIRequester.ts

echo -e "\nContent of APIRequester.spec.ts:"
cat src/client/rest/APIRequester.spec.ts

echo -e "\nSearching for xior type definitions..."
fd -e d.ts -x cat {} \; | rg -A 10 "xior"

Length of output: 4842


1-4: Verify type compatibility between axios and xior.

The type aliases suggest API compatibility, but we should verify that xior's types match axios's behavior:

  • XiorInstanceAxiosInstance
  • XiorRequestConfigCreateAxiosDefaults
✅ Verification successful

Type compatibility between axios and xior is confirmed

The type aliases are correct and safe to use. This is verified by:

  • Xior is explicitly designed as an axios-compatible library
  • Test suite demonstrates identical API usage
  • TypeScript successfully compiles with the aliased types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Compare type definitions between axios and xior

# Find and compare type definitions
echo "Searching for axios type usage in codebase..."
rg -A 5 "AxiosInstance|CreateAxiosDefaults|AxiosHeaders" 

echo "Checking xior's type exports..."
rg -A 5 "export (type|interface) (XiorInstance|XiorRequestConfig)" 

Length of output: 1456


Script:

#!/bin/bash
# Check xior package on npm
echo "Checking xior package info..."
npm view xior

# Try to find any xior-related files
echo -e "\nSearching for xior-related files..."
fd xior

# Check for any xior imports or requires
echo -e "\nSearching for xior usage patterns..."
rg "from ['|\"]xior" --type ts
rg "require\(['|\"]xior" --type ts

Length of output: 1259


Script:

#!/bin/bash
# Check test file content
echo "Checking APIRequester test file..."
cat src/client/rest/APIRequester.spec.ts

# Look for any axios/xior related test assertions
echo -e "\nSearching for test assertions..."
rg -A 5 "describe|it|test|expect" src/client/rest/APIRequester.spec.ts

Length of output: 3796

Comment on lines +1 to +4
import axios from 'xior'
import { APIRequester } from './APIRequester'

jest.mock('axios')
jest.mock('xior')
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Test coverage needs improvement after axios to xior migration

The test suite is incomplete and needs additional test cases for:

  • POST method implementation
  • Error handling for invalid paths (path traversal)
  • Error handling for query params in endpoint
  • Headers functionality in GET requests
  • getRaw method functionality
🔗 Analysis chain

Verify test coverage for xior features.

The mock setup has been updated, but we should ensure:

  1. All xior features are properly mocked
  2. Test coverage is maintained
  3. Error scenarios are still tested
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage and error scenarios

# Search for test cases
echo "Searching for test cases..."
rg -A 5 "it\(|test\(|describe\(" src/client/rest/APIRequester.spec.ts

# Search for error handling tests
echo "Searching for error handling tests..."
rg -A 5 "throw|catch|error|fail" src/client/rest/APIRequester.spec.ts

Length of output: 1505


Script:

#!/bin/bash
# Check APIRequester implementation
echo "Checking APIRequester implementation..."
cat src/client/rest/APIRequester.ts

# Search for HTTP methods
echo -e "\nSearching for HTTP methods..."
rg "get\(|post\(|put\(|delete\(" src/client/rest/APIRequester.ts

Length of output: 3105

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.

1 participant