Repository: enzonotario/vitepress-openapi
Pull request #75 (2024-10-08 22:06:50)

feat(schemas): handle schemas with content types
<!-- Provide a general summary of your changes in the title above. -->

# Description

Allows to handle schema with ContentTypes.

## Related issues/external references


## Types of changes

- New feature


vercel[bot]: [vc]: #TKXBL/vuKy8ExgkLwK5PZZjSyxGgzXfpbcFMGsHRl1M=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJ2aXRlcHJlc3Mtb3BlbmFwaSIsImxpdmVGZWVkYmFjayI6eyJyZXNvbHZlZCI6MCwidW5yZXNvbHZlZCI6MCwidG90YWwiOjAsImxpbmsiOiJ2aXRlcHJlc3Mtb3BlbmFwaS1naXQtZmVhdHVyZS1zY2hlbWEtZW56by1ub3Rhcmlvcy1wcm9qZWN0cy52ZXJjZWwuYXBwIn0sImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS9lbnpvLW5vdGFyaW9zLXByb2plY3RzL3ZpdGVwcmVzcy1vcGVuYXBpL21wV3JFNDdIQXhpcEZ1SlE5akxBRFpHRDN5Q0MiLCJwcmV2aWV3VXJsIjoidml0ZXByZXNzLW9wZW5hcGktZ2l0LWZlYXR1cmUtc2NoZW1hLWVuem8tbm90YXJpb3MtcHJvamVjdHMudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJERVBMT1lFRCJ9XX0=
**The latest updates on your projects**. Learn more about [Vercel for Git ↗︎](https://vercel.link/github-learn-more)

| Name | Status | Preview | Comments | Updated (UTC) |
| :--- | :----- | :------ | :------- | :------ |
| **vitepress-openapi** | ✅ Ready ([Inspect](https://vercel.com/enzo-notarios-projects/vitepress-openapi/mpWrE47HAxipFuJQ9jLADZGD3yCC)) | [Visit Preview](https://vercel.live/open-feedback/vitepress-openapi-git-feature-schema-enzo-notarios-projects.vercel.app?via=pr-comment-visit-preview-link&passThrough=1) | 💬 [**Add feedback**](https://vercel.live/open-feedback/vitepress-openapi-git-feature-schema-enzo-notarios-projects.vercel.app?via=pr-comment-feedback-link) | Oct 8, 2024 10:06pm |


pkg-pr-new[bot]: 
[Open in Stackblitz](https://pkg.pr.new/template/1251cc29-c862-4cc0-9c6a-5e7784511b31)


```
pnpm add https://pkg.pr.new/vitepress-openapi@75
```


```
pnpm add https://pkg.pr.new/vitepress-openapi@75
```


_commit: <a href="https://github.com/enzonotario/vitepress-openapi/runs/31262670265"><code>092d733</code></a>_

coderabbitai[bot]: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- This is an auto-generated comment: review in progress by coderabbit.ai -->

> [!NOTE]
> Currently processing new changes in this PR. This may take a few minutes, please wait...
> 
> 	<details>
> <summary>📥 Commits</summary>
> 
> Files that changed from the base of the PR and between f3bccd3b5c377cd5f79ad33163d5223b62036539 and 092d733816c3f1212dd695b37d3e8f569e28c36d.
> 
> </details>
> 
> <details>
> <summary>📒 Files selected for processing (7)</summary>
> 
> * src/components/Response/OAResponse.vue (1 hunks)
> * src/components/Schema/OASchemaBody.vue (1 hunks)
> * src/lib/generateSchemaJson.ts (1 hunks)
> * src/locales/en.json (1 hunks)
> * src/locales/es.json (1 hunks)
> * test/lib/generateSchemaJson.test.ts (2 hunks)
> * test/testsConstants.ts (1 hunks)
> 
> </details>
> 
> 	```ascii
>  __________________________________________________________________
> < You had me at 'Hello, World!' But I'm staying for the bug fixes. >
>  ------------------------------------------------------------------
>   \
>    \   \
>         \ /\
>         ( )
>       .( o ).
> ```

<!-- end of auto-generated comment: review in progress by coderabbit.ai --><!-- tips_start -->

---

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?

<details>
<summary>❤️ Share</summary>

- [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai)
- [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai)
- [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai)
- [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)

</details>

<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai):

- 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->

Patch:
diff --git a/docs/layouts/custom-slots.md b/docs/layouts/custom-slots.md
index c48697d..8ec8e5f 100644
--- a/docs/layouts/custom-slots.md
+++ b/docs/layouts/custom-slots.md
@@ -61,7 +61,7 @@ const route = useRoute()
 const { isDark } = useData()
 </script>
 
-<OAOperation operationId="getMuseumHours" :isDark="isDark">
+<OAOperation operationId="getAllData" :isDark="isDark">
 
 <template #description="description">
 
diff --git a/docs/public/openapi-scalar-galaxy.json b/docs/public/openapi-scalar-galaxy.json
index 3bc1d25..eee4b9a 100644
--- a/docs/public/openapi-scalar-galaxy.json
+++ b/docs/public/openapi-scalar-galaxy.json
@@ -2,7 +2,7 @@
   "openapi": "3.1.0",
   "info": {
     "title": "Scalar Galaxy",
-    "description": "The Scalar Galaxy is an example OpenAPI specification to test OpenAPI tools and libraries. It’s a fictional universe with fictional planets and fictional data. Get all the data for [all planets](#tag/planets/GET/planets).\n\n## Resources\n\n* https://github.com/scalar/scalar\n* https://github.com/OAI/OpenAPI-Specification\n* https://scalar.com\n\n## Markdown Support\n\nAll descriptions *can* contain ~~tons of text~~ **Markdown**. [If GitHub supports the syntax](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax), chances are we’re supporting it, too. You can even create [internal links to reference endpoints](#tag/authentication/POST/user/signup).\n\n<details>\n  <summary>Examples</summary>\n\n  **Blockquotes**\n\n  > I love OpenAPI. <3\n\n  **Tables**\n\n  | Feature          | Availability |\n  | ---------------- | ------------ |\n  | Markdown Support | ✓            |\n\n  **Accordion**\n\n  ```html\n  <details>\n    <summary>Using Details Tags</summary>\n    <p>HTML Example</p>\n  </details>\n  ```\n\n  **Images**\n\n  Yes, there’s support for images, too!\n\n  ![Empty placeholder image showing the width/height](https://images.placeholders.dev/?width=1280&height=720)\n\n</details>\n",
+    "description": "The Scalar Galaxy is an example OpenAPI specification to test OpenAPI tools and libraries. It’s a fictional universe with fictional planets and fictional data. Get all the data for [all planets](#tag/planets/GET/planets).\n\n## Resources\n\n* https://github.com/scalar/scalar\n* https://github.com/OAI/OpenAPI-Specification\n* https://scalar.com\n\n## Markdown Support\n\nAll descriptions *can* contain ~~tons of text~~ **Markdown**. [If GitHub supports the syntax](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax), chances are we’re supporting it, too. You can even create [internal links to reference endpoints](#createUser).\n\n<details>\n  <summary>Examples</summary>\n\n  **Blockquotes**\n\n  > I love OpenAPI. <3\n\n  **Tables**\n\n  | Feature          | Availability |\n  | ---------------- | ------------ |\n  | Markdown Support | ✓            |\n\n  **Accordion**\n\n  ```html\n  <details>\n    <summary>Using Details Tags</summary>\n    <p>HTML Example</p>\n  </details>\n  ```\n\n  **Images**\n\n  Yes, there’s support for images, too!\n\n  ![Empty placeholder image showing the width/height](https://images.placeholders.dev/?width=1280&height=720)\n\n</details>\n",
     "version": "1.0.0",
     "contact": {
       "name": "Marc from Scalar",
diff --git a/package.json b/package.json
index d4b4ef7..b6c6f11 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
 {
   "name": "vitepress-openapi",
   "type": "module",
-  "version": "0.0.3-alpha.36",
+  "version": "0.0.3-alpha.37",
   "packageManager": "pnpm@9.1.1",
   "homepage": "https://vitepress-openapi.vercel.app/",
   "repository": {
diff --git a/src/components/Common/OAHeading.vue b/src/components/Common/OAHeading.vue
index ed9f181..414f442 100644
--- a/src/components/Common/OAHeading.vue
+++ b/src/components/Common/OAHeading.vue
@@ -5,6 +5,10 @@ import { useTheme } from 'vitepress-openapi'
 import { cn } from '../../lib/utils'
 
 const props = defineProps({
+  id: {
+    type: String,
+    required: false,
+  },
   level: {
     type: String,
     required: true,
@@ -46,6 +50,10 @@ const slotText = computed(() => {
 })
 
 const id = computed(() => {
+  if (props.id) {
+    return props.id
+  }
+
   const value = props.prefix ? `${props.prefix}-${slotText.value}` : slotText.value
 
   return slugify(value, { decamelize: false })
diff --git a/src/components/Common/OAOperation.vue b/src/components/Common/OAOperation.vue
index 5db93b1..10e0c7d 100644
--- a/src/components/Common/OAOperation.vue
+++ b/src/components/Common/OAOperation.vue
@@ -67,8 +67,8 @@ function hasSlot(name) {
         />
 
         <OAHeading
+          :id="headingPrefix"
           level="h1"
-          :prefix="headingPrefix"
           :class="{
             'line-through': header.deprecated,
           }"
diff --git a/src/components/Response/OAResponse.vue b/src/components/Response/OAResponse.vue
index 9dd0825..958eec4 100644
--- a/src/components/Response/OAResponse.vue
+++ b/src/components/Response/OAResponse.vue
@@ -49,7 +49,9 @@ const contentTypeId = `content-type-${Math.random().toString(36).substring(7)}`
       <Label
         :for="contentTypeId"
         class="flex-shrink-0 text-gray-600 dark:text-gray-400"
-      >Content-Type</Label>
+      >
+        {{ $t('Content-Type') }}
+      </Label>
       <div class="flex-shrink-0">
         <Select
           :id="contentTypeId"
diff --git a/src/components/Schema/OASchemaBody.vue b/src/components/Schema/OASchemaBody.vue
index 9462a54..1de99af 100644
--- a/src/components/Schema/OASchemaBody.vue
+++ b/src/components/Schema/OASchemaBody.vue
@@ -36,6 +36,15 @@ if (!isCircularRef) {
       <OASchemaPrimitiveProperty :property="props.schema" />
     </div>
 
+    <div v-else-if="props.schema?.content && Object.keys(props.schema.content).length === 1">
+      <OASchemaBody
+        :schema="Object.values(props.schema.content)[0].schema"
+        :deep="props.deep - 1"
+        :visited="new Set(visited)"
+        :level="level + 1"
+      />
+    </div>
+
     <div
       v-else-if="props.schema?.properties"
       class="flex flex-col pl-2 space-y-2 border-l border-l-solid"
diff --git a/src/lib/generateSchemaJson.ts b/src/lib/generateSchemaJson.ts
index 8764528..f9869a7 100644
--- a/src/lib/generateSchemaJson.ts
+++ b/src/lib/generateSchemaJson.ts
@@ -24,6 +24,12 @@ export function propertiesTypesJsonRecursive(schema: any, useExample = false, vi
 
   visited.add(schema)
 
+  if (schema?.content) {
+    const contentTypesKeys = Object.keys(schema.content)
+    const contentType = contentTypesKeys.find(key => key !== 'application/json') || contentTypesKeys.find(Boolean)
+    return propertiesTypesJsonRecursive(schema.content[contentType].schema, useExample, new Set(visited), level)
+  }
+
   if (schema?.items) {
     return [getPropertyValue(schema.items, useExample, new Set(visited), level + 1)]
   }
diff --git a/src/locales/en.json b/src/locales/en.json
index f1bd4f4..93b8780 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -34,5 +34,6 @@
   "Unrecognized response type. Raw content:": "Unrecognized response type. Raw content:",
   "Download file": "Download file",
   "Select...": "Select...",
-  "operation.badgePrefix.operationId": "ID: "
+  "operation.badgePrefix.operationId": "ID: ",
+  "Content-Type": "Content-Type"
 }
diff --git a/src/locales/es.json b/src/locales/es.json
index e49a1f3..d5bdd37 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -34,5 +34,6 @@
   "Unrecognized response type. Raw content:": "Tipo de respuesta no reconocido. Contenido en crudo:",
   "Download file": "Descargar archivo",
   "Select...": "Seleccionar...",
-  "operation.badgePrefix.operationId": "ID: "
+  "operation.badgePrefix.operationId": "ID: ",
+  "Content-Type": "Content-Type"
 }


Test patch:
diff --git a/test/lib/generateSchemaJson.test.ts b/test/lib/generateSchemaJson.test.ts
index 992d3a0..2591aa1 100644
--- a/test/lib/generateSchemaJson.test.ts
+++ b/test/lib/generateSchemaJson.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest'
 import { merge } from 'allof-merge'
 import { dereferenceSync } from '@trojs/openapi-dereference'
 import { generateSchemaJson } from '../../src/lib/generateSchemaJson'
-import { specWithCircularRef, specWithMultipleLevels } from '../testsConstants'
+import { specWithCircularRef, specWithMultipleLevels, specWithSchemaAndContentTypes } from '../testsConstants'
 import { formatJson } from '../../src/lib/formatJson'
 
 describe('generateSchemaJson', () => {
@@ -299,3 +299,18 @@ describe('schema with multiple levels', () => {
     )
   })
 })
+
+describe('schema with content types', () => {
+  it('generates JSON from schema with content types', () => {
+    const schema = dereferenceSync(merge(specWithSchemaAndContentTypes)).paths['/pets'].get.responses['400']
+    const result = generateSchemaJson(schema)
+    expect(result).toBe(
+      formatJson({
+        type: 'string',
+        title: 'string',
+        status: 0,
+        detail: 'string',
+      }),
+    )
+  })
+})
diff --git a/test/testsConstants.ts b/test/testsConstants.ts
index 47a95a6..5de48e5 100644
--- a/test/testsConstants.ts
+++ b/test/testsConstants.ts
@@ -479,3 +479,59 @@ export const specWithMultipleLevels = {
     },
   },
 }
+
+export const specWithSchemaAndContentTypes = {
+  openapi: '3.0.0',
+  info: {
+    title: 'API with Schema and Content Types',
+    version: '1.0.0',
+  },
+  paths: {
+    '/pets': {
+      get: {
+        summary: 'Get a list of pets',
+        operationId: 'getPets',
+        responses: {
+          400: {
+            description: 'Bad Request',
+            content: {
+              'application/json': {
+                schema: {
+                  type: 'object',
+                  description: 'RFC 7807 (https://datatracker.ietf.org/doc/html/rfc7807)',
+                  properties: {
+                    type: {
+                      type: 'string',
+                      examples: [
+                        'https://example.com/errors/generic-error',
+                      ],
+                    },
+                    title: {
+                      type: 'string',
+                      examples: [
+                        'Something went wrong here.',
+                      ],
+                    },
+                    status: {
+                      type: 'integer',
+                      format: 'int64',
+                      examples: [
+                        403,
+                      ],
+                    },
+                    detail: {
+                      type: 'string',
+                      examples: [
+                        'Unfortunately, we can’t provide further information.',
+                      ],
+                    },
+                  },
+                },
+              },
+            },
+          },
+        },
+      },
+    },
+  },
+}