Skip to content

feat: add order_by and entity_models to sdk #358

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

Merged
merged 3 commits into from
Dec 13, 2024
Merged

Conversation

MartianGreed
Copy link
Collaborator

@MartianGreed MartianGreed commented Dec 13, 2024

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

    • Enhanced querying capabilities for fetching entities and event messages with new optional parameters for ordering and model specification.
  • Bug Fixes

    • Improved error handling and logging mechanisms remain intact during the updates.
  • Documentation

    • Updated method signatures to reflect the addition of new parameters in the SDK functions.
  • Chores

    • Modified script in the package configuration to target specific directories for prettier checks.
  • Style

    • Transitioned from CommonJS to ES module syntax in Tailwind configuration files for improved interoperability.

Copy link

coderabbitai bot commented Dec 13, 2024

Walkthrough

The pull request introduces modifications to the package.json file and updates several functions in the SDK. The prettier-check script in package.json now targets specific directories instead of all files. Additionally, the getEntities and getEventMessages functions have been enhanced to accept two new optional parameters: orderBy and entityModels, which allow for more refined querying of entities. Corresponding changes are made in the SDK's initialization and type definitions to accommodate these new parameters.

Changes

File Change Summary
package.json Updated prettier-check script to target {packages,examples} instead of all files.
packages/sdk/src/getEntities.ts Modified getEntities function to accept orderBy and entityModels parameters, updating the query object.
packages/sdk/src/getEventMessages.ts Modified getEventMessages function to accept orderBy and entityModels parameters, updating the query object.
packages/sdk/src/index.ts Updated SDK initialization to pass orderBy and entityModels to getEntities and getEventMessages methods.
packages/sdk/src/types.ts Updated GetParams interface to include optional orderBy and entityModels properties.
worlds/dojo-starter Updated subproject commit hash to reflect a new state without functional changes.
examples/example-vite-react-app-recs/src/dojo/setup.ts Modified setup function to include new parameters in getSyncEntities and getSyncEvents calls, and updated publish method signature.
examples/example-vite-react-phaser-recs/tailwind.config.js Transitioned to ES module syntax, changing export and import statements.
examples/example-vite-react-threejs-recs/tailwind.config.js Transitioned to ES module syntax, changing export and import statements.

Possibly related PRs

🐇 In the code we hop and play,
New parameters brighten our day!
With order and models now in sight,
Fetching data feels just right.
Let's code and cheer, oh what a treat,
These changes make our work complete! 🎉


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. (Experiment)
  • @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: 0

🧹 Outside diff range and nitpick comments (5)
packages/sdk/src/getEventMessages.ts (1)

37-38: Update JSDoc documentation to include new parameters

The function's JSDoc comments should be updated to document the new orderBy and entityModels parameters.

Add the following to the JSDoc:

 * @param {T} schema - The schema type for the entities.
 * @param {(response: { data?: StandardizedQueryResult<T>; error?: Error }) => void} callback - The callback function to handle the response.
+* @param {torii.OrderBy[]} [orderBy=[]] - Optional array of ordering specifications.
+* @param {string[]} [entityModels=[]] - Optional array of entity model names to filter by.
 * @param {number} [limit=100] - The maximum number of event messages to fetch per request. Default is 100.
packages/sdk/src/getEntities.ts (1)

37-38: Update JSDoc documentation to include new parameters

The function's JSDoc comments should be updated to document the new orderBy and entityModels parameters.

Add the following to the JSDoc:

 * @param {QueryType<T>} query - The query object used to filter entities.
 * @param {(response: { data?: StandardizedQueryResult<T>; error?: Error }) => void} callback - The callback function to handle the response.
+* @param {torii.OrderBy[]} [orderBy=[]] - Optional array of ordering specifications.
+* @param {string[]} [entityModels=[]] - Optional array of entity model names to filter by.
 * @param {number} [limit=100] - The maximum number of entities to fetch per request. Default is 100.
packages/sdk/src/index.ts (2)

Line range hint 64-83: Update JSDoc for getEntities method

The method's documentation should be updated to reflect the new parameters.

Add parameter documentation in the JSDoc:

 * @param {GetParams<T>} params - Parameters object
+* @param {GetParams<T>} params.orderBy - Optional array of ordering specifications
+* @param {GetParams<T>} params.entityModels - Optional array of entity model names to filter by
 * @returns {Promise<StandardizedQueryResult<T>>} - A promise that resolves to the standardized query result.

Line range hint 90-109: Update JSDoc for getEventMessages method

