Skip to content

feat(metagen): union/either for clients#857

Merged
Yohe-Am merged 1 commit intomainfrom
met-643-client-support-for-unions
Sep 26, 2024
Merged

feat(metagen): union/either for clients#857
Yohe-Am merged 1 commit intomainfrom
met-643-client-support-for-unions

Conversation

@Yohe-Am
Copy link
Copy Markdown
Contributor

@Yohe-Am Yohe-Am commented Sep 24, 2024

  • Add union support for the client_xx metagen implementations.

There are still some edge cases especially around variant identification in the client languages. I tried many things but our hands are tied by serde. Basically, users will have to be careful when designing their union types to avoid ambiguity cases. Hopefully, 674 will help there.

Migration notes

...

  • The change comes with new or modified tests
  • Hard-to-understand functions have explanatory comments
  • End-user documentation is updated to reflect the change

Summary by CodeRabbit

  • New Features

    • Introduced new methods for rendering union types in both TypeScript and Python.
    • Enhanced GraphQL query generation with support for multiple union types.
    • Added a new variants property to the NodeMeta type for improved selection handling.
  • Bug Fixes

    • Improved error handling for node selections and argument processing.
  • Tests

    • Updated test cases to reflect schema changes and added new tests for client functionality.

@Yohe-Am Yohe-Am requested a review from Natoandro September 24, 2024 20:33
@linear
Copy link
Copy Markdown

linear bot commented Sep 24, 2024

@Yohe-Am
Copy link
Copy Markdown
Contributor Author

Yohe-Am commented Sep 24, 2024

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Sep 24, 2024

Walkthrough

The changes introduce a new module in the project structure, enhance the handling of node selections and variants, and modify several functions across multiple files to accommodate new return types and parameters. Key updates include the addition of fields for managing named types, improvements in error handling, and the introduction of new methods for rendering union types in both Rust and TypeScript. Additionally, test cases have been updated to reflect these changes, ensuring comprehensive coverage of the new functionality.

Changes

Files Change Summary
Cargo.toml New member added: "src/metagen/src/client_rs/static" to the members array.
src/metagen/src/client_py/mod.rs Updated render_node_metas to return a tuple (NameMemo, HashSet<u32>). Adjusted render_client_py to handle the new return type and added logic for generating GraphQL type mappings for named types.
src/metagen/src/client_py/node_metas.rs Added named_types field to PyNodeMetasRenderer struct and implemented render_for_union method for union types. Modified RenderType implementation to collect named types.
src/metagen/src/client_py/selections.rs Introduced render_for_union method for rendering union types as TypedDict in Python, updated handling for TypeNode::Either and TypeNode::Union.
src/metagen/src/client_py/static/client.py Modified selection_to_nodes to change metas parameter type and updated logic for processing sub_nodes and variants. Enhanced error handling for composite nodes.
src/metagen/src/client_rs/static/client.rs Added selection_to_select_node function for processing node selections and improved error handling for node arguments.
src/metagen/src/client_ts/mod.rs Updated render_node_metas to return a tuple containing both NameMemo and HashSet<u32>.
src/metagen/src/client_ts/node_metas.rs Added named_types field to TsNodeMetasRenderer struct and implemented render_for_union method for union types.
src/metagen/src/client_ts/selections.rs Introduced render_for_union method for rendering TypeScript union types based on variants.
src/metagen/src/client_ts/static/mod.ts Added variants property to NodeMeta type and updated _selectionToNodeSet function to handle both subNodes and variants.
tests/metagen/metagen_test.ts Modified schema definition for compositeUnion2 and added a new test case for client_rs.
tests/metagen/typegraphs/sample.ts Activated union type declarations by uncommenting them.
tests/metagen/typegraphs/sample/py/client.py Updated selection_to_nodes function and modified NodeMeta class to include variants.
tests/metagen/typegraphs/sample/py/main.py Introduced a new GraphQL query (res5) that includes multiple union types.
tests/metagen/typegraphs/sample/rs/client.rs Enhanced selection handling in selection_to_node_set function and added new node metadata functions for unions.
tests/metagen/typegraphs/sample/rs/main.rs Updated the main function to construct a GraphQL query using new union types.
tests/metagen/typegraphs/sample/ts/client.ts Added variants property to NodeMeta type and updated selection handling in _selectionToNodeSet function.
tests/metagen/typegraphs/sample/ts/main.ts Introduced a new query operation (res5) that includes multiple union types.

