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

Refactor OpenAPI examples code #2991

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 84 additions & 47 deletions packages/react-openapi/src/OpenAPICodeSample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,82 @@ import { OpenAPITabs, OpenAPITabsList, OpenAPITabsPanels } from './OpenAPITabs';
import { ScalarApiButton } from './ScalarApiButton';
import { StaticSection } from './StaticSection';
import { type CodeSampleInput, codeSampleGenerators } from './code-samples';
import { generateMediaTypeExample, generateSchemaExample } from './generateSchemaExample';
import { generateMediaTypeExamples, generateSchemaExample } from './generateSchemaExample';
import { stringifyOpenAPI } from './stringifyOpenAPI';
import type { OpenAPIContextProps, OpenAPIOperationData } from './types';
import { getDefaultServerURL } from './util/server';
import { checkIsReference, createStateKey } from './utils';

const CUSTOM_CODE_SAMPLES_KEYS = ['x-custom-examples', 'x-code-samples', 'x-codeSamples'] as const;

/**
* Display code samples to execute the operation.
* It supports the Redocly custom syntax as well (https://redocly.com/docs/api-reference-docs/specification-extensions/x-code-samples/)
*/
export function OpenAPICodeSample(props: {
data: OpenAPIOperationData;
context: OpenAPIContextProps;
}) {
const { data } = props;

// If code samples are disabled at operation level, we don't display the code samples.
if (data.operation['x-codeSamples'] === false) {
return null;
}

const customCodeSamples = getCustomCodeSamples(props);

// If code samples are disabled at the top-level and not custom code samples are defined,
// we don't display the code samples.
if (data['x-codeSamples'] === false && !customCodeSamples) {
return null;
}

const samples = customCodeSamples ?? generateCodeSamples(props);

if (samples.length === 0) {
return null;
}

return (
<OpenAPITabs stateKey={createStateKey('codesample')} items={samples}>
<StaticSection header={<OpenAPITabsList />} className="openapi-codesample">
<OpenAPITabsPanels />
</StaticSection>
</OpenAPITabs>
);
}

function OpenAPICodeSampleFooter(props: {
data: OpenAPIOperationData;
context: OpenAPIContextProps;
}) {
const { data, context } = props;
const { method, path } = data;
const { specUrl } = context;
const hideTryItPanel = data['x-hideTryItPanel'] || data.operation['x-hideTryItPanel'];

if (hideTryItPanel) {
return null;
}

if (!validateHttpMethod(method)) {
return null;
}

return (
<div className="openapi-codesample-footer">
<ScalarApiButton method={method} path={path} specUrl={specUrl} />
</div>
);
}

