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

fix: parseEntities returns array instead of record<string, parsedenti… #382

Merged
merged 1 commit into from
Jan 25, 2025

Conversation

MartianGreed
Copy link
Collaborator

@MartianGreed MartianGreed commented Jan 25, 2025

…ty>

Closes #

Introduced changes

Checklist

  • Linked relevant issue
  • Updated relevant documentation
  • Added relevant tests
  • Add a dedicated CI job for new examples
  • Performed self-review of the code

Summary by CodeRabbit

  • New Features

    • Modified parseEntities function to return an array of parsed entities instead of an object
    • Updated TypeScript configuration to improve module resolution and import paths
  • Refactor

    • Simplified entity fetching logic in getEntities and getEventMessages functions
    • Streamlined parsing and return mechanisms for entity-related functions
  • Chores

    • Updated dependencies related to Dojo Engine SDK

Sorry, something went wrong.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
…ty<T>>
Copy link

coderabbitai bot commented Jan 25, 2025

Walkthrough

This pull request introduces a significant change to the parseEntities function, transforming its return type from a record with string keys to an array of parsed entities. The modification affects multiple files in the SDK, including getEntities.ts, getEventMessages.ts, and the corresponding test file. The changes simplify the entity parsing process by moving from an object-based representation to a more straightforward array format. Additionally, the TypeScript configuration for an example project has been updated to improve module resolution and path mapping.

Changes

File Change Summary
.changeset/curvy-queens-whisper.md Changelog entry for the parseEntities function return type modification
examples/.../tsconfig.json Updated module resolution configuration with baseUrl and paths options
packages/sdk/src/__tests__/parseEntities.test.ts Modified test expectations to match new array-based entity parsing
packages/sdk/src/getEntities.ts Simplified entity fetching logic, removing batch processing loop
packages/sdk/src/getEventMessages.ts Streamlined event message fetching with single-call approach
packages/sdk/src/parseEntities.ts Changed return type from Record<string, ParsedEntity> to ParsedEntity[]

Sequence Diagram

Loading
sequenceDiagram
    participant Client
    participant ParseEntities
    participant ToriiClient
    
    Client->>ToriiClient: Request Entities
    ToriiClient-->>ParseEntities: Return Raw Entities
    ParseEntities->>ParseEntities: Transform Entities
    ParseEntities-->>Client: Return Array of Parsed Entities

Possibly related PRs

Poem

🐰 Hop, hop, through the code we go,
From objects to arrays, watch entities flow!
No more keys to navigate with care,
Just a simple list, beyond compare.
SDK magic, with a rabbit's delight,
Parsing entities now feels just right! 🌟

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

Sorry, something went wrong.

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: 2

🧹 Nitpick comments (4)
packages/sdk/src/getEntities.ts (1)

49-57: Consider adding input validation for query parameters.

The toriiQuery construction could benefit from validation of the input parameters, especially for limit and offset, to ensure they are non-negative values.

+    if (limit < 0 || offset < 0) {
+        throw new Error('Limit and offset must be non-negative values');
+    }
+
     const toriiQuery: torii.Query = {
         limit,
         offset: cursor,
         order_by: orderBy,
         entity_models: entityModels,
         clause,
         dont_include_hashed_keys: dontIncludeHashedKeys,
         entity_updated_after: entityUpdatedAfter,
     };
packages/sdk/src/getEventMessages.ts (1)

61-83: Consider handling rate limits and retries.

The single fetch approach might be more susceptible to rate limiting or temporary network issues. Consider adding retry logic for resilience.