Possibly related PRs

  • feat: well-defined type comparison semantics #846: The changes in this PR involve enhancements to type comparison semantics, which may relate to the new module added in the main PR that expands project structure and could involve type handling in Rust.

Suggested reviewers

  • michael-0acf4
  • zifeo

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

Outside diff range and nitpick comments (18)
tests/metagen/typegraphs/sample.ts (1)

Line range hint 67-73: Approved, but consider improving union type utilization.

The uncommented scalarUnion function successfully exposes the scalarUnion type in the API. However, the current implementation always returns a string ("hello"), which doesn't fully utilize the union type capabilities.

Consider modifying the function to return either a string or an integer based on some condition. For example:

scalarUnion: deno.func(
  t.struct({ id: t.string() }),
  scalarUnion,
  {
    code: ({ id }) => id.length % 2 === 0 ? "hello" : 42,
  },
),

This change would better demonstrate the union type's flexibility and ensure both possible return types are utilized.

tests/metagen/typegraphs/sample/rs/main.rs (2)

107-137: LGTM! New union type queries look good.

The implementation of new query operations for scalar_union, composite_union, and mixed_union aligns well with the PR objective of introducing union support. The code demonstrates proper use of the new union types and selection structures, providing good examples for different selection scenarios.

A few suggestions for improvement:

  1. Consider adding a brief comment explaining the purpose of the scalar_union query, similar to the comments for composite_union and mixed_union.
  2. The composite_union query is repeated twice with different selections. It might be beneficial to add a comment explaining why this repetition is necessary for testing purposes.

Line range hint 1-176: Overall implementation looks solid, addressing PR objectives.

The changes in this file successfully introduce union support for client implementations, aligning well with the PR objectives. The new query operations for scalar_union, composite_union, and mixed_union demonstrate proper use of the new union types and selection structures. The implementation provides good examples of different union selection scenarios, which is valuable for testing purposes.

A few points to consider:

  1. As mentioned in the PR objectives, there might be some edge cases concerning variant identification in client languages. It would be beneficial to add comments or tests specifically addressing these potential edge cases.
  2. The PR notes that end-user documentation has not yet been updated. Consider adding TODO comments in relevant sections to remind about updating the documentation once the implementation is finalized.
tests/metagen/metagen_test.ts (2)

610-614: LGTM: Improved command execution and output validation

The changes to the command execution logic enhance the test by actually running the command and validating its output. Parsing the output as JSON allows for more precise validation against the expected schema, which is a significant improvement.

Consider adding error handling for the JSON parsing step. For example:

let parsedOutput;
try {
  parsedOutput = JSON.parse(res);
} catch (error) {
  throw new Error(`Failed to parse command output as JSON: ${error.message}`);
}
expected.parse(parsedOutput);

This will provide more informative error messages if the command output is not valid JSON.


Line range hint 1-614: Overall assessment: Changes improve union type support and testing

The modifications in this file enhance the testing of union type support across different client implementations (Rust, TypeScript, and Python). The changes align well with the PR objectives and improve the overall test coverage.

Key improvements:

  1. Updated schema definition for compositeUnion2.
  2. New test case for the Rust client implementation.
  3. Enhanced command execution and output validation for all client tests.

To ensure the robustness of these changes:

  1. Verify that all union type scenarios are adequately covered in the tests.
  2. Ensure that the build and test processes for all client implementations (especially the new Rust client) are properly integrated into the CI/CD pipeline.
  3. Consider adding more detailed error handling and logging to facilitate debugging in case of test failures.

These changes provide a solid foundation for union type support in the metagen implementations. Great work on improving the test coverage and consistency across different client languages!

tests/metagen/typegraphs/sample/ts/main.ts (1)

85-113: Consider extracting the repeated ID into a constant for maintainability

The same ID string "94be5420-8c4a-4e67-b4f4-e1b2b54832a2" is used multiple times in your query definitions. Extracting it into a constant can improve maintainability and make future updates easier.

Apply this diff to extract the ID into a constant:

Add the following line above line 85:

+const commonId = "94be5420-8c4a-4e67-b4f4-e1b2b54832a2";

Then update the usages in lines 87, 90, 97, and 104:

tests/metagen/typegraphs/sample/py/main.py (2)

