1 import { OpenAPI } from "types"
2 import type { JSONSchema7 } from "json-schema"
3 import stringify from "json-stringify-pretty-compact"
4 import { sample } from "openapi-sampler"
5
6 export type GenerateSchemaExamplesOptions = {
7 schema?: OpenAPI.SchemaObject
8 schemaExamples?: OpenAPI.OpenAPIV3.ExampleObject
9 schemaExample?: any
10 options?: {
11 skipNonRequired?: boolean
12 }
13 }
14
15 /**
16 * Pure (non-hook) generator of schema examples, shared by the client
17 * `use-schema-example` hook and the server-side Markdown converters. Produces
18 * the same `ExampleObject[]` the UI renders in code blocks.
19 */
20 export default function generateSchemaExamples({
21 schema,
22 schemaExamples,
23 schemaExample,
24 options = {},
25 }: GenerateSchemaExamplesOptions): OpenAPI.ExampleObject[] {
26 const { skipNonRequired = true } = options
27 const tempExamples: OpenAPI.ExampleObject[] = []
28
29 if (!schema) {
30 return tempExamples
31 }
32
33 if (schemaExamples) {
34 Object.entries(schemaExamples).forEach(([value, example]) => {
35 if ("$ref" in example) {
36 return
37 }
38
39 tempExamples.push({
40 title: example.summary || "",
41 value,
42 content: stringify(example.value, {
43 maxLength: 50,
44 }),
45 })
46 })
47 } else if (schemaExample) {
48 tempExamples.push({
49 title: "",
50 value: "",
51 content: stringify(schemaExample, {
52 maxLength: 50,
53 }),
54 })
55 } else {
56 const contentSample = stringify(
57 sample(
58 {
59 ...schema,
60 } as JSONSchema7,
61 {
62 skipNonRequired,
63 }
64 ),
65 {
66 maxLength: 50,
67 }
68 )
69
70 tempExamples.push({
71 title: "",
72 value: "",
73 content: contentSample,
74 })
75 }
76
77 return tempExamples
78 }