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

feat(openapi): custom openapi json serializer #246

Merged
merged 4 commits into from
Mar 15, 2025

Conversation

unnoq
Copy link
Owner

@unnoq unnoq commented Mar 15, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced the JSON serialization engine to support custom serialization strategies via configurable options.
    • Updated API handlers to accept these serializer options, allowing for more flexible data handling.
    • Added a new documentation section for "OpenAPI JSON Serializer" to guide users on customization.
    • Expanded the list of supported data types for both OpenAPIHandler and RPCHandler to include Record (object) and Array.
  • Tests

    • Added a comprehensive suite of unit tests covering built-in and custom data types, including edge case handling (e.g., undefined values), to ensure robust serialization behavior.

Copy link

vercel bot commented Mar 15, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
orpc ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 15, 2025 7:27am

Copy link

coderabbitai bot commented Mar 15, 2025

Walkthrough

This pull request introduces unit tests for the StandardOpenAPIJsonSerializer, enhancing its coverage for both built-in and custom data types. New interfaces for custom JSON serialization are added, and the serializer has been updated to accept custom serializer options. Additionally, the OpenAPIHandler modules in both the fetch and node adapters are modified to pass options to the serializer, and the StandardOpenAPIHandlerOptions interface is extended to include these JSON serializer options. Documentation is also updated to reflect these changes.

Changes

Files Change Summary
packages/openapi-client/.../openapi-json-serializer.ts
packages/openapi-client/.../openapi-json-serializer.test.ts
Added StandardOpenAPICustomJsonSerializer and StandardOpenAPIJsonSerializerOptions interfaces, updated StandardOpenAPIJsonSerializer to support custom serializers, and introduced comprehensive unit tests for built-in and custom data types.
packages/openapi/src/adapters/fetch/openapi-handler.ts
packages/openapi/src/adapters/node/openapi-handler.ts
Updated constructors to pass an options parameter to the StandardOpenAPIJsonSerializer, affecting its configuration.
packages/openapi/src/adapters/standard/openapi-handler.ts Extended the StandardOpenAPIHandlerOptions interface to inherit from StandardOpenAPIJsonSerializerOptions for added serialization capabilities.
apps/content/.vitepress/config.ts Added a new sidebar section titled "Advanced" with a link to the "OpenAPI JSON Serializer" documentation.
apps/content/docs/openapi/advanced/openapi-json-serializer.md Introduced documentation for the "OpenAPI JSON Serializer," detailing customization and providing examples.
packages/openapi/src/openapi-generator.ts Extended the OpenAPIGeneratorOptions interface to include StandardOpenAPIJsonSerializerOptions, modifying the constructor to accept these options.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Serializer as StandardOpenAPIJsonSerializer
    participant Custom as StandardOpenAPICustomJsonSerializer
    Client->>Serializer: serialize(data)
    Note right of Serializer: Iterate over customSerializers
    Serializer->>Custom: condition(data) check
    alt condition met
        Custom-->>Serializer: serialized data
    else condition not met
        Serializer-->>Serializer: default serialization
    end
    Serializer-->>Client: return serialized output
Loading

Possibly related PRs

Poem

I'm a rabbit, quick on my feet,
Hopping through code in a rhythmic beat.
Custom serializers now lead the way,
With tests that ensure the bytes won't stray.
I nibble on bugs and watch them flee,
CodeRabbit cheers this delightful spree!


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

pkg-pr-new bot commented Mar 15, 2025

Open in Stackblitz

More templates

@orpc/client

npm i https://pkg.pr.new/@orpc/client@246

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@246

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@246

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@246

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@246

@orpc/server

npm i https://pkg.pr.new/@orpc/server@246

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@246

@orpc/solid-query

npm i https://pkg.pr.new/@orpc/solid-query@246

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@246

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@246

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@246

@orpc/svelte-query

npm i https://pkg.pr.new/@orpc/svelte-query@246

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@246

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@246

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@246

commit: 2c797ff

