Skip to content

Axios example#52

Merged
RawToast merged 2 commits intomasterfrom
even-more-examples
Dec 23, 2025
Merged

Axios example#52
RawToast merged 2 commits intomasterfrom
even-more-examples

Conversation

@RawToast
Copy link
Copy Markdown
Owner

@RawToast RawToast commented Dec 20, 2025

Summary by CodeRabbit

  • New Features

    • Added an Axios-based client for petstore API (list, create, retrieve pets).
  • Tests

    • Added comprehensive tests covering Axios client behaviors and error handling.
    • Updated test module imports to use path aliases.
  • Chores

    • Updated core dependencies to newer versions.
    • Added axios as a new dependency.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Dec 20, 2025

Walkthrough

Added an Axios-based Petstore client implementation and tests, upgraded several dependencies in the examples package (including adding axios), and converted multiple test imports from relative paths to alias-based paths.

Changes

Cohort / File(s) Change Summary
Dependency updates
packages/examples/package.json
Upgraded @effect/platform (0.93.3 → 0.93.8), @effect/platform-node (0.101.1 → 0.103.0), effect (3.19.6 → 3.19.12); added axios@1.13.2
Import path migrations (tests)
packages/examples/src/__tests__/*
packages/examples/src/__tests__/auth-client-fetch.test.ts, packages/examples/src/__tests__/enum-demo-client-fetch.test.ts, packages/examples/src/__tests__/petstore-client-fetch.test.ts, packages/examples/src/__tests__/petstore-client-ts-effect.test.ts, packages/examples/src/__tests__/petstore-client-undici.test.ts
Updated test imports from relative paths (e.g., ../...) to alias-based paths (e.g., ~/...)
New Axios client implementation
packages/examples/src/petstore-client-axios.ts
Added exported PetstoreClientAxios class with configurable base URL and Axios instance; implements listPets, createPets, showPetById; private overloaded request method with unified error parsing (API ErrorSchema vs HTTP errors) and safe JSON helpers
New Axios client tests
packages/examples/src/__tests__/petstore-client-axios.test.ts
Added comprehensive tests for PetstoreClientAxios: success and error cases for listPets, createPets, showPetById; includes an in-file AxiosLike interface and createAxiosTracker test helper to stub and inspect requests

Sequence Diagram(s)

sequenceDiagram
  participant Test as Test / Caller
  participant Client as PetstoreClientAxios
  participant Axios as AxiosInstance (requester)
  participant API as Petstore API

  Test->>Client: call listPets/createPets/showPetById(...)
  Client->>Axios: request(config)  %% color: `#9ad0f5` %%
  Axios->>API: HTTP request (GET/POST /pets or /pets/{id})
  API-->>Axios: HTTP 2xx with body OR non-2xx error body/status
  Axios-->>Client: response (status, headers, data)
  alt status 2xx and schema present
    Client->>Client: parse JSON, validate with Zod schema
    Client-->>Test: resolved typed data
  else non-2xx
    Client->>Client: try parse ErrorSchema from response
    alt parsed as API error
      Client-->>Test: throw API-specific error
    else
      Client-->>Test: throw generic HTTP error (status + statusText)
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Pay attention to:
    • packages/examples/src/petstore-client-axios.ts: overloaded request signatures, JSON parsing edge cases, and error-class construction from ErrorSchema.
    • packages/examples/src/__tests__/petstore-client-axios.test.ts: ensure the createAxiosTracker stubbing matches real Axios behavior (headers, status handling, body shapes).
    • packages/examples/package.json: confirm dependency upgrades and addition of axios don't conflict with workspace/tooling or other clients.

Poem

🐇 I hopped in code with whiskers twitching bright,

axios tucked in my paws, ready for flight.
Tests aligned like carrots in a row,
Imports rebounded — aliases on show.
A tiny rabbit cheers: new clients take flight!

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 (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Axios example' directly corresponds to the main changes in the PR, which adds a new PetstoreClientAxios class and comprehensive tests for Axios-based HTTP client functionality.
✨ 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 even-more-examples

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.

@codecov
Copy link
Copy Markdown

codecov bot commented Dec 20, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.48%. Comparing base (1f2383d) to head (a75185e).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master      #52   +/-   ##
=======================================
  Coverage   96.48%   96.48%           
=======================================
  Files          14       14           
  Lines        1622     1622           
=======================================
  Hits         1565     1565           
  Misses         57       57           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
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: 1

🧹 Nitpick comments (1)
packages/examples/src/petstore-client-axios.ts (1)

55-61: Consider using proper Axios types instead of type assertion.

The type assertion as unknown as AxiosJsonResponse on line 61 bypasses TypeScript's type checking and could be fragile. Consider importing and using Axios's built-in AxiosResponse type instead.

🔎 Proposed refactor

Update the import on line 2:

-import type { AxiosInstance, Method } from "axios"
+import type { AxiosInstance, AxiosResponse, Method } from "axios"

Update lines 13-17 and 55-61:

-type AxiosJsonResponse = {
-  status: number
-  statusText: string
-  data: unknown
-}
-
-    const response = (await this.requester.request({
+    const response = await this.requester.request<unknown>({
       url,
       method: options?.method,
       headers,
       data: options?.body,
       validateStatus: () => true,
-    })) as unknown as AxiosJsonResponse
+    })
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f2383d and 7c74b4f.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (8)
  • packages/examples/package.json (1 hunks)
  • packages/examples/src/__tests__/auth-client-fetch.test.ts (1 hunks)
  • packages/examples/src/__tests__/enum-demo-client-fetch.test.ts (1 hunks)
  • packages/examples/src/__tests__/petstore-client-axios.test.ts (1 hunks)
  • packages/examples/src/__tests__/petstore-client-fetch.test.ts (1 hunks)
  • packages/examples/src/__tests__/petstore-client-ts-effect.test.ts (1 hunks)
  • packages/examples/src/__tests__/petstore-client-undici.test.ts (1 hunks)
  • packages/examples/src/petstore-client-axios.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Organize imports in this order: built-in → third-party → local; always use double quotes
Use 2 spaces for indentation, no semicolons, trailing commas (ES5), 80 character line width
Use camelCase for variable and function names, PascalCase for class and type names
Prefer Result-style returns or descriptive throws for error handling

Files:

  • packages/examples/src/__tests__/auth-client-fetch.test.ts
  • packages/examples/src/petstore-client-axios.ts
  • packages/examples/src/__tests__/enum-demo-client-fetch.test.ts
  • packages/examples/src/__tests__/petstore-client-axios.test.ts
  • packages/examples/src/__tests__/petstore-client-ts-effect.test.ts
  • packages/examples/src/__tests__/petstore-client-undici.test.ts
  • packages/examples/src/__tests__/petstore-client-fetch.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Export inferred Zod types; keep strict TypeScript with noUncheckedIndexedAccess and noUnusedLocals enabled

Files:

  • packages/examples/src/__tests__/auth-client-fetch.test.ts
  • packages/examples/src/petstore-client-axios.ts
  • packages/examples/src/__tests__/enum-demo-client-fetch.test.ts
  • packages/examples/src/__tests__/petstore-client-axios.test.ts
  • packages/examples/src/__tests__/petstore-client-ts-effect.test.ts
  • packages/examples/src/__tests__/petstore-client-undici.test.ts
  • packages/examples/src/__tests__/petstore-client-fetch.test.ts
🧠 Learnings (1)
📚 Learning: 2025-12-16T13:51:25.042Z
Learnt from: CR
Repo: RawToast/zenko PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-16T13:51:25.042Z
Learning: Applies to packages/zenko/src/__tests__/**/*.{ts,tsx} : Test specs live in `packages/zenko/src/__tests__`; use snapshots for output verification

