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: schema examples #149

Merged
merged 5 commits into from
Jan 10, 2025
Merged

feat: schema examples #149

merged 5 commits into from
Jan 10, 2025

Conversation

enzonotario
Copy link
Owner

Description

Allows to handle schema examples.

Related issues/external references

Closes #141

Types of changes

  • New feature

Copy link

vercel bot commented Jan 9, 2025

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

Name Status Preview Comments Updated (UTC)
vitepress-openapi ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 10, 2025 1:22am

Copy link
Contributor

coderabbitai bot commented Jan 9, 2025

Walkthrough

This pull request introduces comprehensive changes to handle multiple request body examples in the OpenAPI specification. The modifications span across multiple components, focusing on enhancing the documentation and user interface for displaying examples. The changes include updating the OpenAPI JSON file with concrete examples for artists and users, modifying Vue components to support example-based rendering, and introducing new utility functions for generating and managing schema examples.

Changes

File Change Summary
docs/public/openapi.json Added examples for artist and user schemas, including detailed request and response examples.
src/components/Path/OAPath.vue Introduced operationData and modified request body handling to use examples.
src/components/Playground/OAPlaygroundParameters.vue Removed schemaUiContentType, added examples prop.
src/components/Request/OARequestBody.vue Updated props passed to OASchemaTabs to use examples.
src/components/Response/OAResponse.vue Replaced schemaJson with examples computed property.
src/components/Schema/OASchemaTabs.vue Refactored to support dynamic example-based tab rendering.
src/lib/examples/getSchemaExample.ts New module for generating schema examples.
src/types.ts Added OAExampleObject type, removed uiContentType.

Assessment against linked issues