The method's documentation should be updated to reflect the new parameters.

Add parameter documentation in the JSDoc:

 * @param {GetParams<T>} params - Parameters object
+* @param {GetParams<T>} params.orderBy - Optional array of ordering specifications
+* @param {GetParams<T>} params.entityModels - Optional array of entity model names to filter by
 * @returns {Promise<StandardizedQueryResult<T>>} - A promise that resolves to the standardized query result.
packages/sdk/src/types.ts (1)

369-372: Enhance documentation for new parameters

The new parameters would benefit from more detailed JSDoc documentation, including:

  • Examples of valid orderBy values
  • Format requirements for entityModels strings
  • Impact of these parameters on query results

Apply this diff to improve the documentation:

     error?: Error;
 }) => void;
-    // The order to sort the entities by.
+    /**
+     * Specifies the order in which entities should be sorted.
+     * @example
+     * orderBy: [
+     *   { field: "score", direction: "DESC" },
+     *   { field: "name", direction: "ASC" }
+     * ]
+     */
     orderBy?: torii.OrderBy[];
-    // The models to whitelist for fetching. Leave this empty to fetch all models.
+    /**
+     * Whitelist specific models for fetching. Format: "namespace.modelName"
+     * Leave empty to fetch all models.
+     * @example
+     * entityModels: ["world.Player", "world.Item"]
+     */
     entityModels?: string[];
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 424aa08 and 0c9cf79.

📒 Files selected for processing (5)
  • package.json (1 hunks)
  • packages/sdk/src/getEntities.ts (2 hunks)
  • packages/sdk/src/getEventMessages.ts (2 hunks)
  • packages/sdk/src/index.ts (2 hunks)
  • packages/sdk/src/types.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • package.json
🔇 Additional comments (4)
packages/sdk/src/getEventMessages.ts (1)

51-54: LGTM! Clean implementation of query parameters

The implementation correctly maps the new parameters to their corresponding query fields while maintaining the existing functionality.

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

51-54: LGTM! Consistent implementation with getEventMessages

The implementation maintains consistency with getEventMessages.ts, which is excellent for API uniformity.

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

Line range hint 64-109: LGTM! Clean and consistent SDK interface update

The SDK initialization correctly implements the new parameters and maintains consistency with the underlying functions.

Let's verify that the GetParams type has been updated to include the new parameters:

✅ Verification successful

GetParams interface correctly includes all required parameters

The GetParams interface definition perfectly aligns with the parameters used in both getEntities and getEventMessages functions, including:

  • Required parameters: query, callback
  • Optional parameters: orderBy, entityModels, limit, offset, options

All parameters are properly typed and documented with clear comments.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify GetParams type definition includes new parameters
rg -A 10 "interface GetParams" packages/sdk/src/types.ts

Length of output: 501


Script:

#!/bin/bash
# Let's see the complete GetParams interface definition to verify all parameters
rg -A 20 "interface GetParams" packages/sdk/src/types.ts

Length of output: 774

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

369-370: Verify the structure of OrderBy type

Let's verify that the torii.OrderBy type is properly defined and imported.

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

🧹 Outside diff range and nitpick comments (2)
examples/example-vite-react-app-recs/src/dojo/setup.ts (2)

32-33: Document the purpose of the new parameters and consider making them configurable.

The empty arrays passed to getSyncEntities (likely for orderBy and entityModels) lack documentation explaining their purpose. Additionally, consider making these parameters configurable through the config object instead of hardcoding empty arrays.

+ // Configuration for entity synchronization
+ const syncConfig = {
+   orderBy: config.syncOrderBy || [],
+   entityModels: config.syncEntityModels || [],
+   timeout: config.syncTimeout || 3000,
+   enableSync: config.enableSync ?? true
+ };

  const getSync = await getSyncEntities(
    toriiClient,
    contractComponents as any,
    undefined,
-   [],
-   [],
-   [],
-   3000,
-   true
+   syncConfig.orderBy,
+   syncConfig.entityModels,
+   [],  // TODO: Document the purpose of this parameter
+   syncConfig.timeout,
+   syncConfig.enableSync
  );

50-51: Apply consistent configuration pattern for event synchronization.

Similar to getSyncEntities, the empty arrays passed to getSyncEvents should be documented and made configurable through the config object for consistency.

+ // Configuration for event synchronization
+ const eventSyncConfig = {
+   orderBy: config.eventOrderBy || [],
+   entityModels: config.eventEntityModels || []
+ };

  const eventSync = getSyncEvents(
    toriiClient,
    contractComponents as any,
    undefined,
-   [],
-   [],
-   []
+   eventSyncConfig.orderBy,
+   eventSyncConfig.entityModels,
+   []  // TODO: Document the purpose of this parameter
  );
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 09a4237 and fec888c.

