Skip to content

refactor: update ApiClient to use a single registry URL and improve caching - #43

Merged
evilpeach merged 1 commit into
mainfrom
improve/reduce-fetching
Aug 4, 2025
Merged

refactor: update ApiClient to use a single registry URL and improve caching#43
evilpeach merged 1 commit into
mainfrom
improve/reduce-fetching

Conversation

@evilpeach

@evilpeach evilpeach commented Aug 3, 2025

Copy link
Copy Markdown
Collaborator
  • Changed DecoderConfig to accept a single registryUrl instead of an array.
  • Refactored ApiClient methods to utilize a new _fetchWithCache method for improved data fetching and caching.
  • Updated schema imports to use a unified schema object.
  • Adjusted methods to ensure proper handling of registry updates and resource fetching.
  • Enhanced error handling and logging for better debugging.

Summary by CodeRabbit

  • Refactor

    • Improved data fetching, parsing, and caching logic for more consistent and reliable performance.
    • Updated configuration to use a single registry URL instead of multiple URLs.
    • Standardized schema parsing for better maintainability.
    • Enhanced concurrency control when updating registries.
  • Style

    • Minor formatting and cleanup for improved code readability.
  • Tests

    • Updated test helpers to align with the new single registry URL configuration.

…aching

- Changed DecoderConfig to accept a single registryUrl instead of an array.
- Refactored ApiClient methods to utilize a new _fetchWithCache method for improved data fetching and caching.
- Updated schema imports to use a unified schema object.
- Adjusted methods to ensure proper handling of registry updates and resource fetching.
- Enhanced error handling and logging for better debugging.
@coderabbitai

coderabbitai Bot commented Aug 3, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes refactor the ApiClient class to centralize data fetching, parsing, and caching by introducing a unified _fetchWithCache method. Registry configuration is simplified from multiple URLs to a single URL across code, interfaces, and tests. Validator schema parsing is clarified by splitting response and transformed schemas. Minor formatting and test helper adjustments are included.

Changes

Cohort / File(s) Change Summary
ApiClient Refactor & Registry Handling
src/api.ts
Refactored ApiClient to use a single registryUrl property, introduced _fetchWithCache for unified fetching/parsing/caching, improved registry update concurrency, and standardized schema usage under the schema namespace.
DecoderConfig Interface Update
src/interfaces/common.ts
Changed DecoderConfig to use registryUrl: string instead of registryUrls: string[].
Validator Schema Refactor
src/schema/validators.ts
Split zValidator schema into zValidatorResponse and a transformed zValidator, clarifying response structure and transformation.
Test Helper Registry URL Update
src/tests/helpers/initialize.ts
Updated test helper to use registryUrl (string) instead of registryUrls (array), and changed default URLs to new test endpoints.
Formatting Cleanup
src/tests/helpers/api.ts
Added a blank line after a constant declaration for readability; no logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ApiClient
    participant Cache
    participant Axios
    participant SchemaParser

    Client->>ApiClient: call data-fetching method
    ApiClient->>Cache: check for cached data
    alt Cache hit and valid
        Cache-->>ApiClient: return cached data
        ApiClient-->>Client: return parsed data
    else Cache miss or invalid
        ApiClient->>Axios: fetch data from URL
        Axios-->>ApiClient: return raw data
        ApiClient->>SchemaParser: parse data
        SchemaParser-->>ApiClient: return parsed data
        ApiClient->>Cache: store parsed data
        ApiClient-->>Client: return parsed data
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Poem

In the warren, code hops anew,
Caches unified, fetches true!
One registry burrow—no more a crowd,
Validators parsed, the bunnies are proud.
With schemas neat and helpers bright,
This patch brings joy—oh what a sight!
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9984c09 and f52cc6c.

📒 Files selected for processing (5)
  • src/api.ts (9 hunks)
  • src/interfaces/common.ts (1 hunks)
  • src/schema/validators.ts (1 hunks)
  • src/tests/helpers/api.ts (1 hunks)
  • src/tests/helpers/initialize.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (8)
📚 Learning: in `src/client/rest/api/ibcapi.spec.ts`, the rest endpoint `https://rest.devnet.initia.xyz/` is acce...
Learnt from: joon9823
PR: initia-labs/initia.js#86
File: src/client/rest/api/IbcAPI.spec.ts:4-4
Timestamp: 2024-10-18T02:40:07.439Z
Learning: In `src/client/rest/api/IbcAPI.spec.ts`, the REST endpoint `https://rest.devnet.initia.xyz/` is acceptable even if it returns a 501 Not Implemented status code.

Applied to files:

  • src/tests/helpers/initialize.ts
  • src/api.ts
📚 Learning: the typescript types and zod schemas in `@initia/initia-registry-types` package are auto-generated f...
Learnt from: ALPAC-4
PR: initia-labs/initia-registry#274
File: _packages/types/src/zods/Profile.ts:12-17
Timestamp: 2025-02-06T07:15:46.189Z
Learning: The TypeScript types and Zod schemas in `@initia/initia-registry-types` package are auto-generated from JSON Schema files in the root directory. Modifications should be made to the schema files rather than the generated code.

Applied to files:

  • src/tests/helpers/initialize.ts
  • src/schema/validators.ts
  • src/api.ts