Copy link

codecov bot commented Mar 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

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

🧹 Nitpick comments (5)
packages/openapi-client/src/adapters/standard/openapi-json-serializer.test.ts (1)

15-109: Thorough test coverage for built-in data types

Excellent test coverage for various data types including primitives, special values (NaN), dates, BigInt, RegExp, URL, objects, arrays, maps, sets, and binary data (Blob, File).

However, there's a commented section that could be removed or clarified.

-  //   {
-  //     data: undefined,
-  //     expected: expect.toSatisfy(v => v === null || v === undefined), CANNOT ASSERT UNDEFINED IN OBJECT?
-  //   },

The commented test case is addressed in the dedicated "serialize undefined" tests at the end of the file, so this commented code is no longer needed.

packages/openapi-client/src/adapters/standard/openapi-json-serializer.ts (4)

5-8: Good extensibility with custom serializer interface.

The StandardOpenAPICustomJsonSerializer interface provides a clean approach for extensible serialization logic. The separation of condition and serialize methods creates a clear pattern for determining which serializer should handle specific data types.

Consider using a generic type parameter instead of any in the serialize method signature to improve type safety:

export interface StandardOpenAPICustomJsonSerializer {
  condition(data: unknown): boolean
-  serialize(data: any): unknown
+  serialize<T>(data: T): unknown
}

22-28: Add protection against infinite recursion.

The recursive call to this.serialize with custom serializer output could potentially cause infinite recursion if a custom serializer's condition method matches its own output. Consider adding a simple depth counter or processed objects tracking mechanism.

Here's a potential implementation:

serialize(data: unknown, hasBlobRef: { value: boolean } = { value: false }, depth: number = 0): StandardOpenAPIJsonSerialized {
+  // Prevent infinite recursion
+  if (depth > 100) {
+    throw new Error('Maximum serialization depth exceeded. Possible circular structure or infinite recursion in custom serializers.');
+  }

  for (const custom of this.customSerializers) {
    if (custom.condition(data)) {
-      const result = this.serialize(custom.serialize(data), hasBlobRef)
+      const result = this.serialize(custom.serialize(data), hasBlobRef, depth + 1)

      return result
    }
  }
  
  // Rest of the method remains unchanged
}

22-28: Consider adding error handling for custom serializers.

If a custom serializer throws an exception, it would be helpful to include context about which serializer failed. This would make debugging easier for users who implement custom serializers.

for (const custom of this.customSerializers) {
  if (custom.condition(data)) {
+    try {
      const result = this.serialize(custom.serialize(data), hasBlobRef)
      return result
+    } catch (error) {
+      throw new Error(`Error in custom serializer: ${error instanceof Error ? error.message : String(error)}`);
+    }
  }
}

22-28: Document serializer precedence behavior.

The current implementation uses the first matching custom serializer based on array order. Consider adding a comment or documentation that explains this precedence behavior, so users understand how to order their custom serializers.

