Skip to content

Commit 21222c0

Browse files
authored
feat: support const in example generation (#1260)
1 parent 756d016 commit 21222c0

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/* ============================================================================
2+
* Copyright (c) Palo Alto Networks
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
* ========================================================================== */
7+
8+
import { sampleFromSchema } from "./createSchemaExample";
9+
import { SchemaObject } from "./types";
10+
11+
describe("sampleFromSchema", () => {
12+
describe("const support", () => {
13+
it("should return default string value when const is not present", () => {
14+
const schema: SchemaObject = {
15+
type: "string",
16+
};
17+
const context = { type: "request" as const };
18+
19+
const result = sampleFromSchema(schema, context);
20+
21+
expect(result).toBe("string");
22+
});
23+
24+
it("should return const value when const is present", () => {
25+
const schema: SchemaObject = {
26+
type: "string",
27+
const: "example",
28+
};
29+
const context = { type: "request" as const };
30+
31+
const result = sampleFromSchema(schema, context);
32+
33+
expect(result).toBe("example");
34+
});
35+
36+
it("should handle anyOf with const values", () => {
37+
const schema: SchemaObject = {
38+
type: "string",
39+
anyOf: [
40+
{
41+
type: "string",
42+
const: "dog",
43+
},
44+
{
45+
type: "string",
46+
const: "cat",
47+
},
48+
],
49+
};
50+
const context = { type: "request" as const };
51+
52+
const result = sampleFromSchema(schema, context);
53+
54+
expect(result).toBe("dog");
55+
});
56+
});
57+
});

packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,16 @@ export const sampleFromSchema = (
111111
try {
112112
// deep copy schema before processing
113113
let schemaCopy = JSON.parse(JSON.stringify(schema));
114-
let { type, example, allOf, properties, items, oneOf, anyOf } = schemaCopy;
114+
let {
115+
type,
116+
example,
117+
allOf,
118+
properties,
119+
items,
120+
oneOf,
121+
anyOf,
122+
const: constant,
123+
} = schemaCopy;
115124

116125
if (example !== undefined) {
117126
return example;
@@ -218,6 +227,10 @@ export const sampleFromSchema = (
218227
return undefined;
219228
}
220229

230+
if (constant) {
231+
return constant;
232+
}
233+
221234
return primitive(schemaCopy);
222235
} catch (err) {
223236
console.error(

0 commit comments

Comments
 (0)