Objective Addressed Explanation
Multiple request body examples [#141]
Select element for switching examples Partial implementation, more UI work might be needed.

Possibly related PRs


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 514c763 and 9679f66.

📒 Files selected for processing (1)
  • src/components/Schema/OASchemaTabs.vue (4 hunks)
🔇 Additional comments (3)
src/components/Schema/OASchemaTabs.vue (3)

25-38: defaultValue computed property is clean and efficient

The refactored defaultValue logic enhances readability and maintains functionality. Good job on simplifying the nested conditionals.


55-57: Iteration over examples in TabsTrigger is correctly implemented

The v-for loop accurately iterates over props.examples, improving code clarity and efficiency.


74-77: Iteration over examples in TabsContent is correctly implemented

The v-for loop properly handles the rendering of each example, ensuring that all examples are displayed as intended.


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.

Copy link

pkg-pr-new bot commented Jan 9, 2025

Open in Stackblitz

npm i https://pkg.pr.new/vitepress-openapi@149

commit: 9679f66

Copy link
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: 10

🔭 Outside diff range comments (2)
docs/public/openapi.json (2)

Line range hint 107-154: Consider using environment-specific URLs.

The hardcoded CDN URLs (https://cdn.rock-legends.com) might need to be environment-specific.

Consider using environment variables or configuration to make the URLs configurable:

-                    "image": "https://cdn.rock-legends.com/photos/charly.jpg",
+                    "image": "{{% cdn_url %}}/photos/charly.jpg",

Line range hint 401-424: Consider security implications of example passwords.

The example passwords in the user signup examples might inadvertently suggest password patterns to users. Consider using more complex passwords in the examples to promote better security practices.

                 "Carlos": {
                   "value": {
                     "name": "Carlos",
                     "email": "carlos@rock-legends.com",
-                    "password": "i-love-rock"
+                    "password": "P@ssw0rd!2024#Complex"
                   }
                 },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b79af0 and 07f6df4.

⛔ Files ignored due to path filters (1)
  • test/lib/__snapshots__/processOpenAPI.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (15)
  • docs/public/openapi.json (2 hunks)
  • src/components/Path/OAPath.vue (2 hunks)
  • src/components/Playground/OAPlaygroundParameters.vue (2 hunks)
  • src/components/Request/OARequestBody.vue (1 hunks)
  • src/components/Response/OAResponse.vue (2 hunks)
  • src/components/Schema/OASchemaTabs.vue (4 hunks)
  • src/components/Try/OATryWithVariables.vue (2 hunks)
  • src/composables/useTheme.ts (4 hunks)
  • src/lib/examples/getSchemaExample.ts (1 hunks)
  • src/lib/examples/getSchemaUiJson.ts (1 hunks)
  • src/lib/examples/getSchemaUiXml.ts (1 hunks)
  • src/lib/getSchemaUiContentType.ts (0 hunks)
  • src/lib/processOpenAPI.ts (3 hunks)
  • src/types.ts (1 hunks)
  • test/lib/getSchemaUi.test.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • src/lib/getSchemaUiContentType.ts
🧰 Additional context used
🪛 eslint
src/lib/examples/getSchemaUiJson.ts

[error] 1-1: 'OpenAPI' is defined but never used.

(unused-imports/no-unused-imports)

🔇 Additional comments (15)
src/components/Request/OARequestBody.vue (1)

25-25: LGTM! Clean prop update for schema examples support

The change correctly updates the OASchemaTabs component to use the new examples prop, maintaining proper optional chaining for type safety.

src/types.ts (1)

70-72: LGTM! Clean type definition for example objects

The OAExampleObject type correctly extends the OpenAPI type with an optional flag for auto-generated examples.

src/components/Response/OAResponse.vue (1)

38-38: LGTM! Consistent implementation of schema examples

The changes correctly implement the new examples feature:

  • Computed property properly derives examples from the content
  • OASchemaTabs component receives the examples prop consistently

Also applies to: 88-88

src/components/Try/OATryWithVariables.vue (2)

63-64: LGTM! Clean implementation of examples extraction.

The computed property correctly extracts examples from the request body content based on the content type.


76-76: LGTM! Clean prop updates.

The changes correctly update the component to use the new examples-based approach:

  1. hasParameters now checks for body presence using hasBody
  2. Template correctly passes examples to child component

Also applies to: 90-90

src/components/Schema/OASchemaTabs.vue (1)

Line range hint 76-95: LGTM! Well-structured example content rendering.

The template correctly handles:

  1. Optional example description with markdown
  2. Example value with proper language highlighting
  3. Fallback to 'json' for language
src/lib/examples/getSchemaUiJson.ts (1)

7-8: LGTM! Clean extraction of JSON conversion logic.

The new schemaUiToJson function:

  1. Correctly handles both array and single property cases
  2. Maintains the existing functionality while improving code organization

Also applies to: 10-15

src/components/Playground/OAPlaygroundParameters.vue (2)

45-48: LGTM! New examples prop added.

The new examples prop is correctly defined as an optional object property.


87-87: Verify null safety in body initialization.

The body initialization uses optional chaining, but there might be edge cases where props.examples is an empty object. Consider adding a type guard or default value for better null safety.

src/components/Path/OAPath.vue (1)

26-28: LGTM! Operation data initialization.

The operation data is correctly initialized and provided to child components.

src/composables/useTheme.ts (1)

23-23: LGTM! Type definitions updated consistently.

The 'autogenerated' option has been added consistently across all relevant type definitions.

Also applies to: 123-123, 233-233

test/lib/getSchemaUi.test.ts (1)

5-5: LGTM! Import statement updated.

The import has been correctly updated to use the new getSchemaExample function.

src/lib/examples/getSchemaUiXml.ts (1)

2-2: Verify the import path for OAProperty type.

Let's ensure the new import path is correct and the file exists.

✅ Verification successful

Import path for OAProperty is correct

The import path '../getSchemaUi' is valid and consistently used across multiple files in the examples directory.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of getSchemaUi.ts in the parent directory
# and check for any other files importing OAProperty

# Check if the file exists
fd --type f "getSchemaUi.ts" src/lib

# Check for other imports of OAProperty to ensure consistency
rg --type ts "import.*OAProperty.*from" src/

Length of output: 361

docs/public/openapi.json (2)

107-123: LGTM! Well-structured examples for artist creation.

The examples are meaningful, follow the schema requirements, and provide good coverage of the API's capabilities. Both examples use HTTPS for image URLs and include all required fields.


136-154: LGTM! Response examples maintain consistency with request examples.

The response examples correctly include the additional id field and maintain consistency with the request examples.

Copy link
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: 3

🔭 Outside diff range comments (1)
src/lib/examples/getSchemaUiJson.ts (1)

Line range hint 9-92: Enhance type safety and input validation throughout the module.

Several functions lack explicit return types and input validation, which could lead to type-related issues.

  • Specify return types for functions, e.g.:

    -function uiPropertyToJson(property: OAProperty, useExample: boolean): any {
    +function uiPropertyToJson(property: OAProperty, useExample: boolean): unknown {
  • Add input validation where necessary to prevent runtime errors.

Implementing these changes will improve the robustness and maintainability of the code.

♻️ Duplicate comments (3)
src/components/Schema/OASchemaTabs.vue (1)

13-15: 🧹 Nitpick (assertive)

Consider adding type safety for the examples prop.

The current type: null allows any type, which could lead to runtime errors. Defining a specific type enhances type safety and maintainability.

You can apply this diff to add type safety:

+import { PropType } from 'vue'

 examples: {
-  type: null,
+  type: Object as PropType<Record<string, {
+    description?: string;
+    value?: any;
+    lang?: string;
+    isAutogenerated?: boolean;
+  }>>,
   required: false,
+  default: () => ({}),
 },
src/lib/examples/getSchemaExample.ts (2)

18-34: 🧹 Nitpick (assertive)

Add input validation for uiProperties to prevent runtime errors.

The function getSchemaExampleValue lacks validation for the uiProperties parameter, which could lead to runtime errors if uiProperties is null or undefined.

Consider adding validation at the start of the function:

 function getSchemaExampleValue(contentType: string, uiProperties: OAProperty[] | OAProperty, useExample = false): OAExampleObject {
+  if (!uiProperties) {
+    throw new Error('uiProperties is required')
+  }

   if (isXml(contentType)) {
     return {
       summary: 'XML',
       description: '',
       value: getSchemaUiXml(uiProperties, useExample),
       isAutogenerated: true,
     } as OAExampleObject
   }

   return {
     summary: 'JSON',
     description: '',
     value: getSchemaUiJson(uiProperties, useExample),
     isAutogenerated: true,
   } as OAExampleObject
 }

This ensures that the function handles invalid inputs gracefully.


36-38: 🧹 Nitpick (assertive)

Enhance the XML content type detection with a more precise regular expression.

The current regular expression could match unintended content types. Refining it improves accuracy.

Update the isXml function as follows:

 function isXml(contentType: string): boolean {
-  return contentType.toLowerCase().match(/^(text|application)\/.*xml($|;|\\+)/) !== null
+  return /^(application|text)\/(.+\+)?xml(;.*)?$/i.test(contentType)
 }

This regex matches content types like application/xml and application/atom+xml, providing more precise detection.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 07f6df4 and 514c763.

📒 Files selected for processing (3)
  • src/components/Schema/OASchemaTabs.vue (4 hunks)
  • src/lib/examples/getSchemaExample.ts (1 hunks)
  • src/lib/examples/getSchemaUiJson.ts (1 hunks)
🔇 Additional comments (1)
src/components/Schema/OASchemaTabs.vue (1)

25-38: 🧹 Nitpick (assertive)

Simplify the defaultValue computed property for clarity.

The defaultValue logic can be further simplified to improve readability by avoiding the use of an immediately invoked function expression (IIFE) within the viewMap.

Consider refactoring as follows:

 const defaultValue = computed(() => {
   const defaultView = themeConfig.schemaConfig.defaultView.value
   const examplesKeys = Object.keys(props.examples ?? {})

-  const viewMap = {
+  if (defaultView === 'schema') {
+    return 'schema'
+  } else if (defaultView === 'contentType') {
+    return examplesKeys.length ? `examples.${examplesKeys[0]}` : 'schema'
+  } else if (defaultView === 'autogenerated') {
+    const autogeneratedExample = examplesKeys.find(
+      key => props.examples[key]?.isAutogenerated
+    )
+    return autogeneratedExample ? `examples.${autogeneratedExample}` : 'schema'
+  } else {
+    return defaultView
+  }
 })

This refactoring enhances readability by using straightforward conditional statements.

Likely invalid or redundant comment.

@enzonotario enzonotario merged commit 1c0bd0e into develop Jan 10, 2025
6 checks passed
@enzonotario enzonotario deleted the feature/multiple-examples branch January 23, 2025 13:59
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