Applied to files:

  • packages/examples/src/__tests__/auth-client-fetch.test.ts
  • packages/examples/src/__tests__/enum-demo-client-fetch.test.ts
  • packages/examples/src/__tests__/petstore-client-axios.test.ts
  • packages/examples/src/__tests__/petstore-client-ts-effect.test.ts
  • packages/examples/src/__tests__/petstore-client-undici.test.ts
  • packages/examples/src/__tests__/petstore-client-fetch.test.ts
🧬 Code graph analysis (1)
packages/examples/src/__tests__/petstore-client-axios.test.ts (1)
packages/examples/src/petstore-client-axios.ts (1)
  • PetstoreClientAxios (19-102)
🔇 Additional comments (14)
packages/examples/src/__tests__/auth-client-fetch.test.ts (1)

2-2: LGTM! Import path updated to use alias.

The import path has been correctly updated from a relative path to an alias-based path, aligning with the module resolution pattern established across test files in this PR.

packages/examples/src/__tests__/enum-demo-client-fetch.test.ts (1)

2-2: LGTM! Import path updated to use alias.

The import path has been correctly updated to use the alias-based module resolution pattern.

packages/examples/src/__tests__/petstore-client-fetch.test.ts (1)

2-2: LGTM! Import path updated to use alias.

The import path has been correctly updated to use the alias-based module resolution pattern.

packages/examples/src/__tests__/petstore-client-undici.test.ts (1)

2-2: LGTM! Import path updated to use alias.

The import path has been correctly updated to use the alias-based module resolution pattern.

packages/examples/src/__tests__/petstore-client-ts-effect.test.ts (1)

9-9: LGTM! Import path updated to use alias.

The import path has been correctly updated to use the alias-based module resolution pattern.

packages/examples/src/__tests__/petstore-client-axios.test.ts (2)

7-125: Excellent test coverage!

The test suite comprehensively covers all public API methods (listPets, createPets, showPetById) with success cases, error scenarios, and edge cases. The mock tracker implementation is clean and follows the same pattern as other client tests.


128-151: Clean mock infrastructure.

The test helper types and tracker implementation provide a clean, effective way to mock Axios requests. The type assertion on line 150 is acceptable for test code where strict type safety can be relaxed for mocking purposes.

packages/examples/src/petstore-client-axios.ts (6)