110-139: Enhancement: Define the repeated id as a constant

The id value "94be5420-8c4a-4e67-b4f4-e1b2b54832a2" is hardcoded multiple times in the new queries. Defining it as a constant improves readability and maintainability, especially if the value needs to change in the future.

Apply this diff to define a constant and use it throughout:

+TEST_ID = "94be5420-8c4a-4e67-b4f4-e1b2b54832a2"

 ...

 res5 = gql_client.query(
     {
         "scalarUnion": qg.scalar_union(
             {
-                "id": "94be5420-8c4a-4e67-b4f4-e1b2b54832a2",
+                "id": TEST_ID,
             }
         ),
         "compositeUnion1": qg.composite_union(
             {
-                "id": "94be5420-8c4a-4e67-b4f4-e1b2b54832a2",
+                "id": TEST_ID,
             },
             {"post": {"_": SelectionFlags(select_all=True)}},
         ),
         "compositeUnion2": qg.composite_union(
             {
-                "id": "94be5420-8c4a-4e67-b4f4-e1b2b54832a2",
+                "id": TEST_ID,
             },
             {"user": {"_": SelectionFlags(select_all=True)}},
         ),
         "mixedUnion": qg.mixed_union(
             {
-                "id": "94be5420-8c4a-4e67-b4f4-e1b2b54832a2",
+                "id": TEST_ID,
             },
             {
                 "post": {"_": SelectionFlags(select_all=True)},
                 "user": {"_": SelectionFlags(select_all=True)},
             },
         ),
     }
 )

110-139: Add comments to explain each new query for clarity

Adding comments before each query helps readers understand the purpose of the query and what it is testing, which is especially useful in test scripts.

Here's how you can add comments:

 res5 = gql_client.query(
     {
+        # Test scalar union with scalar return type
         "scalarUnion": qg.scalar_union(
             {
                 "id": TEST_ID,
             }
         ),
+        # Test composite union with 'post' selection
         "compositeUnion1": qg.composite_union(
             {
                 "id": TEST_ID,
             },
             {"post": {"_": SelectionFlags(select_all=True)}},
         ),
+        # Test composite union with 'user' selection
         "compositeUnion2": qg.composite_union(
             {
                 "id": TEST_ID,
             },
             {"user": {"_": SelectionFlags(select_all=True)}},
         ),
+        # Test mixed union with both 'post' and 'user' selections
         "mixedUnion": qg.mixed_union(
             {
                 "id": TEST_ID,
             },
             {
                 "post": {"_": SelectionFlags(select_all=True)},
                 "user": {"_": SelectionFlags(select_all=True)},
             },
         ),
     }
 )
src/metagen/src/client_ts/selections.rs (1)

68-70: Fix typos in comments

There are typos in the comments:

  • Line 69: "varaint" should be "variant"
  • Line 70: "normlalization" should be "normalization"
src/metagen/src/client_py/selections.rs (1)

135-157: Possible optimization: Collect variants without intermediate allocations

In the section where variants are collected for render_for_union, consider using iterator methods to avoid intermediate allocations, improving performance.

Refactor the code to:

let variants = variants
    .iter()
    .filter_map(|&inner| {
        if !renderer.is_composite(inner) {
            return None;
        }
        let ty_name = renderer.nodes[inner as usize].deref().base().title.clone();
        let struct_prop_name = normalize_struct_prop_name(&normalize_type_title(&ty_name));

        let selection = selection_for_field(
            inner,
            &self.arg_ty_names,
            renderer,
            cursor,
        ).ok()?;

        Some((struct_prop_name, (ty_name, selection)))
    })
    .collect::<IndexMap<_, _>>();
src/metagen/src/client_ts/mod.rs (1)

Line range hint 282-309: Handle potential panics when unwrapping Rc and Mutex

The use of Rc::try_unwrap(named_types).unwrap() and into_inner().unwrap() can lead to a panic if named_types has multiple strong references or if the Mutex is poisoned. To prevent potential panics, consider handling the Err cases explicitly instead of using unwrap().

Proposed code to handle errors gracefully:

Ok((
    memo,
    Rc::try_unwrap(named_types)
        .map_err(|_| anyhow::anyhow!("named_types has multiple references"))?
        .into_inner()
        .map_err(|e| anyhow::Error::new(e))?,
))