serialize(data: unknown, hasBlobRef: { value: boolean } = { value: false }): StandardOpenAPIJsonSerialized {
+  // Custom serializers are checked in order. The first one whose condition
+  // returns true will be used to process the data.
  for (const custom of this.customSerializers) {
    if (custom.condition(data)) {
      const result = this.serialize(custom.serialize(data), hasBlobRef)

      return result
    }
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5d6030b and 3141f6a.

📒 Files selected for processing (5)
  • packages/openapi-client/src/adapters/standard/openapi-json-serializer.test.ts (1 hunks)
  • packages/openapi-client/src/adapters/standard/openapi-json-serializer.ts (1 hunks)
  • packages/openapi/src/adapters/fetch/openapi-handler.ts (1 hunks)
  • packages/openapi/src/adapters/node/openapi-handler.ts (1 hunks)
  • packages/openapi/src/adapters/standard/openapi-handler.ts (1 hunks)
🔇 Additional comments (10)
packages/openapi/src/adapters/fetch/openapi-handler.ts (1)

16-16: Pass options to the serializer constructor

The change correctly passes the options parameter to the StandardOpenAPIJsonSerializer constructor, allowing customization of the JSON serialization process.

packages/openapi/src/adapters/node/openapi-handler.ts (1)

16-16: Pass options to the serializer constructor

The change correctly passes the options parameter to the StandardOpenAPIJsonSerializer constructor, ensuring consistent behavior between the fetch and node adapters.

packages/openapi/src/adapters/standard/openapi-handler.ts (2)

1-1: Add import for serializer options

The import for StandardOpenAPIJsonSerializerOptions is correctly added to support the interface extension.


5-5: Extend handler options with serializer options

The StandardOpenAPIHandlerOptions interface now properly extends StandardOpenAPIJsonSerializerOptions, allowing serialization options to be passed through the handler.

packages/openapi-client/src/adapters/standard/openapi-json-serializer.test.ts (4)

1-14: Well-structured test setup for JSON serializer

The initial test setup with TestCase type and Test enum provides a clear structure for the comprehensive test suite.


111-148: Good test setup for custom data types

The Person and Person2 classes with toJSON methods create a proper test fixture for verifying custom serialization support.


150-231: Comprehensive test scenarios with custom serializers

The test suite properly configures custom serializers and tests them against various data structures (flat, object, array, set, map, complex). The serializers are correctly registered using the new customJsonSerializers option.


233-249: Proper handling of undefined values

Good edge case testing for undefined values, confirming they're preserved in objects but converted to null in arrays, matching standard JSON.stringify behavior.

packages/openapi-client/src/adapters/standard/openapi-json-serializer.ts (2)

10-12: Well-designed options interface with immutability.

The StandardOpenAPIJsonSerializerOptions interface uses good practices with the readonly modifier for the array of custom serializers, promoting immutability. The interface is also extensible for future options.


15-19: Good implementation of constructor and private properties.

The private readonly property and the constructor using the nullish coalescing operator to provide defaults demonstrate clean code practices. The implementation properly initializes the custom serializers from the provided options.

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 comments (1)
apps/content/docs/rpc-handler.md (1)

60-60: ⚠️ Potential issue

Typo in Code Sample: Use startsWith

The sample code in the Setup and Integration section shows:

if (url.pathname.startWith('/rpc')) {

This appears to be a typo. It should be startsWith. A small correction is needed to ensure the documentation example is accurate.

Apply this diff:

-  if (url.pathname.startWith('/rpc')) {
+  if (url.pathname.startsWith('/rpc')) {
🧹 Nitpick comments (1)
apps/content/docs/openapi/openapi-handler.md (1)

23-24: New Supported Data Types Addition

The addition of Record (object) and Array to the list of supported types is clear and aligns with the new custom JSON serializer functionality. Ensure that these types are also correctly handled in the serializer implementation.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a7d8607 and 2c797ff.

📒 Files selected for processing (2)
  • apps/content/docs/openapi/openapi-handler.md (2 hunks)
  • apps/content/docs/rpc-handler.md (1 hunks)
🔇 Additional comments (3)
apps/content/docs/openapi/openapi-handler.md (1)

35-37: Addition of Custom Serializer Tip

The new tip block providing guidance to extend supported types via a custom serializer is well-formulated and consistent with similar documentation for other handlers. Double-check that the linked documentation (/docs/openapi/advanced/openapi-json-serializer#extending-native-data-types) is current.

apps/content/docs/rpc-handler.md (2)

27-28: New Supported Data Types Addition

The inclusion of Record (object) and Array in the list of native types is a valuable update that mirrors the changes in the OpenAPI documentation. This consistency reinforces the framework's expanded serialization capabilities.


35-37: Addition of Custom Serializer Tip

The tip block advising users on how to extend the list of supported types via a custom serializer has been added in a clear style. Confirm that the hyperlink (/docs/advanced/rpc-json-serializer#extending-native-data-types) is accurate and up-to-date.

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