/**
* Generate code samples for the operation.
*/
function generateCodeSamples(props: {
data: OpenAPIOperationData;
context: OpenAPIContextProps;
}) {
const { data, context } = props;

Expand Down Expand Up @@ -56,13 +119,17 @@ export function OpenAPICodeSample(props: {
: undefined;
const requestBodyContent = requestBodyContentEntries?.[0];

const requestBodyExamples = requestBodyContent
? generateMediaTypeExamples(requestBodyContent[1])
: [];

const input: CodeSampleInput = {
url:
getDefaultServerURL(data.servers) +
data.path +
(searchParams.size ? `?${searchParams.toString()}` : ''),
method: data.method,
body: requestBodyContent ? generateMediaTypeExample(requestBodyContent[1]) : undefined,
body: requestBodyExamples[0]?.value,
headers: {
...getSecurityHeaders(data.securities),
...headersObject,
Expand All @@ -74,7 +141,7 @@ export function OpenAPICodeSample(props: {
},
};

const autoCodeSamples = codeSampleGenerators.map((generator) => ({
return codeSampleGenerators.map((generator) => ({
key: `default-${generator.id}`,
label: generator.label,
body: context.renderCodeBlock({
Expand All @@ -83,14 +150,24 @@ export function OpenAPICodeSample(props: {
}),
footer: <OpenAPICodeSampleFooter data={data} context={context} />,
}));
}

/**
* Get custom code samples for the operation.
*/
function getCustomCodeSamples(props: {
data: OpenAPIOperationData;
context: OpenAPIContextProps;
}) {
const { data, context } = props;

// Use custom samples if defined
let customCodeSamples: null | Array<{
key: string;
label: string;
body: React.ReactNode;
}> = null;
(['x-custom-examples', 'x-code-samples', 'x-codeSamples'] as const).forEach((key) => {

CUSTOM_CODE_SAMPLES_KEYS.forEach((key) => {
const customSamples = data.operation[key];
if (customSamples && Array.isArray(customSamples)) {
customCodeSamples = customSamples
Expand All @@ -102,7 +179,7 @@ export function OpenAPICodeSample(props: {
);
})
.map((sample, index) => ({
key: `redocly-${sample.lang}-${index}`,
key: `custom-sample-${sample.lang}-${index}`,
label: sample.label,
body: context.renderCodeBlock({
code: sample.source,
Expand All @@ -113,47 +190,7 @@ export function OpenAPICodeSample(props: {
}
});

// Code samples can be disabled at the top-level or at the operation level
// If code samples are defined at the operation level, it will override the top-level setting
const codeSamplesDisabled =
data['x-codeSamples'] === false || data.operation['x-codeSamples'] === false;
const samples = customCodeSamples ?? (!codeSamplesDisabled ? autoCodeSamples : []);

if (samples.length === 0) {
return null;
}

return (
<OpenAPITabs stateKey={createStateKey('codesample')} items={samples}>
<StaticSection header={<OpenAPITabsList />} className="openapi-codesample">
<OpenAPITabsPanels />
</StaticSection>
</OpenAPITabs>
);
}

function OpenAPICodeSampleFooter(props: {
data: OpenAPIOperationData;
context: OpenAPIContextProps;
}) {
const { data, context } = props;
const { method, path } = data;
const { specUrl } = context;
const hideTryItPanel = data['x-hideTryItPanel'] || data.operation['x-hideTryItPanel'];

if (hideTryItPanel) {
return null;
}

if (!validateHttpMethod(method)) {
return null;
}

return (
<div className="openapi-codesample-footer">
<ScalarApiButton method={method} path={path} specUrl={specUrl} />
</div>
);
return customCodeSamples;
}

function getSecurityHeaders(securities: OpenAPIOperationData['securities']): {
Expand Down
1 change: 1 addition & 0 deletions packages/react-openapi/src/OpenAPIResponseExample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ function OpenAPIResponseMediaType(props: {
}) {
const { mediaTypeObject, mediaType } = props;
const examples = getExamplesFromMediaTypeObject({ mediaTypeObject, mediaType });
console.log(examples, mediaType);
const syntax = getSyntaxFromMediaType(mediaType);
const firstExample = examples[0];

Expand Down
31 changes: 20 additions & 11 deletions packages/react-openapi/src/generateSchemaExample.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
import { getExampleFromSchema } from '@scalar/oas-utils/spec-getters';
import { checkIsReference } from './utils';

type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };

Expand Down Expand Up @@ -42,27 +43,35 @@ export function generateSchemaExample(
/**
* Generate an example for a media type.
*/
export function generateMediaTypeExample(
export function generateMediaTypeExamples(
mediaType: OpenAPIV3.MediaTypeObject,
options?: GenerateSchemaExampleOptions
): JSONValue | undefined {
): OpenAPIV3.ExampleObject[] {
if (mediaType.example) {
return mediaType.example;
return [{ summary: 'default', value: mediaType.example }];
}

if (mediaType.examples) {
const key = Object.keys(mediaType.examples)[0];
if (key) {
const example = mediaType.examples[key];
if (example) {
return example.value;
}
const { examples } = mediaType;
const keys = Object.keys(examples);
if (keys.length > 0) {
return keys.reduce<OpenAPIV3.ExampleObject[]>((result, key) => {
const example = examples[key];
if (!example || checkIsReference(example)) {
return result;
}
result.push({
summary: example.summary || key,
value: example.value,
});
return result;
}, []);
}
}

if (mediaType.schema) {
return generateSchemaExample(mediaType.schema, options);
return [{ summary: 'default', value: generateSchemaExample(mediaType.schema, options) }];
}

return undefined;
return [];
}
4 changes: 1 addition & 3 deletions packages/react-openapi/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { AnyObject, OpenAPIV3, OpenAPIV3_1 } from '@gitbook/openapi-parser';
import { stringifyOpenAPI } from './stringifyOpenAPI';

export function checkIsReference(
input: unknown
): input is OpenAPIV3.ReferenceObject | OpenAPIV3_1.ReferenceObject {
export function checkIsReference(input: unknown): input is OpenAPIV3.ReferenceObject {
return typeof input === 'object' && !!input && '$ref' in input;
}

Expand Down