⛔ Files ignored due to path filters (3)
  • examples/example-vite-react-phaser-recs/src/dojo/generated/setup.ts is excluded by !**/generated/**
  • examples/example-vite-react-pwa-recs/src/dojo/generated/setup.ts is excluded by !**/generated/**
  • examples/example-vite-react-threejs-recs/src/dojo/generated/setup.ts is excluded by !**/generated/**
📒 Files selected for processing (3)
  • examples/example-vite-react-app-recs/src/dojo/setup.ts (2 hunks)
  • examples/example-vite-react-phaser-recs/tailwind.config.js (2 hunks)
  • examples/example-vite-react-threejs-recs/tailwind.config.js (2 hunks)
🔇 Additional comments (2)
examples/example-vite-react-threejs-recs/tailwind.config.js (1)

2-2: Same issues as in the Phaser example config

This file has the same incorrect plugin import syntax as discussed in the Phaser example's tailwind.config.js.

Please apply the same fixes as suggested in the previous file's review.

Also applies to: 76-76

examples/example-vite-react-app-recs/src/dojo/setup.ts (1)

88-89: Verify the removal of isSessionSignature parameter.

The publish method signature has been simplified by removing the isSessionSignature parameter. This could be a breaking change if other parts of the application rely on this parameter.

✅ Verification successful

Parameter removal is an intentional alignment with underlying API

Looking at the git diff, this is actually a safe change. The isSessionSignature parameter was being passed directly to toriiClient.publishMessage(), and the diff shows that the client method signature has been updated to match its underlying implementation. The parameter was optional (= false) and its removal appears to be part of a cleanup to match the actual API requirements.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing usage of the publish method with three parameters
rg -A 2 "publish\([^)]+,[^)]+,[^)]+\)" 

# Search for any references to isSessionSignature in the codebase
rg "isSessionSignature"

Length of output: 64


Script:

#!/bin/bash
# Let's try a broader search for publish method usage
rg -A 2 "\.publish\(" 

# Search for any files that might contain the old implementation
git diff HEAD~1 -- examples/example-vite-react-app-recs/src/dojo/setup.ts

# Let's also check for any test files that might use this method
fd "test|spec" --exec rg -l "publish"

Length of output: 2049

@@ -1,5 +1,5 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
export default {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Fix invalid plugin import syntax

The current changes introduce two issues:

  1. Using import() in the plugins array is incorrect as it returns a Promise, but Tailwind expects plugin instances
  2. Configuration files should use static imports for predictable initialization

Apply this fix:

+ import animate from "tailwindcss-animate";

/** @type {import('tailwindcss').Config} */
export default {
    // ... rest of config ...
-    plugins: [import("tailwindcss-animate")],
+    plugins: [animate],
};

Alternatively, if you need to maintain CommonJS compatibility:

/** @type {import('tailwindcss').Config} */
- export default {
+ module.exports = {
    // ... rest of config ...
-    plugins: [import("tailwindcss-animate")],
+    plugins: [require("tailwindcss-animate")],
};

Also applies to: 75-75

Comment on lines 31 to 34
[],
[],
[],
3000,
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving type safety and error handling.

  1. The contractComponents as any type assertion appears multiple times. Consider defining proper types to avoid using any.
  2. Error handling could be more robust for the sync operations, similar to how burner account initialization is handled.
+ try {
    const getSync = await getSyncEntities(
      toriiClient,
-     contractComponents as any,
+     contractComponents,
      // ... other parameters
    );
+ } catch (e) {
+   console.error("Failed to initialize entity sync:", e);
+   // Consider proper error recovery strategy
+ }

+ try {
    const eventSync = getSyncEvents(
      toriiClient,
-     contractComponents as any,
+     contractComponents,
      // ... other parameters
    );
+ } catch (e) {
+   console.error("Failed to initialize event sync:", e);
+   // Consider proper error recovery strategy
+ }

Also applies to: 49-52

@MartianGreed MartianGreed merged commit 12dc0a9 into main Dec 13, 2024
3 checks passed
@MartianGreed MartianGreed deleted the feat/torii-order-by branch December 13, 2024 16:04
This was referenced Dec 14, 2024
This was referenced Feb 13, 2025
@coderabbitai coderabbitai bot mentioned this pull request Mar 14, 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.

1 participant