This modification uses map_err to convert potential Err cases into anyhow::Error, providing clearer error handling without panicking.

src/metagen/src/client_ts/static/mod.ts (3)

Line range hint 1-164: Consider refactoring _selectionToNodeSet for better maintainability

The _selectionToNodeSet function is becoming lengthy and complex, with multiple nested conditions and varying logic for handling subNodes and variants. This complexity can make the code harder to read, understand, and maintain. Consider refactoring the function by extracting parts of the logic into smaller helper functions. This would improve readability and make it easier to manage and test individual components of the code.


107-109: Clarify error message for invalid NodeMeta configuration

The error message when both subNodes and variants are defined states "unreachable: union/either NodeMetas can't have subnodes". The term "unreachable" might be misleading if this situation can occur due to incorrect usage. Consider rephrasing the error message to clearly indicate the issue to the developer, such as "Invalid NodeMeta: A NodeMeta cannot have both subNodes and variants defined."

Apply this diff to improve the error message:

107     throw new Error(
-108       "unreachable: union/either NodeMetas can't have subnodes",
+108       "Invalid NodeMeta: A NodeMeta cannot have both `subNodes` and `variants` defined.",
109     );

Line range hint 456-473: Enhance content-type check in fetchGql function

In the fetchGql function, the content-type check uses a strict equality to application/json. This may fail if the response includes additional parameters like charset (e.g., application/json; charset=utf-8). Consider updating the check to use .includes("application/json") for a more robust validation.

Apply this diff to improve the content-type check:

