counterfact
Version:
Generate a TypeScript-based mock server from an OpenAPI spec in seconds — with stateful routes, hot reload, and REPL support.
50 lines (49 loc) • 1.66 kB
JavaScript
/**
* Builds a JSDoc comment string from OpenAPI schema metadata.
* Returns an empty string if there is no relevant metadata.
*/
export function buildJsDoc(data) {
if (typeof data !== "object" || data === null) {
return "";
}
const record = data;
const lines = [];
const description = record["description"];
const summary = record["summary"];
const example = record["example"];
const examples = record["examples"];
const defaultValue = record["default"];
const format = record["format"];
const deprecated = record["deprecated"];
const mainText = description ?? summary;
if (mainText) {
// Escape */ to prevent prematurely closing the JSDoc block
const escaped = String(mainText).replace(/\*\//gu, "* /");
const textLines = escaped.split("\n");
for (const line of textLines) {
lines.push(` * ${line}`);
}
}
if (format !== undefined) {
lines.push(` * @format ${format}`);
}
if (defaultValue !== undefined) {
lines.push(` * @default ${JSON.stringify(defaultValue)}`);
}
// Use scalar `example`, or fall back to the first value from `examples`
const exampleValue = example !== undefined
? example
: examples !== undefined
? Object.values(examples)[0]?.value
: undefined;
if (exampleValue !== undefined) {
lines.push(` * @example ${JSON.stringify(exampleValue)}`);
}
if (deprecated === true) {
lines.push(` * @deprecated`);
}
if (lines.length === 0) {
return "";
}
return `/**\n${lines.join("\n")}\n */\n`;
}