📚 Learning: in `frontend/helpers/address.ts`, the `bech32addresstohex` function is intentionally designed to thr...
Learnt from: Poafs1
PR: initia-labs/multisig#271
File: frontend/helpers/address.ts:13-14
Timestamp: 2025-07-11T05:29:26.096Z
Learning: In `frontend/helpers/address.ts`, the `bech32AddressToHex` function is intentionally designed to throw errors on invalid input instead of returning empty strings. This is a deliberate design choice that differs from the existing `bechAddressToHex` function's error handling behavior.

Applied to files:

  • src/tests/helpers/initialize.ts
📚 Learning: in `src/core/msg.ts`, within the `fromamino` function, the type identifiers for `msgupdateibcpermadm...
Learnt from: joon9823
PR: initia-labs/initia.js#81
File: src/core/Msg.ts:518-521
Timestamp: 2024-10-08T18:48:55.677Z
Learning: In `src/core/Msg.ts`, within the `fromAmino` function, the type identifiers for `MsgUpdateIbcPermAdmin` and `MsgUpdatePermissionedRelayers` should use the prefix `'ibc-perm/'` as the valid identifier.

Applied to files:

  • src/tests/helpers/initialize.ts
📚 Learning: the typescript types and zod schemas in `_packages/types/src/types/` and `_packages/types/src/zods/`...
Learnt from: ALPAC-4
PR: initia-labs/initia-registry#274
File: _packages/types/src/zods/Profile.ts:38-43
Timestamp: 2025-02-06T07:15:49.671Z
Learning: The TypeScript types and Zod schemas in `_packages/types/src/types/` and `_packages/types/src/zods/` are auto-generated from JSON Schema files in the root directory using json-schema-to-typescript and json-schema-to-zod libraries. Changes should be made to the source schema files, not the generated code.

Applied to files:

  • src/schema/validators.ts
  • src/api.ts
📚 Learning: in the tx-decoder project, zod is used for data validation at the input layer, which means direct pr...
Learnt from: evilpeach
PR: initia-labs/tx-decoder#28
File: src/metadata-resolver.ts:27-32
Timestamp: 2025-07-03T01:32:16.425Z
Learning: In the tx-decoder project, Zod is used for data validation at the input layer, which means direct property access is safe in functions like `resolveMetadata` since the data structure is already validated. Optional chaining is not needed in such cases.

Applied to files:

  • src/schema/validators.ts
📚 Learning: in src/object.ts, the getmetadata function's handling of the "move/" prefix does not require validat...
Learnt from: simcheolhwan
PR: initia-labs/utils#5
File: src/object.ts:29-33
Timestamp: 2025-07-31T06:49:39.162Z
Learning: In src/object.ts, the getMetadata function's handling of the "move/" prefix does not require validation of the remaining hex string. Client-side validation is unnecessary as the system likely handles validation at a different layer.

Applied to files:

  • src/api.ts
📚 Learning: in chain.json files, the `op_bridge_id` field in the metadata section should be a string type, not a...
Learnt from: ALPAC-4
PR: initia-labs/initia-registry#245
File: testnets/culinaris/chain.json:80-80
Timestamp: 2025-01-13T16:59:09.410Z
Learning: In chain.json files, the `op_bridge_id` field in the metadata section should be a string type, not an integer, as it represents the OPinit bridge identifier used for L1-L2 asset transfers.

Applied to files:

  • src/api.ts
🔇 Additional comments (11)
src/tests/helpers/api.ts (1)

34-34: Minor formatting change

src/interfaces/common.ts (1)

16-19: Breaking change: Interface modified from array to single string

This change from registryUrls: string[] to registryUrl: string is a breaking change to the public API. Ensure all consumers of this interface have been updated accordingly.

src/tests/helpers/initialize.ts (1)

4-8: Test helper correctly updated for new interface

The changes properly align with the new DecoderConfig interface, and the more descriptive test URLs improve clarity.

src/schema/validators.ts (1)

12-22: Good separation of API response and domain model schemas

Splitting the validator schema into zValidatorResponse and zValidator improves code organization by separating the API response structure from the domain model. The transformation appropriately flattens the nested structure.

src/api.ts (7)

4-12: Clean import organization using namespace pattern

The reorganization of imports with the schema namespace improves code clarity and prevents potential naming conflicts.


18-22: Good concurrency control for registry updates

The addition of registriesUpdatePromise prevents race conditions when multiple concurrent requests trigger registry updates.


156-178: Excellent centralization of fetch, parse, and cache logic

The _fetchWithCache method effectively consolidates the data fetching pattern across the codebase. The cache validation using the Zod parser and automatic cleanup of invalid entries ensures type safety and data integrity.


195-217: Well-implemented registry update with proper concurrency control

The _updateRegistries method effectively prevents concurrent registry fetches and includes appropriate error handling with fallback behavior.


45-58: Clean refactoring using centralized fetch method

The simplification using _fetchWithCache reduces code duplication and improves maintainability.


131-141: Correct usage of the new validator schema pattern

The method properly uses zValidatorResponse for parsing and returns the extracted validator object.


239-239: Consistent schema namespace usage

The updates maintain consistency with the schema namespace pattern throughout the codebase.

Also applies to: 254-254


🪧 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 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.

Comment thread src/api.ts
Comment thread src/api.ts
@evilpeach
evilpeach merged commit 4a18f1b into main Aug 4, 2025
2 checks passed
@evilpeach
evilpeach deleted the improve/reduce-fetching branch August 4, 2025 14:51
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