- if (res.headers.get("content-type") != "application/json") {
+ if (!res.headers.get("content-type")?.includes("application/json")) {
tests/metagen/typegraphs/sample/ts/client.ts (2)

385-385: Avoid Mutating Variables When Possible

The variable gqlTy is reassigned after removing nullability indicators. To maintain immutability and prevent potential side effects, consider using a new variable.

Suggested change:

- gqlTy = gqlTy.replace(/[!]+$/, "");
+ const baseGqlTy = gqlTy.replace(/[!]+$/, "");

And update the usage of gqlTy to baseGqlTy in the returned string:

return `... on ${baseGqlTy} {${ ... }}`;

931-954: Add Documentation for New Methods

The methods scalarUnion, compositeUnion, and mixedUnion lack documentation. Adding JSDoc comments will improve readability and help users understand their purpose and usage.

Consider adding JSDoc comments to these methods, detailing their parameters and return types.

src/metagen/src/client_rs/static/client.rs (2)

23-24: Improve documentation comment for clarity

In the documentation comment on lines 23-24, consider rephrasing "I.e." to "In other words," or "This means that" for better readability and clarity.


47-47: Correct typo in comment

The comment on line 47 contains a typo: "noe" should be corrected to "node".

Apply this diff to correct the typo:

-                // this noe was not selected
+                // this node was not selected
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 24eb721 and ac820c2.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (18)
  • Cargo.toml (1 hunks)
  • src/metagen/src/client_py/mod.rs (4 hunks)
  • src/metagen/src/client_py/node_metas.rs (5 hunks)
  • src/metagen/src/client_py/selections.rs (3 hunks)
  • src/metagen/src/client_py/static/client.py (10 hunks)
  • src/metagen/src/client_rs/static/client.rs (6 hunks)
  • src/metagen/src/client_ts/mod.rs (4 hunks)
  • src/metagen/src/client_ts/node_metas.rs (4 hunks)
  • src/metagen/src/client_ts/selections.rs (3 hunks)
  • src/metagen/src/client_ts/static/mod.ts (14 hunks)
  • tests/metagen/metagen_test.ts (2 hunks)
  • tests/metagen/typegraphs/sample.ts (3 hunks)
  • tests/metagen/typegraphs/sample/py/client.py (17 hunks)
  • tests/metagen/typegraphs/sample/py/main.py (1 hunks)
  • tests/metagen/typegraphs/sample/rs/client.rs (12 hunks)
  • tests/metagen/typegraphs/sample/rs/main.rs (2 hunks)
  • tests/metagen/typegraphs/sample/ts/client.ts (19 hunks)
  • tests/metagen/typegraphs/sample/ts/main.ts (1 hunks)
Additional context used
Ruff
src/metagen/src/client_py/static/client.py

383-383: Loop control variable node overrides iterable it iterates

(B020)

tests/metagen/typegraphs/sample/py/client.py

386-386: Loop control variable node overrides iterable it iterates

(B020)

Additional comments not posted (20)
tests/metagen/typegraphs/sample.ts (2)

37-38: LGTM: Union types activated as intended.

The uncommented declarations for compositeUnion and scalarUnion successfully activate these union types in the typegraph. This change aligns with the PR objective of introducing union support for client implementations. The types used in these unions are correctly defined or built-in, which is good.


Line range hint 37-87: Summary: Union support successfully implemented with room for optimization.

The changes successfully introduce union support for the client_xx metagen implementations as intended. The implementation is correct and functional, aligning well with the PR objectives. However, there are a few points to consider:

  1. The mixedUnion type combines composite and scalar types, which might lead to ambiguity in some cases. Exercise caution when designing such union types, as mentioned in the PR description.
  2. The scalarUnion function could be optimized to better utilize the full range of its union type.

These changes lay a solid foundation for union support, but keep in mind the potential edge cases mentioned in the PR description, particularly concerning variant identification in client languages. As the implementation progresses, it may be beneficial to update the end-user documentation to reflect these new capabilities and potential considerations when using union types.

Cargo.toml (1)

8-8: LGTM. Verify integration of the new module.

The addition of "src/metagen/src/client_rs/static" as a workspace member is consistent with the PR objectives for introducing union support in client metagen implementations. This change expands the project structure to include new Rust code for client-side static generation.

To ensure proper integration, please run the following verification script:

This script will help verify the existence of the new module, its basic structure, and its integration with other parts of the project.

tests/metagen/typegraphs/sample/rs/main.rs (1)

166-171: JSON output updated correctly.

The JSON output has been appropriately updated to include the results of the new union queries (scalarUnion, compositeUnion1, compositeUnion2, and mixedUnion). This change ensures that the results of all new query operations are properly captured and displayed in the output.

tests/metagen/metagen_test.ts (2)

571-571: LGTM: Schema change for compositeUnion2

The change from zod.undefined() to zod.object({}) for compositeUnion2 aligns with the PR objective of introducing union support. This modification allows compositeUnion2 to accept an empty object instead of undefined.

Please ensure that this change doesn't break any existing test cases and that it correctly handles empty objects in the union type validation.


578-583: LGTM: New test case for client_rs

The addition of the client_rs test case is a positive change that ensures the Rust client implementation is properly tested. It uses the same expectedSchema as other client implementations, maintaining consistency across different languages.

Please ensure that:

  1. The Rust client's build process is properly integrated with this test.
  2. The cargo run command executes successfully in the CI/CD pipeline.
  3. The test covers all the union type scenarios introduced in this PR.
tests/metagen/typegraphs/sample/ts/main.ts (1)

85-115: LGTM!

The new queries using union types are correctly implemented and effectively demonstrate the new functionality introduced in this PR.

tests/metagen/typegraphs/sample/py/main.py (1)

110-139: Verification: Confirm that union types are correctly used

Ensure that the union types scalar_union, composite_union, and mixed_union are being used correctly according to the GraphQL schema. Verify that the selections provided are valid for the possible types within each union.

Run the following script to list possible types for each union and ensure the selections match:

This script fetches the schema and lists the union types along with their possible types. Ensure that the selections in your queries correspond to these types.

src/metagen/src/client_py/selections.rs (1)

128-161: Ensure consistent handling of TypeNode::Either and TypeNode::Union variants

The logic for processing TypeNode::Either and TypeNode::Union filters out non-composite variants. However, if there are scalar variants, they are currently being ignored silently. This might lead to incomplete type definitions in the generated code.

Run the following script to check if there are any scalar variants in Either or Union types that might need handling:

src/metagen/src/client_ts/node_metas.rs (1)

92-120: render_for_union method implementation looks good

The new render_for_union method correctly constructs the union type rendering logic. The formatting and iteration over variants are well-implemented.

src/metagen/src/client_py/node_metas.rs (2)

61-64: Ensure correct string interpolation for return_node

At line 61, the code writes return_node = NodeDescs.{return_node}(). Verify that {return_node} is correctly interpolated with the actual return node name in the generated code. Ensure that the placeholder {return_node} is properly formatted and will be replaced as expected during code generation.


96-121: Verify correctness of the render_for_union method

The newly implemented render_for_union method appears to generate the Python code for union types. Ensure that the generated code has the correct syntax and indentation, and that all variants are properly included in the variants dictionary.

src/metagen/src/client_ts/mod.rs (1)

127-127: Confirm correct handling of new return type from render_node_metas

The function render_node_metas now returns a tuple (NameMemo, HashSet<u32>). The updated code correctly captures both node_metas and named_types. Ensure that all usages of render_node_metas are updated accordingly throughout the codebase.

Run the following script to verify all calls to render_node_metas handle the new return type:

Verification successful

All render_node_metas usages correctly handle the new return type

Verified that all calls to render_node_metas properly unpack the returned tuple (node_metas, named_types).

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all instances of `render_node_metas` and check for correct tuple unpacking.

# Expected: All calls should unpack the tuple returned by `render_node_metas`.
rg 'let\s+\(\s*[^)]+\s*\)\s*=\s*render_node_metas' --type rust

Length of output: 445

src/metagen/src/client_ts/static/mod.ts (2)

216-217: Consistency in NodeMeta type usage across the codebase

With the addition of the variants property to the NodeMeta type, ensure that all usages of NodeMeta throughout the codebase are updated accordingly. This includes places where NodeMeta is constructed or destructured, to prevent potential runtime errors or type mismatches.

Run the following script to find all usages of NodeMeta and check for necessary updates:

#!/bin/bash
# Description: Find all usages of 'NodeMeta' and verify updates.

# Search for 'NodeMeta' type references
rg --type ts 'NodeMeta' src/metagen/src/

# Optionally, check for destructuring assignments that may need updates
rg --type ts '{.*} =.*NodeMeta' src/metagen/src/

367-391: Ensure proper handling of subNodes in convertQueryNodeGql

The convertQueryNodeGql function now handles subNodes that can be either an array or a record of variants. Verify that when subNodes is a Record<string, SelectNode[]>, the generated GraphQL query correctly represents union types using inline fragments (... on Type { ... }).

Run the following script to check that union types are correctly transformed into GraphQL queries:

tests/metagen/typegraphs/sample/ts/client.ts (2)

731-735: Verify Argument Type Consistency

The argumentTypes for RootCompositeArgsFn specify id as "RootScalarNoArgsFnOutput", which appears to be an output type. Ensure that the argument type is correct and represents the expected input type.

Please check if RootScalarNoArgsFnOutput is the appropriate type for the id argument or if it should be something like UserIdStringUuid.


836-847: Ensure Accuracy of Union Type Definitions

The union types RootCompositeUnionFnOutput, RootMixedUnionFnOutput, and RootScalarUnionFnOutput combine various types. Confirm that all included types are correct and necessary for the intended functionality.

Review the union type definitions to ensure they represent all valid output types without including unintended ones.

tests/metagen/typegraphs/sample/py/client.py (1)

14-14: Simplified Parameter Type with NodeMetaFn

The parameter metas in the selection_to_nodes function is updated to use NodeMetaFn, which is an alias for typing.Callable[[], "NodeMeta"]. This change simplifies the type signature and enhances code readability.

src/metagen/src/client_rs/static/client.rs (2)

122-123: Re-evaluate the use of unreachable! macro

In lines 122-123, the code uses unreachable!("union/either node metas can't have sub_nodes"). Ensure that this case is truly impossible. If there's a possibility that both variants and sub_nodes are Some, consider handling it gracefully instead of panicking.


Line range hint 1057-1069: Check macro expansion for potential issues

In lines 1057-1069, the macro impl_union_selection_traits is being used. Ensure that the macro expansion correctly generates code without compilation errors, especially regarding the handling of CompositeSelection::Union.

Run the following script to examine the macro expansion:

#!/bin/bash
# Description: Expand macros in the Rust code to check for correctness.

# Test: Use `cargo expand` to see the expanded code for `impl_union_selection_traits`.
cargo expand --lib src/metagen/src/client_rs/static/client.rs | rg 'impl_union_selection_traits' -A 50

Review the expanded code to verify that it aligns with the intended implementation.

@Yohe-Am Yohe-Am merged commit 2b24598 into main Sep 26, 2024
@Yohe-Am Yohe-Am deleted the met-643-client-support-for-unions branch September 26, 2024 08:29
@coderabbitai coderabbitai bot mentioned this pull request Sep 26, 2024
3 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.

2 participants