+    const MAX_RETRIES = 3;
+    const RETRY_DELAY = 1000; // ms
+
+    async function fetchWithRetry(attempt = 1): Promise<any> {
+        try {
+            return await client.getEventMessages(toriiQuery, historical);
+        } catch (error) {
+            if (attempt < MAX_RETRIES && error.message?.includes('rate limit')) {
+                await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
+                return fetchWithRetry(attempt + 1);
+            }
+            throw error;
+        }
+    }
+
     try {
-        const entities = await client.getEventMessages(toriiQuery, historical);
+        const entities = await fetchWithRetry();
packages/sdk/src/__tests__/parseEntities.test.ts (1)

225-227: Consider adding array bounds check.

While optional chaining handles undefined values, an explicit check for array length would make the tests more robust.

+    expect(res).toHaveLength(1);
     expect(res[0]?.models?.onchain_dash?.CallerCounter?.timestamp).toEqual(
         expected
     );

Also applies to: 279-279, 336-336

.changeset/curvy-queens-whisper.md (1)

16-16: Enhance the changeset description with migration guidance.

While the description clearly states the change, it would be helpful to include:

  1. Rationale for the change
  2. Migration guide for existing consumers
  3. Example of how to adapt existing code
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c842833 and b4dc1e2.

📒 Files selected for processing (6)
  • .changeset/curvy-queens-whisper.md (1 hunks)
  • examples/example-vite-react-phaser-recs/tsconfig.json (1 hunks)
  • packages/sdk/src/__tests__/parseEntities.test.ts (4 hunks)
  • packages/sdk/src/getEntities.ts (1 hunks)
  • packages/sdk/src/getEventMessages.ts (1 hunks)
  • packages/sdk/src/parseEntities.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check
  • GitHub Check: build
🔇 Additional comments (5)
packages/sdk/src/getEntities.ts (1)

59-80: Verify pagination behavior after removing batch fetching.

The removal of the batch fetching mechanism might affect the handling of large datasets. Ensure that:

  1. The client can handle the specified limit efficiently
  2. Upstream systems are aware of the change in pagination behavior
  3. Performance implications are understood for large result sets
✅ Verification successful

Pagination behavior verified after batch fetching removal

The pagination mechanism remains intact and properly implemented through limit/offset parameters. The removal of batch fetching doesn't affect the pagination behavior as it's handled at the query level through ToriiQueryBuilder. Large datasets are efficiently managed through the standard pagination interface.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for pagination-related code and comments
rg -A 3 'limit|offset|pagination' --type ts

Length of output: 29174

packages/sdk/src/getEventMessages.ts (1)

51-59: LGTM! Query construction is consistent with getEntities.

The toriiQuery construction follows the same pattern as in getEntities.ts, maintaining consistency across the codebase.

packages/sdk/src/parseEntities.ts (1)

55-55: Consider preserving entity order.

Object.values() doesn't guarantee order preservation. If order matters, consider using an array from the start or maintaining order explicitly.

packages/sdk/src/__tests__/parseEntities.test.ts (1)

143-186: LGTM! Test cases properly validate the new array-based structure.

The test expectations correctly reflect the change from object to array-based return type.

examples/example-vite-react-phaser-recs/tsconfig.json (1)

20-24: LGTM! Verify path alias compatibility with build system.

The TypeScript path alias configuration looks good and follows common practices. However, ensure that your build system (Vite) is configured to handle these aliases correctly.

Run this script to check if the path alias is properly configured in Vite:

✅ Verification successful

Path alias is properly configured in both TypeScript and Vite ✅

The path alias @ is correctly set up in both:

  • tsconfig.json: "@/*": ["./src/*"]
  • vite.config.ts: "@": path.resolve(__dirname, "./src")
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify Vite configuration includes the same path alias

# Search for path alias configuration in vite.config.ts
rg -l 'resolve.*alias.*@/' examples/example-vite-react-phaser-recs/vite.config.ts

if [ $? -ne 0 ]; then
  echo "Warning: Path alias might not be configured in Vite. Check vite.config.ts"
  echo "Add the following to vite.config.ts:"
  echo "resolve: { alias: { '@': '/src' } }"
fi

Length of output: 434


Script:

#!/bin/bash
# Check if vite.config.ts exists and show its content
if [ -f "examples/example-vite-react-phaser-recs/vite.config.ts" ]; then
    echo "vite.config.ts exists. Content:"
    cat examples/example-vite-react-phaser-recs/vite.config.ts
else
    echo "vite.config.ts not found"
    # Check for alternative config files
    fd -t f "vite.config" examples/example-vite-react-phaser-recs/
fi

Length of output: 660

@@ -8,7 +8,7 @@ export function parseEntities<T extends SchemaType>(
options?: { logging?: boolean }
): StandardizedQueryResult<T> {
// @ts-ignore
const result: StandardizedQueryResult<T> = entities;
const result: Record<string, ParsedEntity> = {};
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Type declaration mismatch with return type.

The function's return type is StandardizedQueryResult<T> but the implementation returns an array. This should be updated to match the new array-based return type.

-): StandardizedQueryResult<T> {
+): ParsedEntity<T>[] {

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

Comment on lines +2 to +13
"@dojoengine/sdk": patch
"template-vite-ts": patch
"@dojoengine/core": patch
"@dojoengine/create-burner": patch
"@dojoengine/create-dojo": patch
"@dojoengine/predeployed-connector": patch
"@dojoengine/react": patch
"@dojoengine/state": patch
"@dojoengine/torii-client": patch
"@dojoengine/torii-wasm": patch
"@dojoengine/utils": patch
"@dojoengine/utils-wasm": patch
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update version bump type to reflect breaking changes.

All packages are currently marked for patch updates, but changing the return type of parseEntities from Record<string, ParsedEntity<T>> to Array<ParsedEntity<T>> is a breaking change that will affect API consumers. This should be reflected in the version numbers.

Apply this diff to update the version bump type:

-"@dojoengine/sdk": patch
+"@dojoengine/sdk": major

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

@MartianGreed MartianGreed merged commit 0c5a6ec into main Jan 25, 2025
6 checks passed
@MartianGreed MartianGreed deleted the feat/experimental-events branch January 25, 2025 10:01
@coderabbitai coderabbitai bot mentioned this pull request Jan 27, 2025
5 tasks
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.

None yet

1 participant