fumadocs-openapi
Version:
Generate MDX docs for your OpenAPI spec
64 lines (63 loc) • 2.16 kB
JavaScript
import { getPreferredType } from '../../utils/schema.js';
import { sample } from 'openapi-sampler';
export function getRequestData(path, method, sampleKey, _ctx) {
const result = {
path: {},
cookie: {},
header: {},
query: {},
method: method.method,
};
for (const param of method.parameters ?? []) {
let schema = param.schema;
let value;
if (!schema && param.content) {
const type = getPreferredType(param.content);
const content = type ? param.content[type] : undefined;
if (!content)
throw new Error(`Cannot find parameter schema for ${param.name} in ${path} ${method.method}`);
schema = content.schema;
value = content.example ?? param.example ?? sample(schema);
}
else {
value = param.example ?? sample(schema);
}
if (param.in === 'cookie') {
result.cookie[param.name] = value;
}
else if (param.in === 'header') {
result.header[param.name] = value;
}
else if (param.in === 'query') {
result.query[param.name] = value;
}
else if (param.in === 'path') {
result.path[param.name] = value;
}
}
if (method.requestBody) {
const body = method.requestBody.content;
const type = getPreferredType(body);
if (!type)
throw new Error(`Cannot find body schema for ${path} ${method.method}: missing media type`);
result.bodyMediaType = type;
const bodyOfType = body[type];
if (bodyOfType.examples && sampleKey) {
result.body = bodyOfType.examples[sampleKey].value;
}
else if (bodyOfType.example) {
result.body = bodyOfType.example;
}
else {
result.body = generateBody(method.method, (bodyOfType?.schema ?? {}));
}
}
return result;
}
function generateBody(method, schema) {
return sample(schema, {
skipReadOnly: method !== 'GET',
skipWriteOnly: method === 'GET',
skipNonRequired: true,
});
}