1-3: LGTM! Clean imports with proper type safety.

Imports are well-organized and follow the coding guidelines: built-in → third-party → local. Good practice renaming Error to ErrorSchema to avoid collision with the global Error class.


5-17: Type definitions provide clean abstractions.

The internal type definitions appropriately abstract Axios types for this client's needs. The simplified ZodSchema<T> interface is a good example of duck typing for flexibility.


19-29: Well-designed constructor with dependency injection.

The constructor properly supports dependency injection for the AxiosInstance, making the client easily testable. The use of readonly fields prevents accidental mutation.


63-76: Robust error handling with appropriate fallbacks.

The two-tier error handling approach is well-designed: first attempting to parse structured API errors, then falling back to generic HTTP errors. The careful handling of statusText edge cases (trim, empty check) demonstrates attention to detail.


85-101: Clean public API methods with proper types.

The three public methods (listPets, createPets, showPetById) provide a clean, type-safe interface to the Petstore API. Each method properly delegates to the private request method with appropriate schemas and options.


104-121: Good defensive programming with safe JSON handling.

The safeJsonData and safeJsonParse helper functions provide robust handling of edge cases like empty strings and malformed JSON. While Axios typically handles JSON parsing automatically, these utilities add an extra layer of safety for unexpected data formats.

packages/examples/package.json (1)

21-21: No issues found. Axios version 1.13.2 is the current latest version published, and it is listed as the latest non-vulnerable version. The version number is legitimate and follows normal semantic versioning progression. No known security vulnerabilities affect this version.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
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: 0

🧹 Nitpick comments (1)
packages/examples/src/__tests__/petstore-client-axios.test.ts (1)

140-151: Consider stronger typing for the mock stub.

The as any cast on line 150 bypasses TypeScript's type checking. While this is common for test mocks, it reduces type safety and could hide incompatibilities between the mock and the actual AxiosInstance interface.

🔎 Options to improve type safety

Option 1: Type the stub more precisely to match the parts of AxiosInstance that PetstoreClientAxios actually uses:

-type AxiosLike = { request: (config: Record<string, any>) => Promise<any> }
+type AxiosLike = Pick<AxiosInstance, "request">

Then import AxiosInstance from axios at the top:

import type { AxiosInstance } from "axios"

Option 2: If you prefer to keep the mock lightweight without importing axios types, document why the cast is necessary:

-  return { calls, stub: stub as any }
+  // Cast to any because AxiosLike is a minimal test interface
+  // that doesn't match the full AxiosInstance type
+  return { calls, stub: stub as any }
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7c74b4f and a75185e.

📒 Files selected for processing (1)
  • packages/examples/src/__tests__/petstore-client-axios.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Organize imports in this order: built-in → third-party → local; always use double quotes
Use 2 spaces for indentation, no semicolons, trailing commas (ES5), 80 character line width
Use camelCase for variable and function names, PascalCase for class and type names
Prefer Result-style returns or descriptive throws for error handling

Files:

  • packages/examples/src/__tests__/petstore-client-axios.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Export inferred Zod types; keep strict TypeScript with noUncheckedIndexedAccess and noUnusedLocals enabled

Files:

  • packages/examples/src/__tests__/petstore-client-axios.test.ts
🧠 Learnings (1)
📚 Learning: 2025-12-16T13:51:25.042Z
Learnt from: CR
Repo: RawToast/zenko PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-16T13:51:25.042Z
Learning: Applies to packages/zenko/src/__tests__/**/*.{ts,tsx} : Test specs live in `packages/zenko/src/__tests__`; use snapshots for output verification

Applied to files:

  • packages/examples/src/__tests__/petstore-client-axios.test.ts
🧬 Code graph analysis (1)
packages/examples/src/__tests__/petstore-client-axios.test.ts (1)
packages/examples/src/petstore-client-axios.ts (1)
  • PetstoreClientAxios (19-102)
🔇 Additional comments (4)
packages/examples/src/__tests__/petstore-client-axios.test.ts (4)

1-2: LGTM! Import organization follows guidelines.

The imports are properly organized (built-in/third-party → local) with double quotes, and the alias import ~/petstore-client-axios is used for consistency with the established pattern.


29-112: LGTM! Comprehensive test coverage.

The test suite thoroughly covers:

  • Query parameter handling (limit)
  • Multiple HTTP methods (GET, POST)
  • Success scenarios with proper response parsing
  • Error handling for both structured API errors and raw HTTP errors
  • Various status codes (200, 201, 400, 422, 500, 404)

114-126: LGTM! Error handling is properly tested.

The not-found error case completes the error handling coverage for the showPetById method.


7-27: The test correctly validates the client's design. Since listPets() is a GET operation and the client intentionally omits the method field for default GET requests (relying on axios to default to GET), checking that method is undefined in the config is the expected behavior. No changes needed.

@RawToast RawToast merged commit 52d5f56 into master Dec 23, 2025
7 checks passed
@RawToast RawToast deleted the even-more-examples branch December 23, 2025 02:00
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