Skip to content

Commit

Permalink
Render mandatory headers in the code sample (#2445)
Browse files Browse the repository at this point in the history
  • Loading branch information
vibhanshub authored Sep 6, 2024
1 parent 13c7534 commit a679e72
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/ten-carpets-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---

Render mandatory headers in code sample
18 changes: 17 additions & 1 deletion packages/react-openapi/src/OpenAPICodeSample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react';

import { CodeSampleInput, codeSampleGenerators } from './code-samples';
import { OpenAPIOperationData, toJSON } from './fetchOpenAPIOperation';
import { generateMediaTypeExample } from './generateSchemaExample';
import { generateMediaTypeExample, generateSchemaExample } from './generateSchemaExample';
import { InteractiveSection } from './InteractiveSection';
import { getServersURL } from './OpenAPIServerURL';
import { ScalarApiButton } from './ScalarApiButton';
Expand All @@ -19,6 +19,21 @@ export function OpenAPICodeSample(props: {
}) {
const { data, context } = props;

const requiredHeaders = data.operation.parameters
?.map(noReference)
.filter((param) => param.in === 'header' && param.required);

const headersObject: { [k: string]: string } = {};
requiredHeaders?.forEach((header) => {
const example = header.schema
? generateSchemaExample(noReference(header.schema))
: undefined;
if (example !== undefined) {
headersObject[header.name] =
typeof example !== 'string' ? JSON.stringify(example) : example;
}
});

const requestBody = noReference(data.operation.requestBody);
const requestBodyContent = requestBody ? Object.entries(requestBody.content)[0] : undefined;

Expand All @@ -30,6 +45,7 @@ export function OpenAPICodeSample(props: {
: undefined,
headers: {
...getSecurityHeaders(data.securities),
...headersObject,
...(requestBodyContent
? {
'Content-Type': requestBodyContent[0],
Expand Down

0 comments on commit a679e72

Please sign in to comment.