-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathgenerateSchemaExample.ts
77 lines (70 loc) · 2.43 KB
/
generateSchemaExample.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import type { OpenAPIV3 } from '@gitbook/openapi-parser';
import { getExampleFromSchema } from '@scalar/oas-utils/spec-getters';
import { checkIsReference } from './utils';
type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue };
type ScalarGetExampleFromSchemaOptions = NonNullable<Parameters<typeof getExampleFromSchema>[1]>;
type GenerateSchemaExampleOptions = Pick<
ScalarGetExampleFromSchemaOptions,
'xml' | 'omitEmptyAndOptionalProperties' | 'mode'
>;
/**
* Generate a JSON example from a schema
*/
export function generateSchemaExample(
schema: OpenAPIV3.SchemaObject,
options?: GenerateSchemaExampleOptions
): JSONValue | undefined {
return getExampleFromSchema(
schema,
{
emptyString: 'text',
variables: {
'date-time': new Date().toISOString(),
date: new Date().toISOString().split('T')[0],
email: '[email protected]',
hostname: 'example.com',
ipv4: '0.0.0.0',
ipv6: '2001:0db8:85a3:0000:0000:8a2e:0370:7334',
uri: 'https://example.com',
uuid: '123e4567-e89b-12d3-a456-426614174000',
binary: 'binary',
byte: 'Ynl0ZXM=',
password: 'password',
},
...options,
},
3 // Max depth for circular references
);
}
/**
* Generate an example for a media type.
*/
export function generateMediaTypeExamples(
mediaType: OpenAPIV3.MediaTypeObject,
options?: GenerateSchemaExampleOptions
): OpenAPIV3.ExampleObject[] {
if (mediaType.example) {
return [{ summary: 'default', value: mediaType.example }];
}
if (mediaType.examples) {
const { examples } = mediaType;
const keys = Object.keys(examples);
if (keys.length > 0) {
return keys.reduce<OpenAPIV3.ExampleObject[]>((result, key) => {
const example = examples[key];
if (!example || checkIsReference(example)) {
return result;
}
result.push({
summary: example.summary || key,
value: example.value,
});
return result;
}, []);
}
}
if (mediaType.schema) {
return [{ summary: 'default', value: generateSchemaExample(mediaType.schema, options) }];
}
return [];
}