MCPcopy
hub / github.com/GitbookIO/gitbook / generateCodeSamples

Function generateCodeSamples

packages/react-openapi/src/OpenAPICodeSample.tsx:64–196  ·  view source on GitHub ↗

* Generate code samples for the operation.

(props: {
    data: OpenAPIOperationData;
    context: OpenAPIContext;
})

Source from the content-addressed store, hash-verified

62 * Generate code samples for the operation.
63 */
64function generateCodeSamples(props: {
65 data: OpenAPIOperationData;
66 context: OpenAPIContext;
67}) {
68 const { data, context } = props;
69
70 const searchParams = new URLSearchParams();
71 const headersObject: { [k: string]: string } = {};
72
73 // The parser can sometimes returns invalid parameters (an object instead of an array).
74 // It should get fixed in scalar, but in the meantime we just ignore the parameters in that case.
75 const params = Array.isArray(data.operation.parameters) ? data.operation.parameters : [];
76
77 params.forEach((param) => {
78 if (!param) {
79 return;
80 }
81
82 if (param.in === 'header' && param.required) {
83 const example = param.schema
84 ? generateSchemaExample(param.schema, { mode: 'write' })
85 : undefined;
86 if (example !== undefined && param.name) {
87 headersObject[param.name] =
88 typeof example !== 'string' ? stringifyOpenAPI(example) : example;
89 }
90 } else if (param.in === 'query' && param.required) {
91 const example = param.schema
92 ? generateSchemaExample(param.schema, { mode: 'write' })
93 : undefined;
94 if (example !== undefined && param.name) {
95 searchParams.append(
96 param.name,
97 String(Array.isArray(example) ? example[0] : example)
98 );
99 }
100 }
101 });
102
103 const requestBody = !checkIsReference(data.operation.requestBody)
104 ? data.operation.requestBody
105 : undefined;
106
107 const defaultServerUrl = getDefaultServerURL(data.servers);
108 let serverUrlPath = defaultServerUrl ? parseHostAndPath(defaultServerUrl).path : '';
109 serverUrlPath = serverUrlPath === '/' ? '' : serverUrlPath;
110 const serverUrl = data.servers[0]
111 ? resolveURLWithPrefillCodePlaceholdersFromServer(data.servers[0], defaultServerUrl)
112 : defaultServerUrl;
113 const serverUrlOrigin = serverUrl.replaceAll(serverUrlPath, '');
114 const path =
115 serverUrlPath + data.path + (searchParams.size ? `?${searchParams.toString()}` : '');
116
117 const genericHeaders = {
118 ...getSecurityHeaders({
119 securityRequirement: data.operation.security,
120 securities: data.securities,
121 }),

Callers 1

OpenAPICodeSampleFunction · 0.85

Calls 10

generateSchemaExampleFunction · 0.90
stringifyOpenAPIFunction · 0.90
checkIsReferenceFunction · 0.90
getDefaultServerURLFunction · 0.90
parseHostAndPathFunction · 0.90
getSecurityHeadersFunction · 0.85
toStringMethod · 0.80
generateMethod · 0.65

Tested by

no test coverage detected