diff --git a/src/core/plugins/samples/fn.js b/src/core/plugins/samples/fn.js index a6988d2c1f6..04fad9f1020 100644 --- a/src/core/plugins/samples/fn.js +++ b/src/core/plugins/samples/fn.js @@ -346,7 +346,20 @@ export const sampleFromSchemaGeneric = (schema, config={}, exampleOverride = und if(!canAddProperty(propName)) { return } - res[propName] = sampleFromSchemaGeneric(props[propName], config, overrideE, respectXML) + if(Object.prototype.hasOwnProperty.call(schema, "discriminator") && + schema.discriminator && + Object.prototype.hasOwnProperty.call(schema.discriminator, "mapping") && + schema.discriminator.mapping && + schema.discriminator.propertyName === propName) { + for (let pair in schema.discriminator.mapping){ + if (schema.$$ref.search(schema.discriminator.mapping[pair]) !== -1) { + res[propName] = pair + break + } + } + } else { + res[propName] = sampleFromSchemaGeneric(props[propName], config, overrideE, respectXML) + } propertyAddedCounter++ } } diff --git a/test/unit/core/plugins/samples/fn.js b/test/unit/core/plugins/samples/fn.js index a456a4bf0f4..7bb04184ade 100644 --- a/test/unit/core/plugins/samples/fn.js +++ b/test/unit/core/plugins/samples/fn.js @@ -605,6 +605,74 @@ describe("sampleFromSchema", () => { }) }) + describe("discriminator mapping example", () => { + it("returns an example where discriminated field is equal to mapping value", () => { + let definition = { + "type": "array", + "items": { + "oneOf": [ + { + "required": [ + "type" + ], + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "TYPE1", + "TYPE2" + ] + } + }, + "discriminator": { + "propertyName": "type", + "mapping": { + "TYPE1": "#/components/schemas/FirstDto", + "TYPE2": "#/components/schemas/SecondDto" + } + }, + "$$ref": "examples/swagger-config.yaml#/components/schemas/FirstDto" + }, + { + "required": [ + "type" + ], + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "TYPE1", + "TYPE2" + ] + } + }, + "discriminator": { + "propertyName": "type", + "mapping": { + "TYPE1": "#/components/schemas/FirstDto", + "TYPE2": "#/components/schemas/SecondDto" + } + }, + "$$ref": "examples/swagger-config.yaml#/components/schemas/SecondDto" + } + ] + } + } + + let expected = [ + { + "type": "TYPE1" + }, { + "type": "TYPE2" + } + ] + + expect(sampleFromSchema(definition)).toEqual(expected) + }) + }) + it("should use overrideExample when defined", () => { const definition = { type: "object",