diff --git a/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.test.ts b/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.test.ts new file mode 100644 index 000000000..697a2e2c1 --- /dev/null +++ b/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.test.ts @@ -0,0 +1,57 @@ +/* ============================================================================ + * Copyright (c) Palo Alto Networks + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * ========================================================================== */ + +import { sampleFromSchema } from "./createSchemaExample"; +import { SchemaObject } from "./types"; + +describe("sampleFromSchema", () => { + describe("const support", () => { + it("should return default string value when const is not present", () => { + const schema: SchemaObject = { + type: "string", + }; + const context = { type: "request" as const }; + + const result = sampleFromSchema(schema, context); + + expect(result).toBe("string"); + }); + + it("should return const value when const is present", () => { + const schema: SchemaObject = { + type: "string", + const: "example", + }; + const context = { type: "request" as const }; + + const result = sampleFromSchema(schema, context); + + expect(result).toBe("example"); + }); + + it("should handle anyOf with const values", () => { + const schema: SchemaObject = { + type: "string", + anyOf: [ + { + type: "string", + const: "dog", + }, + { + type: "string", + const: "cat", + }, + ], + }; + const context = { type: "request" as const }; + + const result = sampleFromSchema(schema, context); + + expect(result).toBe("dog"); + }); + }); +}); diff --git a/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.ts b/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.ts index ea0ddcf0c..9fbd1434b 100644 --- a/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.ts +++ b/packages/docusaurus-plugin-openapi-docs/src/openapi/createSchemaExample.ts @@ -111,7 +111,16 @@ export const sampleFromSchema = ( try { // deep copy schema before processing let schemaCopy = JSON.parse(JSON.stringify(schema)); - let { type, example, allOf, properties, items, oneOf, anyOf } = schemaCopy; + let { + type, + example, + allOf, + properties, + items, + oneOf, + anyOf, + const: constant, + } = schemaCopy; if (example !== undefined) { return example; @@ -218,6 +227,10 @@ export const sampleFromSchema = ( return undefined; } + if (constant) { + return constant; + } + return primitive(schemaCopy); } catch (err) { console.error(