From 6e54a06d9c0bebf32b97c0ababa9b11e135064c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=20Berg=C3=A9?= Date: Fri, 31 Jan 2025 18:47:29 +0100 Subject: [PATCH] Support response examples in API blocks (#2799) --- .changeset/chilly-readers-tap.md | 5 ++ .../src/OpenAPIResponseExample.tsx | 62 +++++++++++++------ 2 files changed, 47 insertions(+), 20 deletions(-) create mode 100644 .changeset/chilly-readers-tap.md diff --git a/.changeset/chilly-readers-tap.md b/.changeset/chilly-readers-tap.md new file mode 100644 index 000000000..09b78c7d8 --- /dev/null +++ b/.changeset/chilly-readers-tap.md @@ -0,0 +1,5 @@ +--- +'@gitbook/react-openapi': patch +--- + +Support response examples diff --git a/packages/react-openapi/src/OpenAPIResponseExample.tsx b/packages/react-openapi/src/OpenAPIResponseExample.tsx index e5588020f..bc5d793f6 100644 --- a/packages/react-openapi/src/OpenAPIResponseExample.tsx +++ b/packages/react-openapi/src/OpenAPIResponseExample.tsx @@ -5,6 +5,7 @@ import { generateSchemaExample } from './generateSchemaExample'; import { OpenAPIContextProps } from './types'; import { createStateKey, noReference } from './utils'; import { stringifyOpenAPI } from './stringifyOpenAPI'; +import { OpenAPIV3 } from '@scalar/openapi-types'; /** * Display an example of the response content. @@ -39,39 +40,60 @@ export function OpenAPIResponseExample(props: { }); const examples = responses - .map((response) => { - const responseObject = noReference(response[1]); + .map(([key, value]) => { + const responseObject = noReference(value); + const mediaTypeObject = (() => { + if (!responseObject.content) { + return null; + } + return ( + responseObject.content['application/json'] ?? + responseObject.content[Object.keys(responseObject.content)[0]] + ); + })(); - // TODO: unnecessary with https://github.com/GitbookIO/gitbook/pull/2780 - if (!responseObject) { + if (!mediaTypeObject) { return null; } - const schema = noReference( - ( - responseObject.content?.['application/json'] ?? - responseObject.content?.[Object.keys(responseObject.content)[0]] - )?.schema, + const example: OpenAPIV3.ExampleObject | null = noReference( + (() => { + const { examples, example } = mediaTypeObject; + if (examples) { + const firstKey = Object.keys(examples)[0]; + // @TODO handle multiple examples + const firstExample = noReference(examples[firstKey]); + if (firstExample) { + return firstExample; + } + } + + if (example) { + return { value: example }; + } + + const schema = noReference(mediaTypeObject.schema); + if (!schema) { + return null; + } + + return { value: generateSchemaExample(schema) }; + })(), ); - if (!schema) { - return null; - } - - const example = generateSchemaExample(schema); - if (example === undefined) { + if (!example?.value) { return null; } return { - key: `${response[0]}`, - label: `${response[0]}`, + key: key, + label: key, body: (